bmad-plus 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +36 -8
  3. package/package.json +6 -4
  4. package/readme-international/README.de.md +37 -8
  5. package/readme-international/README.es.md +38 -9
  6. package/readme-international/README.fr.md +37 -8
  7. package/src/bmad-plus/agents/agent-orchestrator/SKILL.md +2 -0
  8. package/src/bmad-plus/module.yaml +270 -220
  9. package/src/bmad-plus/packs/pack-seo/scripts/seo_apis.py +8 -8
  10. package/src/bmad-plus/packs/pack-seo/scripts/seo_fetch.py +1 -2
  11. package/src/bmad-plus/packs/pack-seo/scripts/seo_report.py +0 -1
  12. package/src/bmad-plus/skills/bmad-plus-autopilot/SKILL.md +1 -1
  13. package/tools/bmad-plus-npx.js +4 -2
  14. package/tools/build/adapters.config.js +60 -51
  15. package/tools/build/check-counts.js +52 -54
  16. package/tools/build/check-install-contract.js +298 -0
  17. package/tools/build/generate-adapters.js +252 -56
  18. package/tools/build/generate.js +187 -10
  19. package/tools/build/generated-adapters/.codex/AGENTS.md +20 -7
  20. package/tools/build/generated-adapters/.cursor/rules/bmad-plus.mdc +20 -7
  21. package/tools/build/generated-adapters/.opencode/AGENTS.md +20 -7
  22. package/tools/build/generated-adapters/AGENTS.md +20 -7
  23. package/tools/build/generated-adapters/CLAUDE.md +20 -7
  24. package/tools/build/generated-adapters/CONVENTIONS.md +20 -7
  25. package/tools/build/generated-adapters/GEMINI.md +20 -7
  26. package/tools/build/module.template.yaml +82 -0
  27. package/tools/cli/bmad-plus-cli.js +16 -1
  28. package/tools/cli/commands/doctor.js +12 -40
  29. package/tools/cli/commands/install.js +108 -163
  30. package/tools/cli/commands/uninstall.js +173 -65
  31. package/tools/cli/commands/update-check.js +31 -0
  32. package/tools/cli/commands/update-policy.js +39 -0
  33. package/tools/cli/commands/update.js +102 -113
  34. package/tools/cli/i18n.js +60 -0
  35. package/tools/cli/lib/ide-config.js +4 -261
  36. package/tools/cli/lib/install-manifest.js +17 -0
  37. package/tools/cli/lib/installed-adapters.js +89 -0
  38. package/tools/cli/lib/npm-runner.js +177 -0
  39. package/tools/cli/lib/pack-copy.js +62 -66
  40. package/tools/cli/lib/packs.js +437 -3
  41. package/tools/cli/lib/update-check.js +153 -0
  42. package/tools/cli/lib/update-dispatch.js +182 -0
  43. package/tools/cli/lib/update-policy.js +90 -0
  44. package/tools/cli/lib/update-transaction.js +334 -0
@@ -1,267 +1,10 @@
1
1
  /**
2
- * BMAD+ IDE Configuration Generator
3
- * Extracted from install.js for modularity.
4
- * Generates CLAUDE.md, GEMINI.md, AGENTS.md content with pack-aware agent filtering.
5
- *
2
+ * Compatibility entry for IDE metadata. Rendering lives in the registry generator.
6
3
  * Author: Laurent Rochetta
7
4
  */
