Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
strategy:
matrix:
operating-system: [macos-latest, ubuntu-latest]
node-version: [16, 18, 20, 22, 24]
node-version: [20, 22, 24, 26]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dead Node 16 CI branch

Low Severity

The install step still special-cases Node 16, but the matrix no longer includes 16, so that branch never runs. The leftover eslint@8 install and .eslintrc copy are now dead code after the version list change.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fa77727. Configure here.

name: Node.js ${{ matrix.node-version }} Test on ${{ matrix.operating-system }}

steps:
Expand Down
4 changes: 2 additions & 2 deletions assets/monorepo/package.json.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
"version": "0.0.0",
"private": true,
"description": "${name} monorepo managed by pnpm workspaces",
"packageManager": "pnpm@11.10.0",
"packageManager": "pnpm@10.33.4",
"bin": {
"${name}": "./bin/${name}.js"
},
"engines": {
"node": ">=20",
"pnpm": ">=9"
"pnpm": ">=10"
},
"scripts": {
"dev": "pnpm --filter ${name}-services run dev",
Expand Down
109 changes: 91 additions & 18 deletions commands/init.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,57 @@
/* eslint-disable no-unused-vars */
'use strict';

const path = require('path');
const { spawnSync } = require('child_process');
const { _search, _write, _mkdir, _exists, _move, _sync } = require('@axiosleo/cli-tool/src/helper/fs');
const { _foreach, _exec } = require('@axiosleo/cli-tool/src/helper/cmd');
const { Command, printer, debug } = require('@axiosleo/cli-tool');
const { spawn, spawnSync } = require('child_process');
const { _search, _write, _mkdir, _move, _sync } = require('@axiosleo/cli-tool/src/helper/fs');
const { _foreach } = require('@axiosleo/cli-tool/src/helper/cmd');
const { Command, printer } = require('@axiosleo/cli-tool');
const { _render_with_file } = require('@axiosleo/cli-tool/src/helper/str');
const {
DEFAULT_PNPM_PIN,
readPnpmPin,
corepackEnv,
isCorepackLoadError,
globalInstallCommand
} = require('../src/cli/pnpm');

function hasPnpm() {
const result = spawnSync('pnpm', ['--version'], {
function probePnpm(dir, env) {
return spawnSync('pnpm', ['--version'], {
cwd: dir,
encoding: 'utf8',
shell: true
shell: true,
env
});
return result.status === 0;
}

function probeOutput(result) {
const errMsg = result.error && result.error.message ? result.error.message : '';
return `${result.stderr || ''}${result.stdout || ''}${errMsg}`;
}

function runCommand(command, dir, env) {
return new Promise((resolve, reject) => {
const child = spawn(command, {
cwd: dir,
shell: true,
stdio: 'inherit',
env
});
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`The command "${command}" exited with code "${code}"`));
}
});
});
}

function printPnpmRecovery(dir) {
printer.info('The scaffold is already written. To run pnpm later:');
printer.info(' npm install -g corepack@latest && corepack enable');
printer.info(' # or switch to Node 22+ / 24 (see .nvmrc)');
printer.info(` cd ${dir} && pnpm install`);
}

