diff --git a/packages/void/src/cli/init-subprocess.ts b/packages/void/src/cli/init-subprocess.ts index 0148afce8..70eb9749e 100644 --- a/packages/void/src/cli/init-subprocess.ts +++ b/packages/void/src/cli/init-subprocess.ts @@ -12,6 +12,7 @@ import { statSync, } from 'node:fs'; import { constants, tmpdir } from 'node:os'; +import { stripVTControlCharacters } from 'node:util'; import { join } from 'pathslash'; import { createSpinner } from './output.ts'; @@ -191,6 +192,7 @@ export async function runBehindSpinner( /** Removes partial changes after a failure or interruption. */ undo?: () => void; }, + retryNpx?: (directory: string) => { args: Array; env: NodeJS.ProcessEnv } | undefined, ): Promise { const { failed, undo, ...spawnOptions } = options; const directory = mkdtempSync(join(tmpdir(), 'void-init-')); @@ -224,7 +226,7 @@ export async function runBehindSpinner( const startedAt = performance.now(); let status: number | null = null; try { - status = await new Promise((resolve, reject) => { + const run = (resolve: (status: number | null) => void, reject: (error: Error) => void) => { // Both writers share the same file offset. Inheriting a file instead // of a pipe lets init finish even if a background child keeps it open. const fd = openSync(path, 'wx'); @@ -239,7 +241,17 @@ export async function runBehindSpinner( } finally { closeSync(fd); } - }); + }; + status = await new Promise(run); + const mismatch = + /^(?:npm warn .*\r?\n)*npm error code EBADDEVENGINES\r?\n(?:npm error EBADDEVENGINES .*\r?\n)*npm error EBADDEVENGINES Invalid (?:devEngines\.packageManager|engine "packageManager")(?=\r?\n|$)/; + const output = status === 1 && command === 'npx' ? readFileSync(path, 'utf8') : ''; + const retry = mismatch.test(stripVTControlCharacters(output)) && retryNpx?.(directory); + if (retry) { + ({ args, env: spawnOptions.env } = retry); + rmSync(path); + status = await new Promise(run); + } } finally { if (status !== 0 && !progress.isCancelled && undo) { // A failed generator can still have children writing its outputs. diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index fa7ee1bfc..4bd910a9e 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -1,5 +1,5 @@ -import { spawnSync } from 'node:child_process'; -import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'; import { createRequire } from 'node:module'; import { parseArgs } from 'node:util'; import { isRecord } from '@void/deploy-core'; @@ -1969,12 +1969,51 @@ export function resolveProjectInstall( }; } +/** Write a recovery command that preserves npm's project and user configuration layers. */ +function writeNpxInstallRecovery(root: string, npmrc: string, args: Array): string { + const file = '.void/retry-npm-install.cjs'; + const path = join(root, file); + const script = `const { spawnSync } = require('node:child_process'); +const { copyFileSync, existsSync, mkdtempSync, rmSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join, resolve } = require('node:path'); + +const root = resolve(__dirname, '..'); +const npmrc = resolve(root, ${JSON.stringify(relative(root, npmrc))}); +const prefix = mkdtempSync(join(tmpdir(), 'void-init-')); +const { npm_config_workspace, NPM_CONFIG_WORKSPACE, ...env } = process.env; +const shell = process.platform === 'win32'; +const prefixArg = shell ? '"' + prefix + '"' : prefix; + +try { + if (existsSync(npmrc)) { + copyFileSync(npmrc, join(prefix, '.npmrc')); + } + const result = spawnSync( + 'npx', + ['--prefix', prefixArg, '--workspaces=false', ...${JSON.stringify(args)}], + { cwd: root, shell, env, stdio: 'inherit' }, + ); + if (result.error) throw result.error; + process.exitCode = result.status ?? 1; + if (process.exitCode === 0) rmSync(__filename); +} finally { + rmSync(prefix, { recursive: true, force: true }); +} +`; + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, script); + return file; +} + /** Install the project's dependencies. Returns how long the installer ran, in milliseconds. */ export async function installProjectDependencies( root: string, install: ProjectInstall, + report: Pick = { unfinished: undefined }, ): Promise { const { installer, command, args } = install; + let recoveryFile: string | undefined; const result = await runBehindSpinner( `Installing dependencies with ${installer}`, command, @@ -1984,12 +2023,42 @@ export async function installProjectDependencies( shell: command !== process.execPath && process.platform === 'win32', failed: `Failed to install dependencies with ${installer}`, }, + (directory) => { + try { + const { npm_config_workspace: _lower, NPM_CONFIG_WORKSPACE: _upper, ...env } = process.env; + const shell = process.platform === 'win32'; + const options = { cwd: root, shell, env, stdio: 'pipe' as const, timeout: 10_000 }; + const npmPrefix = execFileSync('npm', ['--force', '--workspaces=null', 'prefix'], options); + const npmrc = join(npmPrefix.toString().replace(/\r?\n$/, ''), '.npmrc'); + writeFileSync(join(directory, '.npmrc'), existsSync(npmrc) ? readFileSync(npmrc) : ''); + const prefix = resolve(directory); + const prefixArg = shell ? quoteShellArgument(prefix) : prefix; + if (report.unfinished !== undefined && install.manualCommand) { + try { + recoveryFile = writeNpxInstallRecovery(root, npmrc, args); + const recovery = commandInProject(root, `node ${recoveryFile}`); + report.unfinished = report.unfinished.replace( + commandInProject(root, install.manualCommand), + () => recovery, + ); + } catch { + // A recovery file is optional when the automatic retry can run. + } + } + return { args: ['--prefix', prefixArg, '--workspaces=false', ...args], env }; + } catch { + return undefined; + } + }, ); if (result.status !== 0) { throw new Error(`${installer} install failed with exit code ${result.status ?? 'unknown'}`); } + if (recoveryFile) { + rmSync(join(root, recoveryFile), { force: true }); + } return result.durationMs; } @@ -2951,7 +3020,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg report.unfinished = migrationMode ? `Run \`${manualInstall}\`, then \`${manualMigration}\` to finish setup` : `Run \`${manualInstall}\` to finish setup`; - const duration = await installProjectDependencies(root, install); + const duration = await installProjectDependencies(root, install, report); report.done(`Installed dependencies in ${formatDuration(duration)}`); } else if (packageDependencyRemoved && !workspaceSubpackageSkip) { // The project is installed, so its user has a way to run the installer. diff --git a/packages/void/test/integration/init-install.test.ts b/packages/void/test/integration/init-install.test.ts index ba550334b..df500aef3 100644 --- a/packages/void/test/integration/init-install.test.ts +++ b/packages/void/test/integration/init-install.test.ts @@ -1,9 +1,19 @@ import { spawnSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { delimiter, dirname, join } from 'node:path'; import { stripVTControlCharacters } from 'node:util'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { commandInProject } from '../../src/cli/init-shell.ts'; import { installProjectDependencies, resolveProjectInstall } from '../../src/cli/init.ts'; import { SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES } from '../../src/cli/template.ts'; @@ -11,15 +21,16 @@ let root: string; let bin: string; let callsFile: string; -function executable(name: string, status = 0): void { +function executable(name: string, status = 0, body?: string): void { const script = join(bin, `${name}.cjs`); + const defaultBody = `process.stdout.write(${JSON.stringify(`${name}: resolving packages\n`)}); +process.stderr.write(${JSON.stringify(`${name}: registry unreachable\n`)});`; writeFileSync( script, `const { appendFileSync } = require('node:fs'); appendFileSync(${JSON.stringify(callsFile)}, JSON.stringify({ command: ${JSON.stringify(name)}, args: process.argv.slice(2), cwd: process.cwd() }) + '\\n'); if (!process.argv.includes('--version')) { - process.stdout.write(${JSON.stringify(`${name}: resolving packages\n`)}); - process.stderr.write(${JSON.stringify(`${name}: registry unreachable\n`)}); + ${body ?? defaultBody} } process.exitCode = process.argv.includes('--version') ? 0 : ${status}; `, @@ -33,6 +44,10 @@ process.exitCode = process.argv.includes('--version') ? 0 : ${status}; } } +function npmRejection(reason: string): string { + return `npm error code EBADDEVENGINES\nnpm error EBADDEVENGINES ${reason}`; +} + function calls(): Array { return readFileSync(callsFile, 'utf8') .trim() @@ -127,6 +142,165 @@ describe('init dependency installation (real subprocesses)', () => { }, ); + it.each([ + ['Invalid engine "packageManager"', 0], + ['Invalid devEngines.packageManager', 7], + ] as const)('retries %s once using the effective workspace npmrc', async (reason, status) => { + const app = join(root, 'packages/app'); + const npmrc = 'registry=https://registry.example/\nworkspaces=true\n'; + const snapshot = join(root, 'bootstrap.json'); + const mismatch = npmRejection(reason).replaceAll('npm error', 'npm \u001b[31merror\u001b[0m'); + mkdirSync(join(app, '.void'), { recursive: true }); + writeFileSync(join(app, 'package.json'), readFileSync(join(root, 'package.json'))); + writeFileSync(join(root, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] })); + writeFileSync(join(root, '.npmrc'), npmrc); + writeFileSync(join(app, '.npmrc'), 'registry=https://wrong.example/\n'); + vi.stubEnv('npm_config_workspace', 'app'); + vi.stubEnv('NPM_CONFIG_WORKSPACE', 'app'); + executable('npm', 0, `console.log(${JSON.stringify(root)});`); + executable( + 'npx', + status, + `const { readFileSync, writeFileSync } = require('node:fs'); +const [flag, prefix] = process.argv.slice(2); +if (flag !== '--prefix') { + console.error('npm warn config ignoring workspace config'); + console.error(${JSON.stringify(mismatch)}); + process.exit(1); +} +const npmrc = readFileSync(require('node:path').join(prefix, '.npmrc'), 'utf8'); +const selectors = ['npm_config_workspace', 'NPM_CONFIG_WORKSPACE'].map(key => process.env[key] ?? null); +writeFileSync(${JSON.stringify(snapshot)}, JSON.stringify({ prefix, npmrc, selectors })); +console.error('Retry output'); +`, + ); + + const plan = resolveProjectInstall(app, 'pnpm'); + const report = { unfinished: commandInProject(app, plan.manualCommand) }; + const result = installProjectDependencies(app, plan, report); + if (status === 0) { + await expect(result).resolves.toBeGreaterThan(0); + expect(output()).not.toContain('Retry output'); + } else { + await expect(result).rejects.toThrow('vp install failed with exit code 7'); + expect(output()).toContain('Retry output'); + expect(report.unfinished).toContain('node .void/retry-npm-install.cjs'); + } + expect(output()).not.toContain('EBADDEVENGINES'); + const copied = JSON.parse(readFileSync(snapshot, 'utf8')); + const args = ['--yes', '--package=vite-plus@^1.3.0', 'vp', 'install', '--no-frozen-lockfile']; + expect(calls()).toEqual([ + { command: 'npx', args, cwd: app }, + { command: 'npm', args: ['--force', '--workspaces=null', 'prefix'], cwd: app }, + { + command: 'npx', + args: ['--prefix', copied.prefix, '--workspaces=false', ...args], + cwd: app, + }, + ]); + expect(copied.npmrc).toBe(npmrc); + expect(copied.selectors).toEqual([null, null]); + expect(existsSync(copied.prefix)).toBe(false); + const recoveryScript = join(app, '.void/retry-npm-install.cjs'); + if (status !== 0) { + // Use the live workspace config after the user has repaired the install. + const repaired = npmrc + 'fetch-retries=0\n'; + writeFileSync(join(root, '.npmrc'), repaired); + expect(readFileSync(recoveryScript, 'utf8')).not.toContain('registry.example'); + executable( + 'npx', + 0, + ` +const { readFileSync, writeFileSync } = require('node:fs'); +const [, prefix] = process.argv.slice(2); +const npmrc = readFileSync(require('node:path').join(prefix, '.npmrc'), 'utf8'); +const selectors = ['npm_config_workspace', 'NPM_CONFIG_WORKSPACE'].map(key => process.env[key] ?? null); +writeFileSync(${JSON.stringify(snapshot)}, JSON.stringify({ prefix, npmrc, selectors })); +`, + ); + const recovery = spawnSync(process.execPath, [recoveryScript], { + cwd: app, + encoding: 'utf8', + }); + expect(recovery.status, recovery.stderr).toBe(0); + const retry = JSON.parse(readFileSync(snapshot, 'utf8')); + expect(retry.npmrc).toBe(repaired); + expect(retry.selectors).toEqual([null, null]); + expect(existsSync(retry.prefix)).toBe(false); + } + expect(existsSync(recoveryScript)).toBe(false); + }); + + it('reports a runtime engine mismatch after one attempt', async () => { + const rejection = npmRejection('Invalid devEngines.runtime'); + executable('npx', 1, `console.error(${JSON.stringify(rejection)});`); + executable('npm', 0, `console.log(${JSON.stringify(root)});`); + + await expect(install(root)).rejects.toThrow('vp install failed with exit code 1'); + expect(output()).toContain(rejection); + expect(calls()).toHaveLength(1); + }); + + it('reports a nested npm error without repeating postinstall', async () => { + const marker = join(root, 'postinstall.txt'); + const rejection = npmRejection('Invalid devEngines.packageManager'); + executable('npm', 0, `console.log(${JSON.stringify(root)});`); + executable( + 'npx', + 1, + `console.log('> fixture postinstall'); +appendFileSync(${JSON.stringify(marker)}, 'ran\\n'); +console.error(${JSON.stringify(rejection)}); +console.error('npm error code 1');`, + ); + + await expect(install(root)).rejects.toThrow('vp install failed with exit code 1'); + expect(readFileSync(marker, 'utf8')).toBe('ran\n'); + expect(output()).toContain(rejection); + expect(calls()).toHaveLength(1); + }); + + it.each(['prefix lookup', 'npmrc copy'])( + 'reports the first failure when %s fails', + async (phase) => { + const temp = join(root, 'temporary directory'); + mkdirSync(temp); + vi.stubEnv(process.platform === 'win32' ? 'TEMP' : 'TMPDIR', temp); + const rejection = npmRejection('Invalid devEngines.packageManager'); + executable('npx', 1, `console.error(${JSON.stringify(rejection)});`); + executable( + 'npm', + phase === 'prefix lookup' ? 1 : 0, + `console.log(${JSON.stringify(root)}); +console.error('prefix lookup output');`, + ); + if (phase === 'npmrc copy') { + mkdirSync(join(root, '.npmrc')); + } + const plan = resolveProjectInstall(root, 'pnpm'); + const hint = commandInProject(root, plan.manualCommand); + const report = { unfinished: hint }; + + await expect(installProjectDependencies(root, plan, report)).rejects.toThrow( + 'vp install failed with exit code 1', + ); + expect(output()).toContain(rejection); + expect(output()).not.toContain('prefix lookup output'); + expect(report.unfinished).toBe(hint); + expect(calls()).toHaveLength(2); + expect(readdirSync(temp)).toEqual([]); + }, + ); + + it('reports a registry error from npx after one attempt', async () => { + executable('npx', 1); + + await expect(install(root)).rejects.toThrow('vp install failed with exit code 1'); + + expect(calls()).toHaveLength(1); + expect(output()).toContain('npx: registry unreachable'); + }); + it.each([ ['pnpm', 'catalog:', 'catalog'], ['pnpm', 'catalog:', 'catalogs.default'],