8
-
9
- // ── IDE Configurations ──
10
-
11
- const IDE_CONFIGS = {
12
- 'claude-code': {
13
- name: 'Claude Code',
14
- detect: ['.claude'],
15
- configFile: 'CLAUDE.md',
16
- },
17
- 'gemini-cli': {
18
- name: 'Gemini CLI',
19
- detect: ['.gemini'],
20
- configFile: 'GEMINI.md',
21
- },
22
- 'codex-cli': {
23
- name: 'Codex CLI / OpenCode',
24
- detect: ['.codex', '.opencode'],
25
- configFile: 'AGENTS.md',
26
- },
27
- 'antigravity': {
28
- name: 'Antigravity',
29
- detect: ['.gemini/antigravity'],
30
- configFile: 'GEMINI.md',
31
- },
32
- };
33
-
34
- // Shield ships 27 compliance agents (registry.yaml `shield.categories`) AND 11
35
- // workflows (`shield.workflows`) — two separate dimensions that must never be
36
- // summed into a single "agents" figure. Summing them is what produced the retired
37
- // "38" over-count that shipped into every generated user config. Declared once so
38
- // the two call sites below cannot drift apart; gated by tools/build/check-counts.js.
39
- const SHIELD_AGENT_LINE =
40
- '- **Shield** (GRC) — 27 compliance agents + 11 workflows (GDPR, ISO 27001, SOC 2, HIPAA, EU AI Act, DORA, NIS2...)';
41
-
42
- // All 14 BMAD+ agents — always included in templates
43
- const AGENT_LIST = [
44
- '- **Atlas** (Strategist) — Business analysis + Product management',
45
- '- **Forge** (Architect-Dev) — Architecture + Development + Documentation',
46
- '- **Sentinel** (Quality) — QA + UX review',
47
- '- **Nexus** (Orchestrator) — Sprint management + Autopilot + Parallel execution',
48
- '- **Shadow** (OSINT) — Investigation + Scraping + Psychoprofiling',
49
- SHIELD_AGENT_LINE,
50
- '- **Miriam** (מרים) — Business Analyst — Strategic analysis, research, product briefs',
51
- '- **Huldah** (חולדה) — Technical Writer — Documentation, diagrams, editorial review',
52
- '- **Yosef** (יוסף) — Product Manager — PRD, requirements, feature prioritization',
53
- '- **Rachel** (רחל) — UX Designer — User experience, wireframes, empathy mapping',
54
- '- **Bezalel** (בצלאל) — System Architect — Architecture, ADRs, epics & stories',
55
- '- **Oholiab** (אהליאב) — Senior Engineer — TDD, sprint, code review, implementation',
56
- '- **Zecher** (זכר) — Memory Archivist — Consolidation, project scanning, context recall',
57
- '- **Maker** (Creator) — Custom agent builder — Create new agents from description',
58
- ];
59
-
60
- /**
61
- * Filter agents based on installed packs.
62
- * Core agents are always included; others depend on pack selection.
63
- *
64
- * @param {string[]} packs - List of installed pack IDs
65
- * @returns {string[]} Agent description lines
66
- */
67
- function getAgentsByPacks(packs) {
68
- const agents = [
69
- '- **Atlas** (Strategist) — Business analysis + Product management',
70
- '- **Forge** (Architect-Dev) — Architecture + Development + Documentation',
71
- '- **Sentinel** (Quality) — QA + UX review',
72
- '- **Nexus** (Orchestrator) — Sprint management + Autopilot + Parallel execution',
73
- ];
74
-
75
- if (packs.includes('osint')) {
76
- agents.push('- **Shadow** (OSINT) — Investigation + Scraping + Psychoprofiling');
77
- }
78
-
79
- if (packs.includes('shield')) {
80
- agents.push(SHIELD_AGENT_LINE);
81
- }
82
-
83
- if (packs.includes('maker')) {
84
- agents.push('- **Maker** (Creator) — Custom agent builder — Create new agents from description');
85
- }
86
-
87
- if (packs.includes('dev-studio')) {
88
- agents.push('- **Miriam** (מרים) — Business Analyst — Strategic analysis, research, product briefs');
89
- agents.push('- **Huldah** (חולדה) — Technical Writer — Documentation, diagrams, editorial review');
90
- agents.push('- **Yosef** (יוסף) — Product Manager — PRD, requirements, feature prioritization');
91
- agents.push('- **Rachel** (רחל) — UX Designer — User experience, wireframes, empathy mapping');
92
- agents.push('- **Bezalel** (בצלאל) — System Architecture — Architecture, ADRs, epics & stories');
93
- agents.push('- **Oholiab** (אהליאב) — Senior Engineer — TDD, sprint, code review, implementation');
94
- }
95
-
96
- if (packs.includes('memory')) {
97
- agents.push('- **Zecher** (זכר) — Memory Archivist — Consolidation, project scanning, context recall');
98
- }
99
-
100
- return agents;
101
- }
102
-
103
- /**
104
- * Build the Memory Protocol section if the memory pack is installed.
105
- *
106
- * @param {string[]} packs - List of installed pack IDs
107
- * @returns {string} Memory section markdown (empty string if no memory pack)
108
- */
109
- function getMemorySection(packs) {
110
- if (!packs.includes('memory')) return '';
111
- return [
112
- '',
113
- '## Memory Protocol (Karpathy Guardrails)',
114
- '',
115
- 'Agents MUST follow these behavioral principles:',
116
- '',
117
- '### G1 — Think Before Coding',
118
- '- State assumptions explicitly. If uncertain, ask.',
119
- '- Check `.agents/memory/decisions.md` for prior decisions before re-deciding.',
120
- '',
121
- '### G2 — Simplicity First',
122
- '- Minimum code that solves the problem. Nothing speculative.',
123
- '- Check `.agents/memory/patterns.md` for existing solutions.',
124
- '',
125
- '### G3 — Surgical Changes',
126
- '- Touch only what you must. Match existing style.',
127
- '- Log surprises in `.agents/memory/lessons.md`.',
128
- '',
129
- '### G4 — Goal-Driven Execution',
130
- '- Define success criteria before implementing.',
131
- '- Log non-obvious decisions in `.agents/memory/decisions.md`.',
132
- '',
133
- '### Memory Files',
134
- '- `.agents/memory/decisions.md` — Read at session start, write when making decisions',
135
- '- `.agents/memory/lessons.md` — Write when something unexpected happens',
136
- '- `.agents/memory/patterns.md` — Write when a reusable pattern is validated',
137
- '- `.agents/memory/context.md` — Update at session end with project state',
138
- ].join('\n');
139
- }
140
-
141
- /**
142
- * Generate IDE config content with pack-aware agent filtering.
143
- *
144
- * @param {string} userName - The user's display name
145
- * @param {string} language - User-facing communication language
146
- * @param {string[]} packs - List of installed pack IDs
147
- * @returns {string} Complete Markdown template
148
- */
149
- function generateIDEConfig(userName, language, packs) {
150
- const agents = getAgentsByPacks(packs);
151
- const memorySection = getMemorySection(packs);
152
-
153
- return `# BMAD+ — AI Agent Configuration
154
-
155
- ## Project Context
156
- This project uses BMAD+, an augmented AI-driven development framework.
157
- Based on BMAD-METHOD v6.6.0 with multi-role agents, autopilot mode, and parallel execution.
158
-
159
- ## Agents
160
- To activate an agent, say its name or persona:
161
- ${agents.join('\n')}
162
-
163
- ## Skills
164
- - Load skills from \`.agents/skills/\`
165
- - Each agent has a SKILL.md with capabilities, activation protocol, and role-switching rules
166
- - Auto-activation triggers: \`.agents/data/role-triggers.yaml\`
167
-
168
- ## Key Commands
169
- - \`bmad-help\` — Show all available agents and skills
170
- - \`autopilot\` — Launch Nexus in full pipeline mode
171
- - \`parallel\` — Enable parallel multi-agent execution
172
-
173
- ## Communication
174
- - User name: ${userName}
175
- - Default language: ${language} for user-facing content, English for code and technical docs.
176
- ${memorySection}`;
177
- }
178
-
179
- /**
180
- * Generate a complete CLAUDE.md / GEMINI.md / AGENTS.md config file
181
- * (all agents, no filtering — backward compatible)
182
- *
183
- * @param {string} userName - The user's display name
184
- * @param {string} language - User-facing communication language
185
- * @returns {string} Complete Markdown template
186
- */
187
- function generateBaseConfig(userName, language) {
188
- return `# BMAD+ — AI Agent Configuration
189
-
190
- ## Project Context
191
- This project uses BMAD+, an augmented AI-driven development framework.
192
- Based on BMAD-METHOD v6.6.0 with multi-role agents, autopilot mode, and parallel execution.
193
-
194
- ## Agents
195
- To activate an agent, say its name or persona:
196
- ${AGENT_LIST.join('\n')}
197
-
198
- ## Skills
199
- - Load skills from \`.agents/skills/\`
200
- - Each agent has a SKILL.md with capabilities, activation protocol, and role-switching rules
201
- - Auto-activation triggers: \`.agents/data/role-triggers.yaml\`
202
-
203
- ## Key Commands
204
- - \`bmad-help\` — Show all available agents and skills
205
- - \`autopilot\` — Launch Nexus in full pipeline mode
206
- - \`parallel\` — Enable parallel multi-agent execution
207
-
208
- ## Communication
209
- - User name: ${userName}
210
- - Default language: ${language} for user-facing content, English for code and technical docs.
211
-
212
- ## Memory Protocol (Karpathy Guardrails)
213
-
214
- Agents MUST follow these behavioral principles:
215
-
216
- ### G1 — Think Before Coding
217
- - State assumptions explicitly. If uncertain, ask.
218
- - Check \`.agents/memory/decisions.md\` for prior decisions before re-deciding.
219
-
220
- ### G2 — Simplicity First
221
- - Minimum code that solves the problem. Nothing speculative.
222
- - Check \`.agents/memory/patterns.md\` for existing solutions.
223
-
224
- ### G3 — Surgical Changes
225
- - Touch only what you must. Match existing style.
226
- - Log surprises in \`.agents/memory/lessons.md\`.
227
-
228
- ### G4 — Goal-Driven Execution
229
- - Define success criteria before implementing.
230
- - Log non-obvious decisions in \`.agents/memory/decisions.md\`.
231
-
232
- ### Memory Files
233
- - \`.agents/memory/decisions.md\` — Read at session start, write when making decisions
234
- - \`.agents/memory/lessons.md\` — Write when something unexpected happens
235
- - \`.agents/memory/patterns.md\` — Write when a reusable pattern is validated
236
- - \`.agents/memory/context.md\` — Update at session end with project state`;
237
- }
5
+ const adapters = require('../../build/generate-adapters');
238
6
 