class InitCommand extends Command {
Expand All @@ -27,8 +65,8 @@ class InitCommand extends Command {
}

/**
* @param {*} args
* @param {*} options
* @param {*} args
* @param {*} options
*/
async exec(args, options) {
let name = args.name;
Expand Down Expand Up @@ -56,23 +94,58 @@ class InitCommand extends Command {

printer.success('Initialized successfully');

if (!hasPnpm()) {
const pin = readPnpmPin(dir) || DEFAULT_PNPM_PIN;
const env = corepackEnv(process.env);
const installHint = globalInstallCommand(pin);
let probe = probePnpm(dir, env);

if (probe.status !== 0) {
const output = probeOutput(probe);
if (isCorepackLoadError(output)) {
printer.error('pnpm failed to run (Corepack could not load the pinned version).');
printPnpmRecovery(dir);
return;
}
printer.warning('pnpm is required but not found');
if (await this.confirm('install pnpm?', true)) {
printer.info('running: npm install -g pnpm');
await _exec('npm install -g pnpm', dir);
printer.info(`running: ${installHint}`);
try {
await runCommand(installHint, dir, env);
} catch (err) {
printer.error(err && err.message ? err.message : String(err));
printPnpmRecovery(dir);
return;
}
probe = probePnpm(dir, env);
if (probe.status !== 0) {
printer.error('pnpm is still not usable after install.');
printPnpmRecovery(dir);
return;
}
} else {
printer.info('Please run: npm install -g pnpm');
process.exit(0);
printer.info(`Please run: ${installHint}`);
printer.info(`Then: cd ${dir} && pnpm install`);
return;
}
}

if (await this.confirm('install dependencies?', true)) {
await _exec('pnpm install', dir);
try {
await runCommand('pnpm install', dir, env);
} catch (err) {
printer.error(err && err.message ? err.message : String(err));
printPnpmRecovery(dir);
return;
}
}

if (await this.confirm('start services right now?')) {
await _exec('pnpm dev', dir);
try {
await runCommand('pnpm dev', dir, env);
} catch (err) {
printer.error(err && err.message ? err.message : String(err));
printPnpmRecovery(dir);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recovery shown for unrelated failures

Low Severity

printPnpmRecovery is reused when pnpm install or pnpm dev fails. Those failures are often network, dependency, or a normal Ctrl+C stop, not a Corepack load problem, so users get Corepack/Node upgrade steps after a successful scaffold or a stopped dev server.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fa77727. Configure here.

}
}
}
Expand Down
77 changes: 77 additions & 0 deletions src/cli/pnpm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
'use strict';

const fs = require('fs');
const path = require('path');

const DEFAULT_PNPM_PIN = '10.33.4';
const NPMMIRROR = 'https://registry.npmmirror.com';

/**
* Parse a Corepack `packageManager` field into a pnpm version pin.
* @param {unknown} packageManager
* @returns {string|null}
*/
function parsePnpmPin(packageManager) {
if (typeof packageManager !== 'string') {
return null;
}
const match = packageManager.trim().match(/^pnpm@(.+)$/);
return match ? match[1] : null;
}

/**
* Read `packageManager` from `dir/package.json` and return the pnpm pin.
* @param {string} dir
* @returns {string|null}
*/
function readPnpmPin(dir) {
try {
const raw = fs.readFileSync(path.join(dir, 'package.json'), 'utf8');
const pkg = JSON.parse(raw);
return parsePnpmPin(pkg && pkg.packageManager);
} catch (_err) { // eslint-disable-line no-unused-vars
return null;
}
}

/**
* Env for Corepack-backed `pnpm` during `koapp init`.
* Skips the extra download prompt and uses the same registry as the template `.npmrc`.
* An existing `COREPACK_NPM_REGISTRY` on the caller is left intact.
*
* @param {NodeJS.ProcessEnv} [baseEnv]
* @returns {NodeJS.ProcessEnv}
*/
function corepackEnv(baseEnv = process.env) {
return {
...baseEnv,
COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
COREPACK_NPM_REGISTRY: baseEnv.COREPACK_NPM_REGISTRY || NPMMIRROR
};
}

/**
* @param {unknown} output
* @returns {boolean}
*/
function isCorepackLoadError(output) {
return String(output || '').includes('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING');
}

/**
* @param {string} pin
* @returns {string}
*/
function globalInstallCommand(pin) {
return `npm install -g pnpm@${pin}`;
}

module.exports = {
DEFAULT_PNPM_PIN,
NPMMIRROR,
parsePnpmPin,
readPnpmPin,
corepackEnv,
isCorepackLoadError,
globalInstallCommand
};
103 changes: 103 additions & 0 deletions tests/pnpm.tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');
const { expect } = require('chai');
const {
DEFAULT_PNPM_PIN,
NPMMIRROR,
parsePnpmPin,
readPnpmPin,
corepackEnv,
isCorepackLoadError,
globalInstallCommand
} = require('../src/cli/pnpm');

function mkdtemp(prefix) {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}

describe('cli/pnpm', () => {
describe('parsePnpmPin()', () => {
it('reads a pnpm@version field', () => {
expect(parsePnpmPin('pnpm@10.33.4')).to.equal('10.33.4');
});

it('keeps a hash suffix after the version', () => {
expect(parsePnpmPin('pnpm@10.33.4+sha512.abc')).to.equal('10.33.4+sha512.abc');
});

it('returns null for other package managers or empty values', () => {
expect(parsePnpmPin('yarn@4.1.0')).to.equal(null);
expect(parsePnpmPin('pnpm')).to.equal(null);
expect(parsePnpmPin('')).to.equal(null);
expect(parsePnpmPin(null)).to.equal(null);
expect(parsePnpmPin(undefined)).to.equal(null);
});
});

describe('readPnpmPin()', () => {
it('matches the monorepo template pin', () => {
const tmpl = fs.readFileSync(
path.join(__dirname, '../assets/monorepo/package.json.tmpl'),
'utf8'
);
expect(tmpl).to.include(`"packageManager": "pnpm@${DEFAULT_PNPM_PIN}"`);
expect(tmpl).to.include('"pnpm": ">=10"');
});

it('reads packageManager from package.json', () => {
const dir = mkdtemp('koapp-pnpm-pin-');
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
name: 'demo',
packageManager: 'pnpm@10.33.4'
}));
expect(readPnpmPin(dir)).to.equal('10.33.4');
});

it('returns null when package.json is missing', () => {
const dir = mkdtemp('koapp-pnpm-missing-');
expect(readPnpmPin(dir)).to.equal(null);
});
});

describe('corepackEnv()', () => {
it('skips the Corepack download prompt and uses npmmirror by default', () => {
const env = corepackEnv({ PATH: '/usr/bin', HOME: '/tmp' });
expect(env.COREPACK_ENABLE_DOWNLOAD_PROMPT).to.equal('0');
expect(env.COREPACK_NPM_REGISTRY).to.equal(NPMMIRROR);
expect(env.PATH).to.equal('/usr/bin');
});

it('does not override an existing COREPACK_NPM_REGISTRY', () => {
const env = corepackEnv({ COREPACK_NPM_REGISTRY: 'https://registry.npmjs.org' });
expect(env.COREPACK_NPM_REGISTRY).to.equal('https://registry.npmjs.org');
expect(env.COREPACK_ENABLE_DOWNLOAD_PROMPT).to.equal('0');
});
});

describe('isCorepackLoadError()', () => {
it('detects the Node/Corepack VM import failure from the screenshot', () => {
const stderr = [
'node:internal/modules/esm/utils:231',
' throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();',
"TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified."
].join('\n');
expect(isCorepackLoadError(stderr)).to.equal(true);
});

it('returns false for unrelated output', () => {
expect(isCorepackLoadError('command not found: pnpm')).to.equal(false);
expect(isCorepackLoadError('')).to.equal(false);
expect(isCorepackLoadError(null)).to.equal(false);
});
});

describe('globalInstallCommand()', () => {
it('pins the requested version instead of npm latest', () => {
expect(globalInstallCommand('10.33.4')).to.equal('npm install -g pnpm@10.33.4');
expect(globalInstallCommand(DEFAULT_PNPM_PIN)).to.equal('npm install -g pnpm@10.33.4');
});
});
});
Loading