Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions packages/faustwp-cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/env node
import { spawnSync } from 'child_process';
import dotenv from 'dotenv-flow';
import { debugLog } from './stdout/index.js';
import { healthCheck } from './healthCheck/index.js';
import { generatePossibleTypes } from './generatePossibleTypes.js';
import { generateGlobalStylesheet } from './generateGlobalStylesheet.js';
import { blockset } from './blockset.js';
import { runNext } from './runNext.js';
import {
getCliArgs,
getNextCliArgs,
Expand Down Expand Up @@ -84,16 +84,5 @@ import { marshallTelemetryData, sendTelemetryData } from './telemetry/index.js';

printFaustVersion();

/**
* Spawn a child process using the args captured in argv and continue the
* standard i/o for the Next.js CLI.
*/
const nextjsCommand = process.platform === 'win32' ? 'next.cmd' : 'next';

process.exit(
spawnSync(nextjsCommand, getNextCliArgs(), {
stdio: 'inherit',
encoding: 'utf8',
})?.status as number | undefined,
);
process.exit(runNext(getNextCliArgs()));
})();
27 changes: 27 additions & 0 deletions packages/faustwp-cli/src/runNext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { spawnSync } from 'child_process';
import { errorLog } from './stdout/index.js';
import { getNextBinPath } from './utils/index.js';

/**
* Runs the Next.js CLI with the given args, inheriting standard i/o.
*
* @returns The exit code to exit Faust with.
*/
export function runNext(args: string[]): number {
const nextBinPath = getNextBinPath();

if (!nextBinPath) {
errorLog('Could not find Next.js. Make sure `next` is installed.');
return 1;
}

const result = spawnSync(process.execPath, [nextBinPath, ...args], {
stdio: 'inherit',
});

if (result.error) {
errorLog('Failed to start Next.js:', result.error);
}

return result.status ?? 1;
}
28 changes: 28 additions & 0 deletions packages/faustwp-cli/src/utils/getNextBinPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import fs from 'fs';
import { createRequire } from 'module';
import path from 'path';
import process from 'process';

/**
* Resolves the Next.js CLI script from the project's dependencies so it can
* be run with Node directly. Spawning `next.cmd` on Windows fails with EINVAL
* on Node versions patched for CVE-2024-27980.
*
* @returns The absolute path to the Next.js CLI script, or undefined if Next.js
* cannot be resolved.
*/
export const getNextBinPath = (cwd = process.cwd()) => {
try {
const pkgPath = createRequire(path.join(cwd, 'package.json')).resolve(
'next/package.json',
);
const { bin } = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as {
bin?: { next?: string };
};
const binPath = bin?.next;

return binPath ? path.resolve(path.dirname(pkgPath), binPath) : undefined;
} catch {
return undefined;
}
};
1 change: 1 addition & 0 deletions packages/faustwp-cli/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { getCliArgs } from './getCliArgs.js';
export { getNextCliArgs } from './getNextCliArgs.js';
export { getNextBinPath } from './getNextBinPath.js';
export { isDebug } from './isDebug.js';
export { getWpSecret } from './getWpSecret.js';
export {
Expand Down
59 changes: 59 additions & 0 deletions packages/faustwp-cli/tests/runNext/runNext.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { spawnSync, SpawnSyncReturns } from 'child_process';
jest.mock('child_process');
import { getNextBinPath } from '../../src/utils/getNextBinPath.js';
jest.mock('../../src/utils/getNextBinPath.js', () => ({
__esModule: true,
getNextBinPath: jest.fn(),
}));

import { runNext } from '../../src/runNext';

const spawnSyncMock = spawnSync as unknown as jest.Mock<
Partial<SpawnSyncReturns<Buffer>>
>;
const getNextBinPathMock = getNextBinPath as jest.Mock;

describe('runNext', () => {
beforeEach(() => {
jest.spyOn(console, 'log').mockImplementation(() => {});
getNextBinPathMock.mockReturnValue('/app/node_modules/next/dist/bin/next');
});

afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});

it('runs the Next.js CLI script with the current Node binary', () => {
spawnSyncMock.mockReturnValueOnce({ status: 0 });

expect(runNext(['dev', '-p', '4040'])).toBe(0);
expect(spawnSyncMock).toHaveBeenCalledWith(
process.execPath,
['/app/node_modules/next/dist/bin/next', 'dev', '-p', '4040'],
{ stdio: 'inherit' },
);
});

it("returns the Next.js CLI's exit code", () => {
spawnSyncMock.mockReturnValueOnce({ status: 2 });

expect(runNext(['build'])).toBe(2);
});

it('returns 1 when Next.js cannot be found', () => {
getNextBinPathMock.mockReturnValueOnce(undefined);

expect(runNext(['dev'])).toBe(1);
expect(spawnSyncMock).not.toHaveBeenCalled();
});

it('returns 1 when the process fails to start', () => {
spawnSyncMock.mockReturnValueOnce({
status: null,
error: new Error('spawnSync EINVAL'),
});

expect(runNext(['dev'])).toBe(1);
});
});
42 changes: 42 additions & 0 deletions packages/faustwp-cli/tests/utils/getNextBinPath.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { getNextBinPath } from '../../src/utils';

describe('utils/getNextBinPath', () => {
let cwd: string;

beforeEach(() => {
cwd = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'faust-cli-')));
});

afterEach(() => {
fs.rmSync(cwd, { recursive: true, force: true });
});

const installNext = (bin: unknown) => {
const nextDir = path.join(cwd, 'node_modules', 'next');
fs.mkdirSync(nextDir, { recursive: true });
fs.writeFileSync(
path.join(nextDir, 'package.json'),
JSON.stringify({ name: 'next', bin }),
);
return nextDir;
};

it('resolves the next bin', () => {
const nextDir = installNext({ next: './dist/bin/next' });

expect(getNextBinPath(cwd)).toBe(path.join(nextDir, 'dist', 'bin', 'next'));
});

it('returns undefined when next is not installed', () => {
expect(getNextBinPath(cwd)).toBeUndefined();
});

it('returns undefined when next has no bin', () => {
installNext(undefined);

expect(getNextBinPath(cwd)).toBeUndefined();
});
});
Loading