239
7
  module.exports = {
240
- IDE_CONFIGS,
241
- generateIDEConfig,
242
- getAgentsByPacks,
243
-
244
- /**
245
- * Generate CLAUDE.md config for Claude Code
246
- * @param {string} userName
247
- * @param {string} language
248
- * @returns {string}
249
- */
250
- generateClaudeMD: generateBaseConfig,
251
-
252
- /**
253
- * Generate GEMINI.md config for Gemini CLI / Antigravity
254
- * @param {string} userName
255
- * @param {string} language
256
- * @returns {string}
257
- */
258
- generateGeminiMD: generateBaseConfig,
259
-
260
- /**
261
- * Generate AGENTS.md config for Codex CLI / OpenCode
262
- * @param {string} userName
263
- * @param {string} language
264
- * @returns {string}
265
- */
266
- generateAgentsMD: generateBaseConfig,
8
+ get IDE_CONFIGS() { return adapters.IDE_CONFIGS; },
9
+ buildIDEConfigs: adapters.buildIDEConfigs,
267
10
  };
@@ -0,0 +1,17 @@
1
+ /** Read the manifest fields used by maintenance commands without unsafe coercion. */
2
+ const fs = require('node:fs');
3
+
4
+ function readInstallManifest(manifestPath) {
5
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
6
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest) ||
7
+ typeof manifest.version !== 'string' || !manifest.version.trim() ||
8
+ typeof manifest.installed !== 'string' || !Number.isFinite(Date.parse(manifest.installed)) ||
9
+ !Array.isArray(manifest.packs) || manifest.packs.length === 0 ||
10
+ manifest.packs.some(pack => typeof pack !== 'string' || !/^[a-z0-9-]+$/.test(pack)) ||
11
+ (manifest.uiLanguage !== undefined && typeof manifest.uiLanguage !== 'string')) {
12
+ throw new Error('Expected version, installed date, and a nonempty array of pack IDs.');
13
+ }
14
+ return manifest;
15
+ }
16
+
17
+ module.exports = { readInstallManifest };
@@ -0,0 +1,89 @@
1
+ /** Installed adapter ownership shared by install, update, and uninstall. */
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const clack = require('@clack/prompts');
6
+ const { GENERATED_MARKER, USER_CONFIG_MARKER } = require('../../build/generate-adapters');
7
+
8
+ const INSTALLER_MARKER = 'BMAD+ \u2014 AI Agent Configuration';
9
+ const contentHash = content => crypto.createHash('sha256').update(String(content).replace(/\r\n/g, '\n')).digest('hex');
10
+
11
+ function classifyAdapter({ existing, content, previousHash, update = false, yes = false }) {
12
+ if (existing === undefined) return { action: 'write', backup: false };
13
+ const installed = existing.includes(USER_CONFIG_MARKER);
14
+ const adopted = existing.includes(GENERATED_MARKER) && !installed;
15
+ const legacy = existing.includes(INSTALLER_MARKER) && !existing.includes(GENERATED_MARKER);
16
+ if (installed && existing === content) return { action: 'same', backup: false };
17
+ const unchanged = installed && previousHash === contentHash(existing);
18
+ if (adopted || (installed && !unchanged) || (!installed && !legacy && (update || !yes))) {
19
+ return { action: 'preserve', backup: false, adopted, installed, reason: adopted ? 'repository-adopted' : 'local-instructions' };
20
+ }
21
+ return { action: 'write', backup: legacy || (!installed && yes), legacy };
22
+ }
23
+
24
+ // Refuse redirected parent directories as well as linked destination files.
25
+ function safeAdapterPath(projectDir, file) {
26
+ const root = path.resolve(projectDir);
27
+ const target = path.resolve(root, file);
28
+ const relative = path.relative(root, target);
29
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
30
+ throw new Error('Adapter path outside project: ' + file);
31
+ }
32
+ let current = root;
33
+ for (const part of relative.split(path.sep)) {
34
+ current = path.join(current, part);
35
+ try {
36
+ if (fs.lstatSync(current).isSymbolicLink()) throw new Error('Adapter path is a symbolic link or junction: ' + current);
37
+ } catch (err) {
38
+ if (err.code !== 'ENOENT') throw err;
39
+ }
40
+ }
41
+ return target;
42
+ }
43
+
44
+ function writeIDEConfigs({ projectDir, files, yes = false, update = false, adapterHashes = {} }) {
45
+ const outcome = { written: [], skipped: [], backedUp: [], adapterHashes: {} };
46
+ // Preflight the complete set before writing any adapter.
47
+ for (const { file } of files) safeAdapterPath(projectDir, file);
48
+ for (const { file, content } of files) {
49
+ const target = safeAdapterPath(projectDir, file);
50
+ const previousHash = Object.hasOwn(adapterHashes, file) ? adapterHashes[file] : undefined;
51
+ let backup = false;
52
+ if (fs.existsSync(target)) {
53
+ const existing = fs.readFileSync(target, 'utf8');
54
+ const decision = classifyAdapter({ existing, content, previousHash, update, yes });
55
+ if (decision.action === 'same') {
56
+ outcome.adapterHashes[file] = contentHash(content);
57
+ continue;
58
+ }
59
+ if (decision.action === 'preserve') {
60
+ if (previousHash && decision.installed) outcome.adapterHashes[file] = previousHash;
61
+ outcome.skipped.push(file);
62
+ const compare = decision.adopted
63
+ ? ` Compare package defaults: node "${require.resolve('../../build/generate-adapters')}" --target "${path.resolve(projectDir)}" --check`
64
+ : '';
65
+ clack.log.warn(`${file}: existing project instructions preserved.${compare}`);
66
+ continue;
67
+ }
68
+ // Older installers did not record hashes. Keep their exact bytes before
69
+ // migration, including any local additions that cannot be distinguished.
70
+ backup = decision.backup;
71
+ }
72
+ if (backup) {
73
+ let suffix = '.bak';
74
+ let index = 1;
75
+ while (fs.existsSync(safeAdapterPath(projectDir, file + suffix))) suffix = `.bak.${index++}`;
76
+ fs.copyFileSync(target, safeAdapterPath(projectDir, file + suffix), fs.constants.COPYFILE_EXCL);
77
+ outcome.backedUp.push(file);
78
+ clack.log.warn(`${file}: backed up to ${file + suffix} before refreshing.`);
79
+ }
80
+ fs.mkdirSync(path.dirname(target), { recursive: true });
81
+ safeAdapterPath(projectDir, file);
82
+ fs.writeFileSync(target, content, 'utf8');
83
+ outcome.written.push(file);
84
+ outcome.adapterHashes[file] = contentHash(content);
85
+ }
86
+ return outcome;
87
+ }
88
+
89
+ module.exports = { INSTALLER_MARKER, contentHash, safeAdapterPath, writeIDEConfigs, classifyAdapter };
@@ -0,0 +1,177 @@
1
+ /** Run npm through Node with bounded output and no shell interpolation. */
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const childProcess = require('node:child_process');
5
+
6
+ function resolveNpmCli({
7
+ env = process.env,
8
+ execPath = process.execPath,
9
+ platform = process.platform,
10
+ realpath = fs.realpathSync,
11
+ isFile = (file) => fs.statSync(file).isFile(),
12
+ } = {}) {
13
+ const paths = platform === 'win32' ? path.win32 : path.posix;
14
+ const searchPath = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] || '';
15
+ const directories = searchPath.split(platform === 'win32' ? ';' : ':').filter(Boolean);
16
+ const nodeDir = paths.dirname(execPath);
17
+ const candidates = [
18
+ env.npm_execpath,
19
+ paths.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
20
+ paths.resolve(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
21
+ ...directories.flatMap((dir) => [
22
+ paths.join(dir, 'npm'),
23
+ paths.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
24
+ ]),
25
+ ];
26
+ for (const candidate of candidates) {
27
+ if (!candidate) continue;
28
+ try {
29
+ const resolved = realpath(candidate);
30
+ if (paths.basename(resolved).toLowerCase() === 'npm-cli.js' && isFile(resolved))
31
+ return resolved;
32
+ } catch {
33
+ /* Try the next standard npm installation location. */
34
+ }
35
+ }
36
+ throw new Error('npm-cli.js was not found. Install Node.js with npm or repair its PATH.');
37
+ }
38
+
39
+ /** Injectable process boundary; tests never need to fetch a package. */
40
+ function createNpmRunner({
41
+ spawn = childProcess.spawn,
42
+ resolveCli = resolveNpmCli,
43
+ platform = process.platform,
44
+ execPath = process.execPath,
45
+ kill = process.kill.bind(process),
46
+ } = {}) {
47
+ return async function runNpm(
48
+ args,
49
+ { cwd, timeout = 6000, env = process.env, maxBuffer = 1024 * 1024, signal } = {}
50
+ ) {
51
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== 'string' || arg.includes('\0'))) {
52
+ throw new Error('npm arguments must be an array of strings without NUL bytes.');
53
+ }
54
+ if (
55
+ !Number.isSafeInteger(timeout) ||
56
+ timeout <= 0 ||
57
+ !Number.isSafeInteger(maxBuffer) ||
58
+ maxBuffer <= 0
59
+ ) {
60
+ throw new Error('npm timeout and maxBuffer must be positive integers.');
61
+ }
62
+ if (signal?.aborted)
63
+ throw Object.assign(new Error('npm operation was cancelled.'), { code: 'ABORT_ERR' });
64
+ const cli = resolveCli({ env, execPath, platform });
65
+
66
+ return new Promise((resolve, reject) => {
67
+ let child;
68
+ try {
69
+ child = spawn(execPath, [cli, ...args], {
70
+ cwd,
71
+ env,
72
+ shell: false,
73
+ windowsHide: true,
74
+ detached: platform !== 'win32',
75
+ stdio: ['ignore', 'pipe', 'pipe'],
76
+ });
77
+ } catch (error) {
78
+ reject(new Error('Could not start npm.', { cause: error }));
79
+ return;
80
+ }
81
+ let settled = false;
82
+ let bytes = 0;
83
+ const stdout = [];
84
+ const stderr = [];
85
+ let timer;
86
+ const finish = (error, output) => {
87
+ if (settled) return;
88
+ settled = true;
89
+ clearTimeout(timer);
90
+ signal?.removeEventListener('abort', abort);
91
+ if (error) {
92
+ error.stdout = Buffer.concat(stdout).toString('utf8');
93
+ error.stderr = Buffer.concat(stderr).toString('utf8');
94
+ const diagnostic = [error.stdout.trim(), error.stderr.trim()].filter(Boolean).join('\n');
95
+ if (diagnostic) error.message += '\n' + diagnostic;
96
+ reject(error);
97
+ } else resolve(output);
98
+ };
99
+ const killChild = () => {
100
+ try {
101
+ child.kill('SIGKILL');
102
+ } catch {
103
+ /* The process may already have exited. */
104
+ }
105
+ };
106
+ const stop = () => {
107
+ if (!Number.isInteger(child.pid) || child.pid <= 0) return killChild();
108
+ if (platform !== 'win32') {
109
+ // A detached npm owns this process group, including its updater child.
110
+ try {
111
+ kill(-child.pid, 'SIGKILL');
112
+ } catch {
113
+ killChild();
114
+ }
115
+ return;
116
+ }
117
+ try {
118
+ const terminator = spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], {
119
+ shell: false,
120
+ windowsHide: true,
121
+ stdio: 'ignore',
122
+ env,
123
+ });
124
+ terminator.once('error', killChild);
125
+ terminator.once('close', (code) => {
126
+ if (code !== 0) killChild();
127
+ });
128
+ } catch {
129
+ killChild();
130
+ }
131
+ };
132
+ const cancel = (message, code) => {
133
+ if (settled) return;
134
+ stop();
135
+ finish(Object.assign(new Error(message), { code }));
136
+ };
137
+ const abort = () =>
138
+ cancel('npm operation was cancelled; child termination requested.', 'ABORT_ERR');
139
+ const collect = (chunk, save) => {
140
+ if (settled) return;
141
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
142
+ bytes += buffer.length;
143
+ if (bytes > maxBuffer)
144
+ return cancel('npm output exceeded the configured buffer limit.', 'ENOBUFS');
145
+ (save ? stdout : stderr).push(buffer);
146
+ };
147
+ child.stdout.on('data', (chunk) => collect(chunk, true));
148
+ child.stderr.on('data', (chunk) => collect(chunk, false));
149
+ child.once('error', (error) => finish(new Error('Could not run npm.', { cause: error })));
150
+ child.once('close', (code, exitSignal) => {
151
+ if (code !== 0 || exitSignal) {
152
+ finish(
153
+ Object.assign(new Error(`npm exited unsuccessfully (${exitSignal || code}).`), {
154
+ code: 'NPM_EXIT',
155
+ exitCode: code,
156
+ signal: exitSignal,
157
+ })
158
+ );
159
+ } else finish(null, Buffer.concat(stdout).toString('utf8'));
160
+ });
161
+ timer = setTimeout(
162
+ () =>
163
+ cancel(
164
+ `npm exceeded its ${timeout} ms deadline; child termination requested.`,
165
+ 'ETIMEDOUT'
166
+ ),
167
+ timeout
168
+ );
169
+ timer.unref?.();
170
+ signal?.addEventListener('abort', abort, { once: true });
171
+ if (signal?.aborted) abort();
172
+ });
173
+ };
174
+ }
175
+
176
+ const runNpm = createNpmRunner();
177
+ module.exports = { runNpm, resolveNpmCli, createNpmRunner };