huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.4

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -4,11 +4,123 @@
4
4
  // src/update-check.ts re-export face.
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { SUPPORTED_AGENT_TARGETS } from "./auth/agent-registration.js";
7
+ import { isCredentialEnvVarName } from "./lib/secret-vault/refs.js";
7
8
  import { determineTarget, semverCompare } from "./update-semver.js";
8
9
  import { readInstalledVersion } from "./update-installed.js";
9
- import { queryDistTags, errorMessage } from "./update-registry.js";
10
+ import { queryDistTags, errorMessage, resolveRegistryOverride, resolveEnvSpelling } from "./update-registry.js";
10
11
  import { invalidateUpdateCache } from "./update-cache.js";
11
12
  const NPX_BIN = process.platform === 'win32' ? 'npx.cmd' : 'npx';
13
+ // The upgrade child is arbitrary registry code and the published package needs
14
+ // no account, so it gets an environment without the credential family the
15
+ // vault predicate owns (case-normalized, so a Windows spelling cannot survive),
16
+ // plus dev 4890d78c's AWS keys and KooCLI's `HUAWEI_*` alias spellings, which the
17
+ // predicate does not claim.
18
+ const UPGRADE_EXTRA_CREDENTIAL_ENV_KEYS = new Set([
19
+ 'AWS_ACCESS_KEY_ID',
20
+ 'AWS_SECRET_ACCESS_KEY',
21
+ 'AWS_SESSION_TOKEN',
22
+ 'HUAWEI_ACCESS_KEY',
23
+ 'HUAWEI_SECRET_KEY',
24
+ 'GITHUB_ENTERPRISE_TOKEN',
25
+ 'GH_ENTERPRISE_TOKEN',
26
+ 'GITHUB_TOKEN',
27
+ 'GH_TOKEN',
28
+ 'DOCKER_PASSWORD',
29
+ 'DOCKER_AUTH_CONFIG',
30
+ 'GITLAB_TOKEN',
31
+ 'GITLAB_CI_JOB_TOKEN',
32
+ 'BITBUCKET_TOKEN',
33
+ 'AZURE_DEVOPS_EXT_PAT',
34
+ 'NPM_AUTH_TOKEN',
35
+ 'YARN_NPM_AUTH_TOKEN',
36
+ 'NUGET_API_KEY',
37
+ 'GOOGLE_APPLICATION_CREDENTIALS',
38
+ 'VAULT_TOKEN',
39
+ 'TERRAFORM_CLOUD_TOKEN',
40
+ 'HEROKU_API_KEY',
41
+ 'SLACK_TOKEN',
42
+ 'PYPI_TOKEN',
43
+ 'TWINE_PASSWORD',
44
+ 'HUAWEI_DOMAIN_TOKEN',
45
+ 'HUAWEI_SECURITY_TOKEN',
46
+ ]);
47
+ // The predicate's prefixes also cover the devkit's own configuration. These
48
+ // names are read by the child's update graph (registry, proxy, state root,
49
+ // binary resolution, install skips), so they pass through unchanged.
50
+ const UPGRADE_PRESERVE_ENV_KEYS = new Set([
51
+ 'HCLOUD_BIN',
52
+ 'HCLOUD_BIN_ARGS_JSON',
53
+ 'HCLOUD_CONFIG_PATH',
54
+ 'HCLOUD_META_DIR',
55
+ 'HCLOUD_OBS_CONFIG_PATH',
56
+ 'HUAWEICLOUD_DEVKIT_DEBUG',
57
+ 'HUAWEICLOUD_DEVKIT_HOME',
58
+ 'HUAWEICLOUD_DEVKIT_SKIP_DSH_PLUGIN_INSTALL',
59
+ 'HUAWEICLOUD_DEVKIT_SKIP_OFFICEACE_DETECT',
60
+ 'HUAWEICLOUD_DEVKIT_SKIP_UPDATE',
61
+ 'HUAWEICLOUD_DEVKIT_TELEMETRY',
62
+ 'HUAWEICLOUD_DEVKIT_TELEMETRY_ENDPOINT',
63
+ 'HUAWEICLOUD_HOME',
64
+ 'HUAWEICLOUD_ICONS_OFFLINE',
65
+ 'HUAWEICLOUD_INJECT_STS_CMD',
66
+ 'HUAWEICLOUD_MCP_POLICY_FILE',
67
+ 'HUAWEICLOUD_NPM_REGISTRY',
68
+ 'HUAWEICLOUD_OPENCODE_PERMISSION_SEAM',
69
+ 'HUAWEICLOUD_REGION',
70
+ 'HUAWEICLOUD_VENDOR_CHALLENGE',
71
+ 'HW_IAM_ENDPOINT',
72
+ 'HW_POOL_TEMPLATE_EPHEMERAL',
73
+ 'HW_POOL_TEMPLATE_PERSISTENT',
74
+ 'HW_REGION',
75
+ 'HW_SANDBOX_POOL_CACHE_PATH',
76
+ 'HW_STS_EXPIRES_AT',
77
+ 'HW_WORKSPACE_ID',
78
+ ]);
79
+ function upgradeEnv(env = process.env) {
80
+ const next = {};
81
+ const registrySpellings = [];
82
+ for (const [key, value] of Object.entries(env)) {
83
+ // The vault predicate trims its spelling; the strip and preserve lists must
84
+ // agree, so a padded vendor key strips and a padded preserve key survives.
85
+ const upper = key.trim().toUpperCase();
86
+ if (upper === 'HUAWEICLOUD_NPM_REGISTRY')
87
+ continue;
88
+ if (upper === 'NPM_CONFIG_REGISTRY')
89
+ registrySpellings.push(key);
90
+ // npm's own auth channels are resolved after the loop through the shared
91
+ // spelling rule, matching the pre-flight query's bearer exactly.
92
+ if (upper === 'NPM_TOKEN' || upper === 'NODE_AUTH_TOKEN')
93
+ continue;
94
+ if (UPGRADE_PRESERVE_ENV_KEYS.has(upper)) {
95
+ // A padded spelling cannot reach the child's exact-name lookup: forward
96
+ // the trimmed name, letting an existing exact spelling win.
97
+ const canonical = key.trim();
98
+ if (key === canonical || next[canonical] === undefined)
99
+ next[canonical] = value;
100
+ continue;
101
+ }
102
+ if (isCredentialEnvVarName(key) || UPGRADE_EXTRA_CREDENTIAL_ENV_KEYS.has(upper))
103
+ continue;
104
+ next[key] = value;
105
+ }
106
+ // One canonical channel through the shared resolver, so the child's own
107
+ // devkit lookup, npm's pin, and the pre-flight query cannot disagree; empty
108
+ // and whitespace count as unset everywhere, and an unset override never pins.
109
+ const authKeys = ['NPM_TOKEN', 'NODE_AUTH_TOKEN'];
110
+ for (const name of authKeys) {
111
+ const token = resolveEnvSpelling(env, name);
112
+ if (token)
113
+ next[name] = token;
114
+ }
115
+ const registry = resolveRegistryOverride(env);
116
+ if (registry) {
117
+ next.HUAWEICLOUD_NPM_REGISTRY = registry;
118
+ for (const key of registrySpellings)
119
+ delete next[key];
120
+ next.npm_config_registry = registry;
121
+ }
122
+ return next;
123
+ }
12
124
  function defaultSpawn(command, args, options) {
13
125
  // The args join into the command string before the spawn: options carries
14
126
  // shell:true (the #643 npm.cmd routing; the target interpolation stays
@@ -19,6 +131,962 @@ function defaultSpawn(command, args, options) {
19
131
  // injected test doubles.
20
132
  return spawnSync([command, ...args].join(' '), options);
21
133
  }
134
+ // npm reports failures as `npm error ...` lines (npm 7+) or `npm ERR! ...`
135
+ // (legacy), with ANSI color, pty spinners, warnings, notices, and log pointers
136
+ // around them. The tail is boilerplate, so the reason keeps the identifying
137
+ // code line plus the human diagnostic when the npm block wins; a strong
138
+ // code-less line wins alone, and a weak one inherits the code line (#1117).
139
+ const ESCAPE = String.fromCharCode(27);
140
+ const ANSI_ESCAPE = new RegExp(`${ESCAPE}\\[[0-9;?]*[A-Za-z]`, 'g');
141
+ const SINGLE_FRAME_BEFORE_ESCAPE = new RegExp(`^[|\\\\/-](?=${ESCAPE})`);
142
+ const LOG_POINTER_SUFFIX = /\s*(?:npm error\s+)?(?:A complete log of this run can be found in:|For a full report see:|(?:完整的运行日志|本次运行的完整日志)可在以下位置(?:找到|查看)[::]|Please include the following file with any support request:).*$/;
143
+ const DIAGNOSTIC_HINT = /\b[A-Za-z]*Error\b|\b(?:failed|failure|fatal|unknown|unsupported|stopped|cannot|unable)\b|permission denied|错误|失败|不支持|未知/i;
144
+ // Error-name starts: Error, TypeError, RangeError, ReferenceError, SyntaxError,
145
+ // and the bracketed dump header `[TypeError: ...] {`.
146
+ const ERROR_NAME = /^(?:\[?[A-Za-z]*Error\b|fatal\b|FATAL\b)/;
147
+ // Errno names are a closed vocabulary (POSIX plus npm's own codes), so
148
+ // membership is the shape test real errno tokens have. An English progress
149
+ // word cannot masquerade no matter how the vocabulary of prose grows
150
+ // (EVICTED, ENQUEUED, EVALUATING, ERRORS, and every future sibling).
151
+ const ERRNO_SHAPE = /^E[A-Z0-9][A-Z0-9_]+$/;
152
+ const ERRNO_CODES = new Set([
153
+ 'E2BIG',
154
+ 'EACCES',
155
+ 'EADDRINUSE',
156
+ 'EADDRNOTAVAIL',
157
+ 'EAFNOSUPPORT',
158
+ 'EAGAIN',
159
+ 'EALREADY',
160
+ 'EBADF',
161
+ 'EBADMSG',
162
+ 'EBUSY',
163
+ 'ECANCELED',
164
+ 'ECHILD',
165
+ 'ECONNABORTED',
166
+ 'ECONNREFUSED',
167
+ 'ECONNRESET',
168
+ 'EDEADLK',
169
+ 'EDESTADDRREQ',
170
+ 'EDOM',
171
+ 'EDQUOT',
172
+ 'EEXIST',
173
+ 'EFAULT',
174
+ 'EFBIG',
175
+ 'EHOSTDOWN',
176
+ 'EHOSTUNREACH',
177
+ 'EIDRM',
178
+ 'EILSEQ',
179
+ 'EINPROGRESS',
180
+ 'EINTR',
181
+ 'EINVAL',
182
+ 'EIO',
183
+ 'EISCONN',
184
+ 'EISDIR',
185
+ 'ELOOP',
186
+ 'EMFILE',
187
+ 'EMLINK',
188
+ 'EMSGSIZE',
189
+ 'EMULTIHOP',
190
+ 'ENAMETOOLONG',
191
+ 'ENETDOWN',
192
+ 'ENETRESET',
193
+ 'ENETUNREACH',
194
+ 'ENFILE',
195
+ 'ENOBUFS',
196
+ 'ENODATA',
197
+ 'ENODEV',
198
+ 'ENOENT',
199
+ 'ENOEXEC',
200
+ 'ENOLCK',
201
+ 'ENOLINK',
202
+ 'ENOMEM',
203
+ 'ENOMSG',
204
+ 'ENOPROTOOPT',
205
+ 'ENOSPC',
206
+ 'ENOSR',
207
+ 'ENOSTR',
208
+ 'ENOSYS',
209
+ 'ENOTCONN',
210
+ 'ENOTDIR',
211
+ 'ENOTEMPTY',
212
+ 'ENOTRECOVERABLE',
213
+ 'ENOTSOCK',
214
+ 'ENOTSUP',
215
+ 'ENOTTY',
216
+ 'ENXIO',
217
+ 'EOPNOTSUPP',
218
+ 'EOVERFLOW',
219
+ 'EOWNERDEAD',
220
+ 'EPERM',
221
+ 'EPIPE',
222
+ 'EPROTO',
223
+ 'EPROTONOSUPPORT',
224
+ 'EPROTOTYPE',
225
+ 'ERANGE',
226
+ 'EROFS',
227
+ 'ESPIPE',
228
+ 'ESRCH',
229
+ 'ESTALE',
230
+ 'ETIME',
231
+ 'ETIMEDOUT',
232
+ 'ETXTBSY',
233
+ 'EWOULDBLOCK',
234
+ 'EXDEV',
235
+ 'EAI_AGAIN',
236
+ 'EUSAGE',
237
+ 'ENOGIT',
238
+ 'EMISSINGROOT',
239
+ 'ELOCKVERIFY',
240
+ 'EINTEGRITY',
241
+ 'EINVALIDPACKAGENAME',
242
+ 'ECOMPROMISED',
243
+ 'EAI_SYSTEM',
244
+ 'EAI_SOCKTYPE',
245
+ 'EAI_SERVICE',
246
+ 'EAI_OVERFLOW',
247
+ 'EAI_NONAME',
248
+ 'EAI_MEMORY',
249
+ 'EAI_FAIL',
250
+ 'EAI_NODATA',
251
+ 'E404',
252
+ 'E401',
253
+ 'E403',
254
+ 'E426',
255
+ 'E429',
256
+ 'E500',
257
+ 'EBADENGINE',
258
+ 'EBADPLATFORM',
259
+ 'EJSONPARSE',
260
+ 'ELIFECYCLE',
261
+ 'EMAXREDIRECT',
262
+ 'EMAXREDIRECTS',
263
+ 'ENOAUDIT',
264
+ 'ENOLOCAL',
265
+ 'ENOLOCK',
266
+ 'ENOSELF',
267
+ 'ENOVERSIONS',
268
+ 'ENOTCACHED',
269
+ 'ENOTFOUND',
270
+ 'EOTP',
271
+ 'EREGISTRY',
272
+ 'ERESOLVE',
273
+ 'ETARGET',
274
+ 'EUNKNOWNCOMMAND',
275
+ 'EUNSUPPORTEDPROTOCOL',
276
+ ]);
277
+ function isErrnoToken(token) {
278
+ return Boolean(token && ERRNO_SHAPE.test(token) && ERRNO_CODES.has(token));
279
+ }
280
+ function stripLogPointerSuffix(line) {
281
+ return line.replace(LOG_POINTER_SUFFIX, '').trim();
282
+ }
283
+ function shiftNpmErrorToken(line) {
284
+ const errorAt = line.search(/npm error\b/);
285
+ if (errorAt === 0)
286
+ return line;
287
+ if (errorAt > 0 && /^[^\x21-\x7e]*$/.test(line.slice(0, errorAt)))
288
+ return line.slice(errorAt);
289
+ // npm 9 under a pty glues progress text before the legacy token; nothing
290
+ // printable there is a diagnostic of its own, so the token still moves.
291
+ const legacyAt = line.search(/npm ERR!/);
292
+ return legacyAt > 0 ? line.slice(legacyAt) : line;
293
+ }
294
+ function normalizeNpmLine(line) {
295
+ const withoutSpinner = line
296
+ .trim()
297
+ .replace(SINGLE_FRAME_BEFORE_ESCAPE, '')
298
+ .replace(ANSI_ESCAPE, '')
299
+ .replace(/^[\u2800-\u28ff\s]+/, '')
300
+ .replace(/^[|\\/-]{2,}/, '');
301
+ const shifted = shiftNpmErrorToken(withoutSpinner);
302
+ return stripLogPointerSuffix(shifted.replace(/^npm ERR!\s?/, 'npm error '));
303
+ }
304
+ function npmPayload(line) {
305
+ return line.replace(/^npm error\s*/, '');
306
+ }
307
+ function isNpmErrorLine(line) {
308
+ return /^npm error\b/.test(line);
309
+ }
310
+ // A pointer line carries nothing but the npm log path (optionally behind a
311
+ // label); a sentence that mentions the path keeps its content.
312
+ function isPointerOnlyLine(line) {
313
+ const payload = npmPayload(line)
314
+ .trim()
315
+ .replace(/^(?:[A-Za-z][\w .-]*|[\u4e00-\u9fa5][\u4e00-\u9fa5\w .-]*)\s*[::]\s*/, '');
316
+ if (!/(?:-debug(?:-\d+)?\.log|-eresolve-report\.txt)$/.test(payload))
317
+ return false;
318
+ if (/^(?:[A-Za-z]:[\\/]|~[\\/]|\.{0,2}[\\/])/.test(payload))
319
+ return true;
320
+ // A bare relative log name ("npm-debug.log", "logs/npm-debug-0.log").
321
+ return !/\s/.test(payload) && !payload.includes(':');
322
+ }
323
+ // V8 frames: `at`, optional async/new, a token (optionally aliased `[as x]`),
324
+ // then a location in parentheses, a `file:`/`node:`/`<anonymous>` target, a
325
+ // `wasm` frame, or a bare `:<line>:<col>` tail. A sentence that opens with
326
+ // "at least" or "at startup (retry 1)" carries prose, not a location.
327
+ function isStackFrame(payload) {
328
+ const match = /^\s*at\s+(?:async\s+|new\s+)?(.+)$/.exec(payload);
329
+ if (!match)
330
+ return false;
331
+ const rest = match[1].trim();
332
+ if (rest === '<anonymous>')
333
+ return true;
334
+ if (/^wasm[-:]/.test(rest) || /\bwasm-function\b/.test(rest))
335
+ return true;
336
+ const call = /^\S+(?:\s+\[as [^\]]+\])?\s*\(([^)]*)\)\s*{?\s*$/.exec(rest);
337
+ if (call) {
338
+ const location = call[1].trim();
339
+ return location === '<anonymous>' || /^index \d+$/.test(location) || /^\S+:\d+(?::\d+)?$/.test(location);
340
+ }
341
+ // Nested eval frames close more than one paren (eval at <anonymous> (...)),
342
+ // so the flat paren match above cannot span them; a frame ends with a paren
343
+ // and carries a location token.
344
+ if (/\)\s*$/.test(rest) && /(?:file:|node:|\[eval\]|eval at |<anonymous>|:\d+(?::\d+)?)/.test(rest)) {
345
+ return true;
346
+ }
347
+ return /^(?:file:|node:)\S*:\d+:\d+\b/.test(rest) || /^\S+:\d+:\d+\b/.test(rest);
348
+ }
349
+ function isNpmNoiseLine(line) {
350
+ if (/^Node\.js v\d/.test(line) || /^\s*\^\s*$/.test(line))
351
+ return true;
352
+ if (/^Require stack:/.test(line) || /^\s*-\s+[/~]\S*$/.test(line))
353
+ return true;
354
+ if (/^\s*throw err;\s*$/.test(line))
355
+ return true;
356
+ if (!/[\p{L}\p{N}]/u.test(line))
357
+ return true;
358
+ if (/^(?:npm warn\b|npm notice\b|\(node:\d+\))/i.test(line))
359
+ return true;
360
+ // Node's non-deprecation warning footer: the `(node:…)` header is dropped
361
+ // above, but its continuation lines are boilerplate too (the
362
+ // MODULE_TYPELESS_PACKAGE_JSON / ExperimentalWarning family). Anchor on the
363
+ // emission shapes, not the word "warning", which can ride a real diagnostic.
364
+ if (/^\(Use `node --trace-warnings\b[^`]*` to show where the warning was created\)$/.test(line))
365
+ return true;
366
+ if (/^\(Use `node --trace-uncaught\b[^`]*` to show where the exception was thrown\)$/.test(line))
367
+ return true;
368
+ if (/^Reparsing as ES module because module syntax was detected\b/.test(line))
369
+ return true;
370
+ if (/^To eliminate this warning, add "type": "module" to\b/.test(line))
371
+ return true;
372
+ // npm's log channels are not diagnostics: every `npm <channel>` prefix is
373
+ // noise except the error channel and the `info run` echo of a script.
374
+ if (/^npm\s+(?:notice|warn|info|verbose|verb(?:ose)?|http|silly|sill|timing)\b/i.test(line) &&
375
+ !/^npm info run\b/i.test(line)) {
376
+ return true;
377
+ }
378
+ if (/DeprecationWarning|trace-deprecation/i.test(line))
379
+ return true;
380
+ if (/^gyp info\b/i.test(line))
381
+ return true;
382
+ if (/^added \d+ packages? in\b/i.test(line))
383
+ return true;
384
+ const payload = npmPayload(line);
385
+ return (/^A complete log of this run can be found in:/.test(payload) ||
386
+ /^For a full report see:/.test(payload) ||
387
+ /^Log files were not written due to an error writing to the directory:/.test(payload) ||
388
+ /^You can rerun the command with `--loglevel=verbose`/.test(payload) ||
389
+ isPointerOnlyLine(line) ||
390
+ isStackFrame(payload));
391
+ }
392
+ // Tiers: a strong failure marker, then failure words, then the plain position
393
+ // tier, and metadata last. The strongest tier takes its later line (a fatal
394
+ // line lands after a retry marker), the hint tier its earlier one (the real
395
+ // failure precedes cleanup chatter), and the position tier the later line in
396
+ // the codeless branch.
397
+ function isNpmScriptResult(line) {
398
+ return /\{\s*code:\s*(?:-?\d+|null)\s*,?\s*signal:/.test(line);
399
+ }
400
+ function isFailingScriptResult(line) {
401
+ const match = /\{\s*code:\s*(-?\d+|null)\s*,?\s*signal:\s*(null|'[^']*'|"[^"]*")/.exec(line);
402
+ if (!match)
403
+ return false;
404
+ return !(match[1] === '0' && match[2] === 'null');
405
+ }
406
+ // npm's echo of a failing script: the block's `command <shell> -c <script>`
407
+ // line (sh, bash, or cmd.exe) and the npm-prefixed `info run` echo. A child
408
+ // line that merely starts with "command:" or a shell word is not an echo.
409
+ function isEchoLine(line, payload) {
410
+ if (isNpmScriptResult(line) || isNpmScriptResult(payload))
411
+ return false;
412
+ if (/^npm info run\b/.test(line))
413
+ return true;
414
+ // npm's block echo, whichever shell it named; `command failed` is metadata.
415
+ if (/^npm error\s+command\s+/i.test(line) && !/^command failed$/i.test(payload))
416
+ return true;
417
+ // A bare shell lead counts only when the -c payload is one command (quoted
418
+ // or a single token), not a child sentence that merely starts with one.
419
+ const commandEnd = /^(?:"[^"]*"|'[^']*'|\S+)\s*$/;
420
+ const shell = /^(?:\S*\/)?(?:ba|z|k|da)?sh\s+-c\s+(.*)$/.exec(payload)?.[1];
421
+ if (shell && commandEnd.test(shell))
422
+ return true;
423
+ const cmd = /^cmd(?:\.exe)?\b[^]*?\/c\s+(.*)$/i.exec(payload)?.[1];
424
+ if (cmd && commandEnd.test(cmd))
425
+ return true;
426
+ return false;
427
+ }
428
+ function lineRank(line) {
429
+ const payload = npmPayload(line);
430
+ // Dump punctuation demotes before any token scan: a `[cause]:` line carrying
431
+ // an errno code is still dump metadata, not a diagnosis.
432
+ if (/^\[cause\]:/.test(payload))
433
+ return 4;
434
+ // The echo test runs before the strong-marker scans: an echo that quotes the
435
+ // child's own errno token must not tie with the child's line.
436
+ if (isEchoLine(line, payload))
437
+ return 3;
438
+ if (ERROR_NAME.test(payload))
439
+ return 0;
440
+ const token = /^([A-Z0-9_]+)(?=:|\s|$)/.exec(payload)?.[1];
441
+ if (isErrnoToken(token))
442
+ return 0;
443
+ for (const match of payload.matchAll(/(?<=:\s)(E[A-Z0-9][A-Z0-9_]+)\b/g)) {
444
+ if (isErrnoToken(match[1]))
445
+ return 0;
446
+ }
447
+ if (!payload || /^(?:errno|syscall|path|code|command failed)\b/.test(payload))
448
+ return 4;
449
+ if (/^\s*[A-Za-z_]\w*:\s*(?:'[^']*'|"[^"]*"|-?\d+|\[[^\]]*\])\s*,?\s*$/.test(payload))
450
+ return 4;
451
+ if (/^\s*[A-Za-z_]\w*:\s*\[[^\]]*\]\s*,?\s*$/.test(payload))
452
+ return 4;
453
+ if (/^\s*requireStack:\s*\[.*$/.test(payload) || /^\s*'[^']*',?\s*$/.test(payload))
454
+ return 4;
455
+ if (isNpmScriptResult(payload))
456
+ return 4;
457
+ // npm's echo of the failing script carries the child's words in quotes, so it
458
+ // must not tie with the child's own line; it is the honest fallback only when
459
+ // the child printed nothing.
460
+ if (DIAGNOSTIC_HINT.test(payload))
461
+ return 1;
462
+ return 2;
463
+ }
464
+ function lastFailingResult(entries) {
465
+ return entries.filter((entry) => isNpmScriptResult(entry.line) && isFailingScriptResult(entry.line)).at(-1);
466
+ }
467
+ // INVARIANT (gyp preference): the preference is PAIRED, never tier-wide. A gyp
468
+ // banner (`gyp ERR! build/configure error`) is demoted only in favor of a gyp
469
+ // `stack Error:` line in the same rank-1 tier; a non-gyp rank-1 line (a
470
+ // compiler diagnostic, a make line, any child text) is NEVER displaced by a
471
+ // gyp line. The selector's usual earlier-wins order stands everywhere else.
472
+ // Every site that selects from the rank-1 tier routes through this helper.
473
+ const GYP_BANNER = /^gyp ERR! (?:build|configure) error\b/;
474
+ const GYP_STACK_CAUSE = /^gyp ERR! stack Error\b/;
475
+ function pickRankOneLine(hits) {
476
+ const first = hits[0];
477
+ if (!GYP_BANNER.test(npmPayload(first.line)))
478
+ return first;
479
+ return hits.find((entry) => GYP_STACK_CAUSE.test(npmPayload(entry.line))) ?? first;
480
+ }
481
+ // The promoted-dying-words sites see a rank-<=2 window, not a single tier;
482
+ // they follow the selector's tier order (rank 0 later, rank 1 through the
483
+ // paired helper, otherwise the last line).
484
+ function pickPromotedLine(entries) {
485
+ const rankZero = entries.filter((entry) => lineRank(entry.line) === 0);
486
+ if (rankZero.length)
487
+ return rankZero.at(-1);
488
+ const rankOne = entries.filter((entry) => lineRank(entry.line) === 1);
489
+ if (rankOne.length)
490
+ return pickRankOneLine(rankOne);
491
+ return entries.at(-1);
492
+ }
493
+ function lastEchoBefore(entries, index) {
494
+ return entries.filter((entry) => entry.index < index && lineRank(entry.line) === 3).at(-1);
495
+ }
496
+ function selectFailureLine(rawEntries, { positionLast, echoAllowed = () => true }) {
497
+ // A recovery announcement (in a block body or in the plain stderr) is never a
498
+ // candidate; skipping it lets the next truthful tier of the same capture win.
499
+ const entries = rawEntries.filter((entry) => !isRecoveryAnnouncement(entry.line));
500
+ for (const rank of [0, 1, 2, 3, 4]) {
501
+ const hits = entries.filter((entry) => lineRank(entry.line) === rank);
502
+ if (!hits.length)
503
+ continue;
504
+ if (rank === 3) {
505
+ // The echo tier names the failing script: the last echo that carries the
506
+ // failing result's own package/script identity wins, so a nesting script's
507
+ // nearer echo cannot stand in; an echo that belongs to a recovered window
508
+ // never qualifies; else the last allowed echo.
509
+ const allowed = hits.filter((entry) => echoAllowed(entry.index));
510
+ if (!allowed.length)
511
+ continue;
512
+ const failing = lastFailingResult(entries);
513
+ const identity = failing ? npmRunIdentity(failing.line) : undefined;
514
+ const identityPaired = identity
515
+ ? allowed
516
+ .filter((entry) => entry.index < failing.index && lineRank(entry.line) === 3 && npmRunIdentity(entry.line) === identity)
517
+ .at(-1)
518
+ : undefined;
519
+ const paired = identityPaired ?? (failing ? allowed.filter((entry) => entry.index < failing.index).at(-1) : undefined);
520
+ const chosen = paired ?? allowed.at(-1);
521
+ return { line: chosen.line, rank, index: chosen.index };
522
+ }
523
+ const later = rank === 0 || (rank === 2 && positionLast);
524
+ const chosen = later ? hits.at(-1) : rank === 1 ? pickRankOneLine(hits) : hits[0];
525
+ return { line: chosen.line, rank, index: chosen.index };
526
+ }
527
+ return undefined;
528
+ }
529
+ function errorBlocks(codeEntries, otherEntries, codelessEntries = []) {
530
+ return codeEntries.map((code, position) => {
531
+ const next = codeEntries[position + 1]?.index ?? Number.POSITIVE_INFINITY;
532
+ // A lifecycle line (an info-run echo or a result) starts the next step:
533
+ // the block body (npm's error metadata) cannot own a later step's echo.
534
+ const bare = codelessEntries.find((entry) => entry.index > code.index &&
535
+ entry.index < next &&
536
+ (/^npm info run\b/.test(entry.line) || isNpmScriptResult(entry.line)))?.index ?? next;
537
+ const boundary = Math.min(next, bare);
538
+ return {
539
+ code,
540
+ entries: otherEntries.filter((entry) => entry.index > code.index && entry.index < boundary),
541
+ };
542
+ });
543
+ }
544
+ function pickInBlock(block) {
545
+ const entries = block.entries.filter((entry) => !isRecoveryAnnouncement(entry.line));
546
+ for (const rank of [0, 1, 2, 3, 4]) {
547
+ const hits = entries.filter((entry) => lineRank(entry.line) === rank);
548
+ if (!hits.length)
549
+ continue;
550
+ // The in-block pick mirrors the selector it overrides: the strongest tier
551
+ // takes its later line (a fatal line follows a retry marker).
552
+ const hit = rank === 0 ? hits.at(-1) : rank === 1 ? pickRankOneLine(hits) : hits[0];
553
+ return { line: hit.line, rank, index: hit.index };
554
+ }
555
+ return undefined;
556
+ }
557
+ function npmRunIdentity(line) {
558
+ return /^npm info run (\S+ \S+)\b/.exec(npmPayload(line))?.[1];
559
+ }
560
+ // A line that *announces* a recovery is evidence the step succeeded, not a
561
+ // dying word. A token at the sentence end is the canonical announcement
562
+ // ("... failed once, recovered"); the sentence's final clause wins over an
563
+ // earlier failure mention ("first attempt failed, recovered, fine"), while a
564
+ // governing verb/negation ("failed to recover", "could not yet recover")
565
+ // keeps the line a diagnostic.
566
+ const RECOVER_TOKEN = /\brecover(?:ed|ing|s|y|ies)?\b/i;
567
+ const RECOVER_CONTINUATION = /^\s*(?:[.!?]?\s*$|,\s*(?:continuing\b|anyway\b|complete\b|succeeded\b|ok\b|fine\b).*|\s+(?:complete|completely|fully|succeeded|ok|fine)\b.*)$/i;
568
+ // The governing verb/negation before the token turns a sentence into a failure
569
+ // statement ("failed to recover", "not yet recovered", "no recovery"), even
570
+ // when the recover token is the sentence's last word. Adverbs may sit before or
571
+ // after `to` ("failed to fully recover", "unable to completely recover").
572
+ const RECOVER_GOVERNING = /(?:failed|failure|refused|rejected|unable|could not|cannot|can't|not|never|no)\s+(?:(?:yet|still|even|ever|really|quite|fully|actually|entirely|completely|eventually)\s+)*(?:to\s+(?:(?:yet|still|even|ever|really|quite|fully|actually|entirely|completely|eventually)\s+)*)?$/i;
573
+ // A recovered step's continuation notices ("falling back to the bundled
574
+ // toolchain", "retrying from snapshot", "using cached copy of previous build",
575
+ // "best-effort rebuild only", "degraded mode active"): "falling back" and
576
+ // "retrying" are announcements only in their full forms, so a failing step's
577
+ // bare dying words surface, while the cached/best-effort/degraded idiom tokens
578
+ // mark an announcement wherever they appear. A dying line that merely contains
579
+ // one of those fallback tokens is therefore treated as a recovered-step notice
580
+ // (a ledgered trade).
581
+ const CONTINUATION_ANNOUNCEMENT = /\b(?:falling back to|retrying from|using cached|best-effort|degraded)\b/i;
582
+ function isRecoveryAnnouncement(line) {
583
+ const payload = npmPayload(line);
584
+ // A command/echo line names a script, not prose: "sh -c node recover" is not
585
+ // a recovery announcement.
586
+ if (/^command\b/i.test(payload) ||
587
+ /^(?:\S*\/)?(?:ba|z|k|da)?sh\s+-c\b/i.test(payload) ||
588
+ /^cmd(?:\.exe)?\s/i.test(payload)) {
589
+ return false;
590
+ }
591
+ const match = RECOVER_TOKEN.exec(payload);
592
+ if (match) {
593
+ const prefix = payload.slice(0, match.index);
594
+ const suffix = payload.slice(match.index + match[0].length);
595
+ // Governing negation/verb first: the sentence-final shortcut must not eat it.
596
+ if (RECOVER_GOVERNING.test(prefix))
597
+ return false;
598
+ // The recovery is the sentence's final clause: a failure mention earlier in
599
+ // the sentence ("first attempt failed, recovered, fine") does not veto it.
600
+ return RECOVER_CONTINUATION.test(suffix);
601
+ }
602
+ const continuation = CONTINUATION_ANNOUNCEMENT.exec(payload);
603
+ if (!continuation)
604
+ return false;
605
+ return !RECOVER_GOVERNING.test(payload.slice(0, continuation.index));
606
+ }
607
+ function isCauseLine(line) {
608
+ const payload = npmPayload(line);
609
+ if (!/^\[cause\]:/.test(payload))
610
+ return false;
611
+ const rest = payload.replace(/^\[cause\]:\s*/, '');
612
+ if (ERROR_NAME.test(rest))
613
+ return true;
614
+ const token = /^([A-Z0-9_]+)(?=:|\s|$)/.exec(rest)?.[1];
615
+ return isErrnoToken(token);
616
+ }
617
+ function extractNpmFailureReason(execResult) {
618
+ // Keep the untrimmed source beside the normalized lines: the blank-line and
619
+ // stack-frame shapes the warning scan needs survive only in the raw text.
620
+ const sourceLines = String(execResult.stderr || '').split(/\r?\n/);
621
+ const rawLines = sourceLines.map((line) => normalizeNpmLine(line));
622
+ // A Node crash preamble carries three lines the per-line rules cannot judge:
623
+ // the `file:line` header, the source snippet, and the caret under it.
624
+ const crashPreamble = new Set();
625
+ rawLines.forEach((line, index) => {
626
+ const header = /^\S+:\d+$/.test(line);
627
+ const snippet = Boolean(rawLines[index + 1] && /[;=()]/.test(rawLines[index + 1]));
628
+ const caret = /^\s*\^+\s*$/.test(rawLines[index + 2] ?? '');
629
+ if (header && snippet && caret) {
630
+ crashPreamble
631
+ .add(index)
632
+ .add(index + 1)
633
+ .add(index + 2);
634
+ }
635
+ });
636
+ // Node's warning continuation lines are boilerplate whatever their wording.
637
+ // The region ends at the FIRST structural closer met scanning forward from
638
+ // the header — a traced stack-frame run (its last frame), an `npm error`
639
+ // block start (the last line before it is kept as the child's possible
640
+ // diagnostic), a blank line, the `(Use …)` footer, or a crash/diagnostic
641
+ // header (the lines before it are excluded, the header itself is kept). A
642
+ // later closer never re-extends a region an earlier one already closed: the
643
+ // outer loop re-scans from every warning header, which covers adjacent
644
+ // warnings without a separate header clause.
645
+ const WARNING_FOOTER = /^\(Use `node --trace-(?:warnings|deprecation)\b[^`]*` to show where the warning was created\)$/;
646
+ const WARNING_HEADER = /^\(node:\d+\)/;
647
+ const frameLine = (raw) => /^\s+at\s/.test(raw);
648
+ const crashHeader = (line) => /^\S+:\d+$/.test(line);
649
+ const diagnosticHeader = (line) => /^(?:\[?[A-Za-z]*Error\b|[Ff][Aa][Tt][Aa][Ll]\b|Uncaught\b)/.test(line);
650
+ const warningContinuation = new Set();
651
+ for (let index = 0; index < rawLines.length; index += 1) {
652
+ if (!WARNING_HEADER.test(rawLines[index]))
653
+ continue;
654
+ let end = -1;
655
+ let frameSeen = false;
656
+ for (let cursor = index + 1; cursor < rawLines.length; cursor += 1) {
657
+ const raw = sourceLines[cursor] ?? '';
658
+ const line = rawLines[cursor];
659
+ if (frameLine(raw)) {
660
+ frameSeen = true;
661
+ end = cursor;
662
+ continue;
663
+ }
664
+ if (frameSeen)
665
+ break;
666
+ if (!raw.trim()) {
667
+ end = cursor - 1;
668
+ break;
669
+ }
670
+ if (isNpmErrorLine(line)) {
671
+ end = cursor - 2;
672
+ break;
673
+ }
674
+ if (WARNING_FOOTER.test(line)) {
675
+ end = cursor;
676
+ break;
677
+ }
678
+ if (crashHeader(line) || diagnosticHeader(line)) {
679
+ end = cursor - 1;
680
+ break;
681
+ }
682
+ }
683
+ for (let cursor = index + 1; cursor <= end; cursor += 1)
684
+ warningContinuation.add(cursor);
685
+ }
686
+ // Every entry keeps its raw position: the code candidate, the block and the
687
+ // echo are compared against the success window in one index space, so a
688
+ // duplicate text line can never be re-resolved to its first occurrence.
689
+ const entries = rawLines
690
+ .map((line, index) => ({ line, index }))
691
+ .filter((entry) => Boolean(entry.line) &&
692
+ !crashPreamble.has(entry.index) &&
693
+ !warningContinuation.has(entry.index) &&
694
+ !isNpmNoiseLine(entry.line));
695
+ const codeEntries = entries.filter((entry) => isNpmErrorLine(entry.line) && /^code \S+/.test(npmPayload(entry.line)));
696
+ const otherEntries = entries.filter((entry) => isNpmErrorLine(entry.line) && !codeEntries.some((code) => code.index === entry.index));
697
+ const codelessEntries = entries.filter((entry) => !isNpmErrorLine(entry.line));
698
+ const codeFor = (target) => (target ? codeEntries.filter((entry) => entry.index <= target.index).at(-1) : undefined)?.line ??
699
+ codeEntries.at(-1)?.line;
700
+ const isSuccessAssertion = (line) => /^gyp info ok\b/i.test(line) ||
701
+ /^prebuilt binary installed\b/i.test(line) ||
702
+ (isNpmScriptResult(line) && !isFailingScriptResult(line));
703
+ const lastSuccessIndex = (before) => {
704
+ let found = -1;
705
+ rawLines.forEach((line, index) => {
706
+ if (index < before && isSuccessAssertion(line))
707
+ found = index;
708
+ });
709
+ return found;
710
+ };
711
+ // The gate is a failing pair: a failure result line with its own echo. A
712
+ // successful script's echo pair, or a lone echo, proves nothing about the
713
+ // failing step.
714
+ const failing = lastFailingResult(codelessEntries);
715
+ // npm's echo of the failing script may be a bare shell line or the block's own
716
+ // `npm error command` line; the pair is the result line plus the echo that
717
+ // names the same package and lifecycle script. A nesting script's nearer echo
718
+ // must not stand in for the failing step, and a result line whose echo landed
719
+ // after it (a dying step that printed `gyp info ok` then its result) is not a
720
+ // pair.
721
+ const failingIdentity = failing ? npmRunIdentity(failing.line) : undefined;
722
+ // A code-0 result owns the lines between its echo and its result, whether or
723
+ // not it shares the failing step's identity: a recovered run of the same
724
+ // package is a different step. Each result claims its nearest preceding echo
725
+ // of the same identity that no earlier result claimed, so interleaved
726
+ // same-identity siblings get one window each instead of both anchoring at the
727
+ // later echo.
728
+ // Under concurrency a later successful run of the same package must not claim
729
+ // the echo the failing pair needs: the pair's anchoring wins.
730
+ const reservedPairEchoes = new Set();
731
+ if (failing && failingIdentity) {
732
+ const identityEchoes = entries.filter((entry) => entry.index < failing.index && lineRank(entry.line) === 3 && npmRunIdentity(entry.line) === failingIdentity);
733
+ // The pair's own echo is the one followed by its failure-shaped rank-0
734
+ // dying words (a FATAL/Error header). An errno diagnostic follower (for
735
+ // example "EACCES: permission denied, using user cache instead") can be a
736
+ // successful sibling's recovered evidence, so it never reserves an echo;
737
+ // under concurrency the other same-identity echo belongs to the sibling's
738
+ // run.
739
+ const strongWordEcho = identityEchoes
740
+ .filter((echo) => {
741
+ const next = codelessEntries.find((entry) => entry.index > echo.index && entry.index < failing.index);
742
+ return Boolean(next &&
743
+ lineRank(next.line) === 0 &&
744
+ ERROR_NAME.test(npmPayload(next.line)) &&
745
+ !isNpmScriptResult(next.line) &&
746
+ !isRecoveryAnnouncement(next.line));
747
+ })
748
+ .at(-1);
749
+ // A lone echo cannot be split between two runs; reserving it would leave
750
+ // the pair with nothing, so the sequential claim handles that shape.
751
+ if (strongWordEcho && identityEchoes.length >= 2)
752
+ reservedPairEchoes.add(strongWordEcho.index);
753
+ }
754
+ const recoveredWindows = [];
755
+ const claimedEchoes = new Set();
756
+ for (const result of codelessEntries) {
757
+ if (!isNpmScriptResult(result.line) || isFailingScriptResult(result.line))
758
+ continue;
759
+ const identity = npmRunIdentity(result.line);
760
+ if (!identity)
761
+ continue;
762
+ const echo = entries
763
+ .filter((entry) => entry.index < result.index &&
764
+ lineRank(entry.line) === 3 &&
765
+ npmRunIdentity(entry.line) === identity &&
766
+ !claimedEchoes.has(entry.index) &&
767
+ !reservedPairEchoes.has(entry.index))
768
+ .at(-1);
769
+ if (echo) {
770
+ claimedEchoes.add(echo.index);
771
+ recoveredWindows.push({ start: echo.index, end: result.index });
772
+ }
773
+ // A result with no claimable echo is unattributable: it registers no window.
774
+ }
775
+ const startsRecoveredWindow = (index) => recoveredWindows.some((window) => window.start === index);
776
+ // The failing pair's echo is the step's own: the nearest identity echo that
777
+ // does not belong to a recovered window; a fallback echo that does belong to
778
+ // one leaves the pair unattributable.
779
+ const ownEcho = failing
780
+ ? entries
781
+ .filter((entry) => entry.index < failing.index &&
782
+ lineRank(entry.line) === 3 &&
783
+ npmRunIdentity(entry.line) === failingIdentity &&
784
+ !startsRecoveredWindow(entry.index))
785
+ .at(-1)
786
+ : undefined;
787
+ const fallbackEcho = failing ? lastEchoBefore(entries, failing.index) : undefined;
788
+ const failingPairEcho = ownEcho ?? (fallbackEcho && !startsRecoveredWindow(fallbackEcho.index) ? fallbackEcho : undefined);
789
+ const hasFailingPair = Boolean(failing && failingPairEcho);
790
+ // A nested window whose own echo starts after the failing pair's echo belongs
791
+ // to a nested step and is excluded even when it sits inside the pair's span;
792
+ // only the failing step's own words between its echo and result are in-pair
793
+ // survivors. Boundaries are inclusive: a window's own echo is not a reason.
794
+ const insideFailingPair = (index) => Boolean(failing && failingPairEcho && index > failingPairEcho.index && index < failing.index);
795
+ // A candidate line is excluded when it is a recovery notice or sits in a
796
+ // nested window (one opening after the failing echo). A window opening before
797
+ // the failing echo can interleave with the failing step, so it blocks only its
798
+ // recovery notices; with no failing pair every window blocks its whole span.
799
+ const inNestedWindow = (index) => recoveredWindows.some((window) => index >= window.start && index <= window.end && window.start > (failingPairEcho?.index ?? -1));
800
+ const lineExcluded = (index) => {
801
+ const line = entries.find((entry) => entry.index === index)?.line ?? '';
802
+ // With no failing pair every window start is past the sentinel, so
803
+ // inNestedWindow already covers the whole span.
804
+ return isRecoveryAnnouncement(line) || inNestedWindow(index);
805
+ };
806
+ // A success assertion is recovery evidence only when it precedes the last
807
+ // failing pair: the failing step's own `gyp info ok`, printed after its dying
808
+ // words and before its own result line, is not a recovery.
809
+ const recoverySuccess = failingPairEcho ? lastSuccessIndex(failingPairEcho.index) : -1;
810
+ const echoAllowed = (index) => !startsRecoveredWindow(index);
811
+ let block = selectFailureLine(otherEntries, { positionLast: false, echoAllowed });
812
+ let bare = selectFailureLine(codelessEntries, { positionLast: true, echoAllowed });
813
+ let codeLine = codeFor(block);
814
+ let recoveredSwap = false;
815
+ let bodylessTwin = false;
816
+ const blocks = codeEntries.length ? errorBlocks(codeEntries, otherEntries, codelessEntries) : [];
817
+ const blockBodyEnd = (target) => target.entries.reduce((max, entry) => Math.max(max, entry.index), target.code.index);
818
+ const firstBlockCode = blocks[0]?.code.index ?? -1;
819
+ const lastBlockBodyEnd = blocks.length ? blockBodyEnd(blocks.at(-1)) : -1;
820
+ const inBlockRange = (index) => blocks.some((target) => index >= target.code.index && index <= blockBodyEnd(target));
821
+ // At npm's default loglevel lifecycle result lines do not exist, so a nested
822
+ // step's recovered block is the only visible error text while the failing
823
+ // step said nothing. With no failing pair, the last error block is the only
824
+ // attributable one; a sole nested block whose errno code cannot be tied to
825
+ // the exit falls to the honest exit status, and a child line outside it is
826
+ // the child's dying words.
827
+ if (!hasFailingPair && codeEntries.length) {
828
+ const lastBlock = blocks.at(-1);
829
+ // A duplicate `code N` line with no body of its own (a harness prepend) is
830
+ // one logical block; two populated blocks are distinct steps even when
831
+ // their code text matches, so both shapes keep the last-block rule.
832
+ const previous = blocks.at(-2);
833
+ const distinctLastCode = Boolean(previous) &&
834
+ npmPayload(previous.code.line).replace(/^code\s+/, '') !==
835
+ npmPayload(lastBlock.code.line).replace(/^code\s+/, '');
836
+ // A harness-prepended `code N` line has no block body of its own: it is the
837
+ // same logical block as the one that follows the child diagnostic. A real
838
+ // nested block always carries its own path/echo lines, so shared code text
839
+ // between two populated blocks must not disable the last-block rule.
840
+ const previousHasBody = Boolean(previous && previous.entries.length);
841
+ const overrides = blocks.length > 1 && (distinctLastCode || previousHasBody);
842
+ const picked = pickInBlock(lastBlock);
843
+ const lastHasEcho = lastBlock.entries.some((entry) => lineRank(entry.line) === 3);
844
+ const codeToken = npmPayload(lastBlock.code.line).replace(/^code\s+/, '');
845
+ const numericLast = /^-?\d+$/.test(codeToken);
846
+ const codeTiesExit = numericLast && typeof execResult.status === 'number' && Number(codeToken) === execResult.status;
847
+ // Two populated blocks are a recovered step plus npm's summary of the
848
+ // failing one; a shared code text is the round-25 shape. From three blocks
849
+ // on, a numeric block whose code does not tie to the exit is another nested
850
+ // step even when it carries npm's inner script echo.
851
+ const attributableNumeric = numericLast && (codeTiesExit || blocks.length <= 2 || typeof execResult.status !== 'number');
852
+ const unattributableNested = numericLast
853
+ ? typeof execResult.status === 'number' && execResult.status > 1 && !attributableNumeric
854
+ : !lastHasEcho && typeof execResult.status === 'number' && execResult.status > 1;
855
+ const blockEnd = blockBodyEnd(lastBlock);
856
+ if (overrides) {
857
+ // A body-less trailing duplicate of a tying populated block is npm's
858
+ // summary of the same step: the populated twin's line and echo ride.
859
+ const tiedBodyless = !picked && Boolean(previous?.entries.length) && !distinctLastCode;
860
+ bodylessTwin = tiedBodyless;
861
+ const owner = tiedBodyless ? previous : lastBlock;
862
+ block = (tiedBodyless ? pickInBlock(previous) : picked) ?? {
863
+ line: lastBlock.code.line,
864
+ rank: 4,
865
+ index: lastBlock.code.index,
866
+ };
867
+ codeLine = owner.code.line;
868
+ // The child's earlier chatter belongs to a recovered step; the last
869
+ // block's own echo names the failing script.
870
+ if (bare && bare.index < lastBlock.code.index)
871
+ bare = undefined;
872
+ }
873
+ // An errno-coded block with no echo is a nested/recovered block, not this
874
+ // exit's failure at an exit above 1: plural nested blocks and the
875
+ // metadata-only lone block are the same shape. A child line after the block
876
+ // is the dying words; otherwise the exit status is honest. A top-level errno
877
+ // failure exits 1 and keeps its code line, as do the numeric blocks above.
878
+ if (unattributableNested) {
879
+ const dying = pickPromotedLine(codelessEntries
880
+ .filter((entry) => entry.index > blockEnd && lineRank(entry.line) <= 2)
881
+ .filter((entry) => !isRecoveryAnnouncement(entry.line) &&
882
+ !rawLines.some((line, index) => index > entry.index && isSuccessAssertion(line))));
883
+ if (dying)
884
+ return dying.line;
885
+ block = undefined;
886
+ codeLine = undefined;
887
+ }
888
+ }
889
+ // A block that trails the last failing result is npm's own summary of that
890
+ // step, and it owns the failure even when an earlier, recovered block carries
891
+ // a higher-ranked diagnostic (the verbose/default asymmetry). Its code line
892
+ // is the failing step's, so no recovered block's code can be the reason.
893
+ let trailingSwap = false;
894
+ if (hasFailingPair) {
895
+ const tiesExit = (candidate) => {
896
+ const token = npmPayload(candidate.code.line).replace(/^code\s+/, '');
897
+ return /^-?\d+$/.test(token) && typeof execResult.status === 'number' && Number(token) === execResult.status;
898
+ };
899
+ const trailing = blocks.filter((candidate) => candidate.code.index > failing.index).at(-1);
900
+ const firstFailing = codelessEntries.find((entry) => isNpmScriptResult(entry.line) && isFailingScriptResult(entry.line));
901
+ const tyingTrailing = firstFailing && !(trailing && tiesExit(trailing))
902
+ ? blocks.filter((candidate) => candidate.code.index > firstFailing.index && tiesExit(candidate)).at(-1)
903
+ : undefined;
904
+ const chosen = trailing && tiesExit(trailing) ? trailing : (tyingTrailing ?? trailing);
905
+ const chosenIndex = chosen ? blocks.indexOf(chosen) : -1;
906
+ const previousBlock = chosenIndex > 0 ? blocks[chosenIndex - 1] : undefined;
907
+ const tiedBodyless = chosen &&
908
+ !chosen.entries.length &&
909
+ Boolean(previousBlock?.entries.length) &&
910
+ npmPayload(previousBlock.code.line).replace(/^code\s+/, '') ===
911
+ npmPayload(chosen.code.line).replace(/^code\s+/, '');
912
+ const owner = tiedBodyless ? previousBlock : chosen;
913
+ if (owner) {
914
+ block = pickInBlock(owner) ?? { line: owner.code.line, rank: 4, index: owner.code.index };
915
+ codeLine = owner.code.line;
916
+ // The child's earlier chatter belongs to the step that recovered.
917
+ if (bare && bare.index < owner.code.index)
918
+ bare = undefined;
919
+ trailingSwap = true;
920
+ recoveredSwap = true;
921
+ }
922
+ }
923
+ // A loud successful script (or a gyp error it survived) is not the cause when
924
+ // npm emitted a failing echo pair later: the echo names the failing script.
925
+ if (bare && failing && failingPairEcho && recoverySuccess > -1 && bare.index < recoverySuccess) {
926
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
927
+ }
928
+ // The failing step's own dying words sit between its echo and its result;
929
+ // earlier chatter belongs to a step that recovered (or another step). This is
930
+ // the in-pair window: a code-0 success between the echo and the result does
931
+ // not restore the earlier line.
932
+ let promotedInPair = false;
933
+ if (failing && failingPairEcho) {
934
+ const inside = pickPromotedLine(codelessEntries
935
+ .filter((entry) => entry.index > failingPairEcho.index && entry.index < failing.index)
936
+ .filter((entry) => lineRank(entry.line) <= 2)
937
+ .filter((entry) => !lineExcluded(entry.index)));
938
+ if (inside) {
939
+ bare = { line: inside.line, rank: lineRank(inside.line), index: inside.index };
940
+ promotedInPair = true;
941
+ }
942
+ else if (!bare || !insideFailingPair(bare.index)) {
943
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
944
+ }
945
+ }
946
+ // Lines belonging to a step whose own result says it recovered are not this
947
+ // failure's words: the failing pair's echo is the honest fallback, and with no
948
+ // attributable pair echo the floor is the exit status. The in-pair promotion
949
+ // already filtered its own candidates.
950
+ if (bare && lineExcluded(bare.index)) {
951
+ bare = failingPairEcho ? { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index } : undefined;
952
+ }
953
+ // The outer shell names a signal death "Terminated" or "Killed"; when npm
954
+ // emitted the failing echo pair, the named script is the better reason.
955
+ if (bare?.rank === 2 && /^(?:Terminated|Killed)\b/i.test(bare.line) && hasFailingPair) {
956
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
957
+ }
958
+ // A spawn kill (timeout, buffer ceiling) or a plain nonzero status with no
959
+ // failing pair and no error block leaves no line attributable to the failing
960
+ // script: the spawn artifact or the exit status is the honest reason.
961
+ const unattributableStatus = (typeof execResult.status === 'number' && execResult.status !== 0) ||
962
+ (execResult.status === null && Boolean(execResult.signal || execResult.error));
963
+ if (!block &&
964
+ !codeLine &&
965
+ !hasFailingPair &&
966
+ bare &&
967
+ !/^(?:Terminated|Killed)\b/i.test(bare.line) &&
968
+ unattributableStatus) {
969
+ bare = undefined;
970
+ }
971
+ // A sole surviving diagnostic line is the child's dying words and is kept
972
+ // after the floor, even when noise filtering discarded its companions (a
973
+ // pointer, a stack frame, spinner residue). Only a failure-marked line
974
+ // qualifies: plain progress chatter does not distinguish itself, and a
975
+ // filtered success assertion (a code-0 result, gyp's info channel) means the
976
+ // survivor belongs to a script that did not fail.
977
+ const survivorEligible = (entry) => !inBlockRange(entry.index) &&
978
+ !lineExcluded(entry.index) &&
979
+ !(hasFailingPair &&
980
+ failing &&
981
+ failingPairEcho &&
982
+ entry.index < failingPairEcho.index &&
983
+ rawLines.some((line, index) => index > entry.index && index < failing.index && isSuccessAssertion(line))) &&
984
+ (entry.index > lastBlockBodyEnd || (blocks.length <= 1 && entry.index < firstBlockCode));
985
+ const strongSurvivors = codelessEntries.filter((entry) => lineRank(entry.line) <= 1 && survivorEligible(entry));
986
+ // A demoted `[cause]:` line still rides when it is the only substantive text:
987
+ // the rank-4 demotion exists to keep it from outranking a header, not to
988
+ // silence a dump that has nothing else.
989
+ const attributableSurvivors = strongSurvivors.length
990
+ ? strongSurvivors
991
+ : codelessEntries.filter((entry) => isCauseLine(entry.line) && survivorEligible(entry));
992
+ if (!block &&
993
+ !codeLine &&
994
+ typeof execResult.status === 'number' &&
995
+ execResult.status !== 0 &&
996
+ attributableSurvivors.length === 1) {
997
+ const survivor = attributableSurvivors[0];
998
+ // The entry's own raw position: a crash snippet that repeats the text must
999
+ // not move the survivor past the success assertion that vetoes it.
1000
+ const survivorIndex = survivor.index;
1001
+ const echoIndex = failingPairEcho ? failingPairEcho.index : -1;
1002
+ const successAfter = rawLines.some((line, index) => index >= survivorIndex && isSuccessAssertion(line));
1003
+ const laterFailingPair = hasFailingPair &&
1004
+ echoIndex > survivorIndex &&
1005
+ rawLines.some((line, index) => index > survivorIndex && index < echoIndex && isSuccessAssertion(line));
1006
+ if (!laterFailingPair && (!successAfter || hasFailingPair))
1007
+ return survivor.line;
1008
+ }
1009
+ // A recovered block's echo must name the failing step: the block line moved
1010
+ // to a later echo only when the success that recovered it precedes the last
1011
+ // failing pair, and the code line is re-derived from the failing step's own
1012
+ // block (never re-resolved by duplicate text).
1013
+ if (block && block.rank <= 2 && recoverySuccess > block.index) {
1014
+ const echo = entries
1015
+ .filter((entry) => lineRank(entry.line) === 3 && entry.index > block.index && entry.index > recoverySuccess)
1016
+ .at(-1);
1017
+ if (echo) {
1018
+ block = { line: echo.line, rank: 3, index: echo.index };
1019
+ codeLine = codeEntries.filter((entry) => entry.index > recoverySuccess).at(-1)?.line;
1020
+ recoveredSwap = true;
1021
+ }
1022
+ }
1023
+ // A success assertion after a rank-0/1 code-less line means that line came
1024
+ // from a step that recovered and a later block names a different step; the
1025
+ // block's code line and echo are the honest reason instead.
1026
+ if (!hasFailingPair && bare && block && bare.rank <= 1) {
1027
+ const laterCode = codeEntries.find((entry) => entry.index > bare.index);
1028
+ const boundary = laterCode?.index ?? block.index;
1029
+ const recovered = rawLines.some((line, index) => index > bare.index && index < boundary && isSuccessAssertion(line));
1030
+ if (recovered)
1031
+ return [codeLine, block.line].filter((line) => Boolean(line)).join(' ');
1032
+ }
1033
+ // A failing pair after an earlier dying-words line, with a success assertion
1034
+ // between them, names a later failing step; prefer it. Without that gap the
1035
+ // pair belongs to the same script as the cause, and the cause stays.
1036
+ const bareRawIndex = bare ? bare.index : -1;
1037
+ if (hasFailingPair &&
1038
+ failingPairEcho &&
1039
+ bare &&
1040
+ bareRawIndex >= 0 &&
1041
+ bareRawIndex < failingPairEcho.index &&
1042
+ bare.rank <= 1 &&
1043
+ rawLines.some((line, index) => index > bareRawIndex && index < failingPairEcho.index && isSuccessAssertion(line))) {
1044
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
1045
+ }
1046
+ // An echo that precedes the chosen block belongs to an earlier step; a
1047
+ // metadata-only block must not inherit it.
1048
+ if (bare && lineRank(bare.line) === 3 && block && bare.index < block.index)
1049
+ bare = undefined;
1050
+ // A success assertion is never the reason: it names a step that recovered.
1051
+ if (bare && isSuccessAssertion(bare.line))
1052
+ bare = undefined;
1053
+ // The same holds when the echo itself won the tier: npm's block echo follows
1054
+ // its code line, so an echo above the last code line is an earlier step's.
1055
+ if (!bodylessTwin &&
1056
+ !trailingSwap &&
1057
+ block &&
1058
+ lineRank(block.line) === 3 &&
1059
+ codeEntries.length &&
1060
+ block.index < codeEntries.at(-1).index) {
1061
+ block = undefined;
1062
+ }
1063
+ // Both branches compete: an unprefixed crash line outranks a block echo, and
1064
+ // the block keeps its code prefix when the block wins or when only a weak
1065
+ // code-less line survives, because the code still identifies the failure.
1066
+ if (bare && (!block || bare.rank < block.rank)) {
1067
+ if (trailingSwap && promotedInPair)
1068
+ return bare.line;
1069
+ if (recoveredSwap && block && bare.rank >= 2) {
1070
+ return [codeLine, block.line].filter((line) => Boolean(line)).join(' ');
1071
+ }
1072
+ return codeLine && bare.rank >= 2 ? `${codeLine} ${bare.line}` : bare.line;
1073
+ }
1074
+ if (block && block.rank < 4)
1075
+ return [codeLine, block.line].filter((line) => Boolean(line)).join(' ');
1076
+ if (codeLine)
1077
+ return codeLine;
1078
+ if (bare)
1079
+ return bare.line;
1080
+ // A spawn artifact (timeout, ENOBUFS) names the kill for unattributable
1081
+ // stderr; a block or a failing pair has already won above.
1082
+ if (execResult.error?.message)
1083
+ return execResult.error.message;
1084
+ if (execResult.signal)
1085
+ return `signal ${execResult.signal}`;
1086
+ if (typeof execResult.status === 'number')
1087
+ return `exit ${execResult.status}`;
1088
+ return 'unknown failure';
1089
+ }
22
1090
  function restartMessage(target) {
23
1091
  if (target === 'officeace') {
24
1092
  return '升级完成,请打开连接器 → 我的连接器 → huaweicloud-devkit → 重新连接后使用新版本。';
@@ -48,7 +1116,7 @@ export async function upgradePackage({ target = 'all', version = 'latest' } = {}
48
1116
  return {
49
1117
  success: false,
50
1118
  error: errorMessage(error) || '无法确认最新版本(registry 查询失败)。',
51
- manual: `npx --yes huaweicloud-devkit@latest update --target ${target}`,
1119
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@latest update --target ${target}`,
52
1120
  };
53
1121
  }
54
1122
  const targetVersion = determineTarget(previousVersion, distTags ?? {});
@@ -56,7 +1124,7 @@ export async function upgradePackage({ target = 'all', version = 'latest' } = {}
56
1124
  return {
57
1125
  success: false,
58
1126
  error: '无法确认最新版本(registry 查询失败)。',
59
- manual: `npx --yes huaweicloud-devkit@latest update --target ${target}`,
1127
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@latest update --target ${target}`,
60
1128
  };
61
1129
  }
62
1130
  if (!targetVersion) {
@@ -64,16 +1132,23 @@ export async function upgradePackage({ target = 'all', version = 'latest' } = {}
64
1132
  }
65
1133
  const isNextTarget = Boolean(distTags.next && semverCompare(targetVersion, distTags.next) === 0);
66
1134
  const tag = isNextTarget ? 'next' : 'latest';
67
- const command = ['--yes', `huaweicloud-devkit@${tag}`, 'update', '--target', String(target)];
1135
+ const command = ['--yes', '--foreground-scripts', `huaweicloud-devkit@${tag}`, 'update', '--target', String(target)];
68
1136
  let execResult;
69
1137
  try {
70
- execResult = spawnFn(NPX_BIN, command, { encoding: 'utf8', timeout: 300000, windowsHide: true, shell: true });
1138
+ execResult = spawnFn(NPX_BIN, command, {
1139
+ encoding: 'utf8',
1140
+ timeout: 300000,
1141
+ windowsHide: true,
1142
+ shell: true,
1143
+ env: upgradeEnv(),
1144
+ maxBuffer: 16 * 1024 * 1024,
1145
+ });
71
1146
  }
72
1147
  catch (error) {
73
1148
  return {
74
1149
  success: false,
75
1150
  error: errorMessage(error) || '升级命令执行失败。',
76
- manual: `npx --yes huaweicloud-devkit@${tag} update --target ${target}`,
1151
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@${tag} update --target ${target}`,
77
1152
  };
78
1153
  }
79
1154
  if (execResult.status === 0) {
@@ -86,16 +1161,10 @@ export async function upgradePackage({ target = 'all', version = 'latest' } = {}
86
1161
  message: restartMessage(target),
87
1162
  };
88
1163
  }
89
- const errObj = execResult.error;
90
- const stderr = String(execResult.stderr || '').trim();
91
- const reason = errObj?.message
92
- ? errObj.message
93
- : stderr
94
- ? stderr.split(/\r?\n/).filter(Boolean).slice(-2).join(' ')
95
- : `exit ${execResult.status}`;
1164
+ const reason = extractNpmFailureReason(execResult);
96
1165
  return {
97
1166
  success: false,
98
1167
  error: reason,
99
- manual: `npx --yes huaweicloud-devkit@${tag} update --target ${target}`,
1168
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@${tag} update --target ${target}`,
100
1169
  };
101
1170
  }