diff --git a/packages/create-void/src/main.ts b/packages/create-void/src/main.ts index c5488404c..c990a7a95 100644 --- a/packages/create-void/src/main.ts +++ b/packages/create-void/src/main.ts @@ -1,9 +1,9 @@ -import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'; import * as p from '@voidzero-dev/vite-plus-prompts'; import { resolve } from 'pathslash'; import pc from 'picocolors'; import { parseCreateArgs, validateProjectName } from './args.ts'; -import { detectPM, pmExec, pmInstall, run, writePnpmBuildPolicy } from './pm.ts'; +import { detectPM, runVoidInit } from './pm.ts'; const pm = detectPM(); @@ -50,29 +50,8 @@ async function main() { mkdirSync(targetDir, { recursive: true }); - const pkg = { - name: appName, - private: true, - type: 'module', - devDependencies: { - void: voidVersion, - }, - }; - - writeFileSync(resolve(targetDir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n'); - // pnpm 12 fails the first install when a dependency has an unapproved build - // script. Write Void's narrow policy before installing the CLI so a fresh - // project can bootstrap without disabling pnpm's build-script protection. - writePnpmBuildPolicy(targetDir, pm); - - p.log.step('Installing Void...'); - await run(pmInstall(pm), targetDir); - p.log.step('Scaffolding starter...'); - await run([...pmExec(pm), 'void', 'init', ...createArgs.initArgs], targetDir); - - p.log.step('Installing starter dependencies...'); - await run(pmInstall(pm), targetDir); + await runVoidInit(pm, voidVersion, createArgs.initArgs, targetDir); p.outro(`\n${pc.green(`✓ Created ${appName}`)}`, { withGuide: false }); p.outro(`cd ${appName} && ${pm === 'npm' ? 'npm run' : pm} dev`); diff --git a/packages/create-void/src/pm.ts b/packages/create-void/src/pm.ts index 0e1f2b285..bf1c65f42 100644 --- a/packages/create-void/src/pm.ts +++ b/packages/create-void/src/pm.ts @@ -1,24 +1,7 @@ import { spawn } from 'node:child_process'; -import { writeFileSync } from 'node:fs'; -import { join } from 'pathslash'; export type PM = 'npm' | 'pnpm' | 'yarn' | 'bun'; -const VOID_PNPM_ALLOWED_BUILDS = ['esbuild', 'sharp', 'workerd'] as const; - -/** Write the explicit build-script policy required by a new pnpm project. */ -export function writePnpmBuildPolicy(root: string, pm: PM): void { - if (pm !== 'pnpm') { - return; - } - writeFileSync( - join(root, 'pnpm-workspace.yaml'), - // better-sqlite3 13 ships Node-API binaries and declares gypfile:false. - // Match the repository policy instead of invoking pnpm's implicit rebuild. - `allowBuilds:\n better-sqlite3: false\n${VOID_PNPM_ALLOWED_BUILDS.map((name) => ` ${name}: true`).join('\n')}\n`, - ); -} - export function detectPM(): PM { const agent = process.env.npm_config_user_agent; if (agent) { @@ -54,6 +37,45 @@ export function pmExec(pm: PM): ReadonlyArray { } } +function isYarnClassic(userAgent = process.env.npm_config_user_agent): boolean { + return /^yarn\/1(?:\.|$)/.test(userAgent ?? ''); +} + +/** Run the matching Void CLI without adding it to the generated project. */ +export function pmDlx(pm: PM, version: string): ReadonlyArray { + const pkg = `void@${version}`; + switch (isYarnClassic() ? 'npm' : pm) { + case 'npm': + return ['npm', 'exec', '--yes', `--package=${pkg}`, '--', 'void']; + case 'pnpm': + return ['pnpm', 'dlx', pkg]; + case 'yarn': + return ['yarn', 'dlx', pkg]; + case 'bun': + return ['bunx', pkg]; + } +} + +export function pmInitCommand( + pm: PM, + version: string, + initArgs: ReadonlyArray, +): ReadonlyArray { + return [...pmDlx(pm, version), 'init', ...initArgs]; +} + +export type InitCommandRunner = (argv: ReadonlyArray, cwd?: string) => Promise; + +export function runVoidInit( + pm: PM, + version: string, + initArgs: ReadonlyArray, + cwd: string, + runner: InitCommandRunner = run, +): Promise { + return runner(pmInitCommand(pm, version, initArgs), cwd); +} + export function run(argv: ReadonlyArray, cwd?: string): Promise { return new Promise((resolve, reject) => { const [cmd, ...args] = argv; diff --git a/packages/create-void/test/unit/delegation.test.ts b/packages/create-void/test/unit/delegation.test.ts new file mode 100644 index 000000000..9bbf7f8f0 --- /dev/null +++ b/packages/create-void/test/unit/delegation.test.ts @@ -0,0 +1,90 @@ +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vite-plus/test'; +import { parseInitArgs, runInitCommand } from '../../../void/src/cli/init.ts'; +import { runVoidInit } from '../../src/pm.ts'; + +const VOID_VERSION = JSON.parse( + readFileSync(join(import.meta.dirname, '..', '..', 'package.json'), 'utf8'), +) as { version: string }; + +describe('create-void delegation', () => { + it('delegates to void init in a pnpm workspace member and forwards --no-install', async () => { + const root = mkdtempSync(join(tmpdir(), 'create-void-workspace-')); + try { + const appDirectory = join(root, 'apps', 'my-app'); + mkdirSync(appDirectory, { recursive: true }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'fixture', private: true })); + writeFileSync( + join(root, 'pnpm-workspace.yaml'), + [ + '# Keep this workspace comment', + 'packages:', + ' - apps/*', + 'allowBuilds:', + ' esbuild: false # Keep this approval decision', + ' custom-build: true', + '', + ].join('\n'), + ); + + let invoked = false; + await runVoidInit( + 'pnpm', + VOID_VERSION.version, + [ + '--toolchain', + 'vite', + '--framework', + 'react', + '--starter', + 'static', + '--deploy', + 'none', + '--no-install', + ], + appDirectory, + async (argv, cwd) => { + invoked = true; + expect(argv).toEqual([ + 'pnpm', + 'dlx', + `void@${VOID_VERSION.version}`, + 'init', + '--toolchain', + 'vite', + '--framework', + 'react', + '--starter', + 'static', + '--deploy', + 'none', + '--no-install', + ]); + expect(cwd).toBe(appDirectory); + await runInitCommand(cwd!, parseInitArgs(argv.slice(4))); + }, + ); + expect(invoked).toBe(true); + + expect(existsSync(join(appDirectory, 'package.json'))).toBe(true); + expect(existsSync(join(appDirectory, 'pages', 'index.tsx'))).toBe(true); + expect(existsSync(join(appDirectory, 'pnpm-workspace.yaml'))).toBe(false); + expect(existsSync(join(appDirectory, 'pnpm-lock.yaml'))).toBe(false); + expect(existsSync(join(appDirectory, 'package-lock.json'))).toBe(false); + expect(existsSync(join(appDirectory, 'node_modules'))).toBe(false); + + const updatedWorkspaceConfig = readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf8'); + expect(updatedWorkspaceConfig).toContain('# Keep this workspace comment'); + expect(updatedWorkspaceConfig).toContain('esbuild: false # Keep this approval decision'); + expect(updatedWorkspaceConfig).toContain('custom-build: true'); + expect(updatedWorkspaceConfig).toContain('better-sqlite3: false'); + expect(updatedWorkspaceConfig).toContain('sharp: true'); + expect(updatedWorkspaceConfig).toContain('workerd: true'); + expect(existsSync(join(root, 'pnpm-lock.yaml'))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/create-void/test/unit/pm.test.ts b/packages/create-void/test/unit/pm.test.ts index d0d1506fc..9901a3d1a 100644 --- a/packages/create-void/test/unit/pm.test.ts +++ b/packages/create-void/test/unit/pm.test.ts @@ -1,37 +1,77 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, describe, expect, it } from 'vite-plus/test'; -import { writePnpmBuildPolicy } from '../../src/pm.ts'; - -const temporaryDirectories: Array = []; - -afterEach(() => { - for (const directory of temporaryDirectories.splice(0)) { - rmSync(directory, { recursive: true, force: true }); - } -}); +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { detectPM, pmDlx, pmInitCommand } from '../../src/pm.ts'; -describe('create-void package manager bootstrap', () => { - it('writes the narrow Void build policy before a fresh pnpm install', () => { - const root = mkdtempSync(join(tmpdir(), 'create-void-pnpm-')); - temporaryDirectories.push(root); +describe('create-void package manager delegation', () => { + afterEach(() => vi.unstubAllEnvs()); - writePnpmBuildPolicy(root, 'pnpm'); + it.each([ + ['npm', ['npm', 'exec', '--yes', '--package=void@1.2.3', '--', 'void']], + ['pnpm', ['pnpm', 'dlx', 'void@1.2.3']], + ['yarn', ['yarn', 'dlx', 'void@1.2.3']], + ['bun', ['bunx', 'void@1.2.3']], + ] as const)('uses %s to execute the requested Void version', (pm, expected) => { + vi.stubEnv('npm_config_user_agent', ''); + expect(pmDlx(pm, '1.2.3')).toEqual(expected); + }); - expect(readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf-8')).toBe( - 'allowBuilds:\n better-sqlite3: false\n esbuild: true\n sharp: true\n workerd: true\n', - ); + it('uses npm exec for Yarn Classic, which does not provide dlx', () => { + vi.stubEnv('npm_config_user_agent', 'yarn/1.22.22 npm/? node/v24.22.1'); + expect(pmDlx('yarn', '1.2.3')).toEqual([ + 'npm', + 'exec', + '--yes', + '--package=void@1.2.3', + '--', + 'void', + ]); }); - it('does not add pnpm policy files for other package managers', () => { - for (const manager of ['npm', 'yarn', 'bun'] as const) { - const root = mkdtempSync(join(tmpdir(), `create-void-${manager}-`)); - temporaryDirectories.push(root); + it.each([ + ['npm', ['npm', 'exec', '--yes', '--package=void@1.2.3', '--', 'void', 'init']], + ['pnpm', ['pnpm', 'dlx', 'void@1.2.3', 'init']], + ['yarn', ['yarn', 'dlx', 'void@1.2.3', 'init']], + ['bun', ['bunx', 'void@1.2.3', 'init']], + ] as const)('builds the %s void init command', (pm, expected) => { + vi.stubEnv('npm_config_user_agent', ''); + expect(pmInitCommand(pm, '1.2.3', [])).toEqual(expected); + }); - writePnpmBuildPolicy(root, manager); + it('uses npm exec for void init under Yarn Classic', () => { + vi.stubEnv('npm_config_user_agent', 'yarn/1.22.22 npm/? node/v24.22.1'); + expect(pmInitCommand('yarn', '1.2.3', ['--no-install'])).toEqual([ + 'npm', + 'exec', + '--yes', + '--package=void@1.2.3', + '--', + 'void', + 'init', + '--no-install', + ]); + }); + + it('forwards init options, including --no-install, without adding a package install', () => { + const command = pmInitCommand('pnpm', '1.2.3', ['--framework', 'react', '--no-install']); + + expect(command).toEqual([ + 'pnpm', + 'dlx', + 'void@1.2.3', + 'init', + '--framework', + 'react', + '--no-install', + ]); + expect(command).not.toContain('install'); + }); - expect(existsSync(join(root, 'pnpm-workspace.yaml'))).toBe(false); - } + it.each([ + ['pnpm/10.0.0 npm/? node/v24.22.1', 'pnpm'], + ['npm/11.0.0 node/v24.22.1', 'npm'], + ['yarn/4.5.0 npm/? node/v24.22.1', 'yarn'], + ['bun/1.2.0', 'bun'], + ] as const)('detects %s from npm_config_user_agent', (userAgent, expected) => { + vi.stubEnv('npm_config_user_agent', userAgent); + expect(detectPM()).toBe(expected); }); }); diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 27a9f8449..4e696c70a 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -127,6 +127,7 @@ const HELP_TREE: HelpTree = { usage: ['void init [options]'], options: [ { command: '--tsconfig', description: 'Update tsconfig.json and set up coding agents' }, + { command: '--no-install', description: 'Skip installing dependencies after setup' }, { command: '--git', description: 'Initialize a Git repository without prompting' }, { command: '--no-git', description: 'Skip Git repository initialization' }, { command: '--toolchain ', description: 'Scaffold with vite-plus or vite' }, diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 423878108..7bb66323d 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -79,6 +79,7 @@ import { export type InitArgs = { tsconfig: boolean; github: boolean; + install?: boolean; git?: boolean; toolchain?: ScaffoldToolchain; framework?: ScaffoldFramework; @@ -116,6 +117,7 @@ export function parseInitArgs(args: Array): InitArgs { options: { tsconfig: { type: 'boolean' }, github: { type: 'boolean' }, + install: { type: 'boolean' }, git: { type: 'boolean' }, toolchain: { type: 'string' }, framework: { type: 'string' }, @@ -133,6 +135,7 @@ export function parseInitArgs(args: Array): InitArgs { return { tsconfig: parsed.values.tsconfig === true, github: parsed.values.github === true, + install: parsed.values.install as boolean | undefined, git: parsed.values.git as boolean | undefined, toolchain: parseChoice( 'toolchain', @@ -3155,7 +3158,14 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg : './node_modules/.bin/void' : projectVoidRunner[state.packageManager]; const manualMigration = `${voidRunner} db generate`; - if (scaffoldAddedDependencies) { + if (scaffoldAddedDependencies && initArgs?.install === false) { + const install = resolveProjectInstall(root, state.packageManager); + const manualInstall = commandInProject(root, install.manualCommand); + report.next(`Run \`${manualInstall}\` to install dependencies`); + if (migrationMode) { + report.next(`Then run \`${commandInProject(root, manualMigration)}\` to finish setup`); + } + } else if (scaffoldAddedDependencies) { const install = resolveProjectInstall(root, state.packageManager); const manualInstall = commandInProject(root, install.manualCommand); report.unfinished = migrationMode @@ -3169,7 +3179,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg const manualInstall = commandInProject(root, `${installer} install`); report.next(`Run \`${manualInstall}\` to update your lockfile`); } - if (migrationMode) { + if (migrationMode && initArgs?.install !== false) { report.unfinished = `Run \`${commandInProject(root, manualMigration)}\` to finish setup`; await generateStarterMigration(root, migrationMode); report.done('Generated the initial database migration'); @@ -3200,6 +3210,10 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg } } else { const devCommand = commandInProject(root, getDevCommand(root, framework)); - printSuccess(`Project initialized. Run \`${devCommand}\` to start developing.`); + printSuccess( + initArgs?.install === false && scaffoldAddedDependencies + ? 'Project initialized. Follow the next steps to finish setup.' + : `Project initialized. Run \`${devCommand}\` to start developing.`, + ); } } diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 592afd680..91e464b99 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -167,6 +167,43 @@ describe('init scaffold arguments', () => { expect(() => parseInitArgs(['--framework', 'angular'])).toThrow( 'init: --framework must be one of react, vue, svelte, solid.', ); + expect(parseInitArgs(['--no-install', '--no-git'])).toMatchObject({ + install: false, + git: false, + }); + }); + + it('scaffolds with --no-install without running the package manager install', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-no-install-')); + try { + await runInitCommand( + root, + parseInitArgs([ + '--toolchain', + 'vite', + '--framework', + 'react', + '--starter', + 'static', + '--deploy', + 'none', + '--no-install', + ]), + ); + + expect(existsSync(join(root, 'pages', 'index.tsx'))).toBe(true); + expect( + mockSpawnSync.mock.calls.filter(([, args]) => Array.isArray(args) && args[0] === 'install'), + ).toEqual([]); + expect(summaryMessages('→').join('\n')).toContain('npm install'); + expect( + summaryMessages('✓').some( + (message) => typeof message === 'string' && message.startsWith('Installed dependencies'), + ), + ).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } }); it('scaffolds from flags without prompting when stdin is not a terminal', async () => {