@holmes-lab/holmes-kit 0.40.1 → 0.41.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.
- package/CHANGELOG.md +78 -0
- package/README.md +11 -3
- package/dist/.build-id +1 -1
- package/dist/holmes/cli/approve-context.js +4 -3
- package/dist/holmes/cli/approve.js +22 -12
- package/dist/holmes/cli/autonomy.d.ts +21 -0
- package/dist/holmes/cli/autonomy.js +35 -5
- package/dist/holmes/cli/doctor.js +58 -6
- package/dist/holmes/cli/index.js +371 -250
- package/dist/holmes/cli/init.js +17 -6
- package/dist/holmes/cli/ledger-witness.d.ts +61 -0
- package/dist/holmes/cli/ledger-witness.js +212 -0
- package/dist/holmes/cli/playbook-skills.d.ts +3 -56
- package/dist/holmes/cli/playbook-skills.js +26 -349
- package/dist/holmes/config/config.d.ts +4 -0
- package/dist/holmes/config/config.js +10 -3
- package/dist/holmes/governance/approval-queue.d.ts +65 -1
- package/dist/holmes/governance/approval-queue.js +279 -9
- package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
- package/dist/holmes/governance/autonomous-shell.js +157 -4
- package/dist/holmes/governance/autonomy.d.ts +209 -0
- package/dist/holmes/governance/autonomy.js +1127 -6
- package/dist/holmes/governance/install-manifest.d.ts +7 -4
- package/dist/holmes/governance/install-manifest.js +144 -14
- package/dist/holmes/governance/ledger-witness.d.ts +63 -0
- package/dist/holmes/governance/ledger-witness.js +296 -0
- package/dist/holmes/governance/provenance-chain.d.ts +8 -1
- package/dist/holmes/governance/provenance-chain.js +23 -4
- package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
- package/dist/holmes/governance/recorded-pairs.js +25 -1
- package/dist/holmes/governance/session-context.d.ts +7 -0
- package/dist/holmes/governance/session-context.js +34 -6
- package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
- package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
- package/dist/holmes/guardrail/command-traits.d.ts +102 -0
- package/dist/holmes/guardrail/command-traits.js +379 -0
- package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
- package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
- package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
- package/dist/holmes/guardrail/outward-acts.js +1102 -0
- package/dist/holmes/guardrail/refusal-codes.js +8 -1
- package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
- package/dist/holmes/guardrail/refusal-templates.js +71 -0
- package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
- package/dist/holmes/guardrail/risk-classifier.js +12 -118
- package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
- package/dist/holmes/guardrail/shell-lexer.js +567 -0
- package/dist/holmes/guardrail/write-target.js +7 -1
- package/dist/holmes/hooks/pre-tool-use.d.ts +60 -0
- package/dist/holmes/hooks/pre-tool-use.js +1423 -10
- package/dist/holmes/hooks/session-start.js +11 -1
- package/dist/holmes/hooks/stop.d.ts +7 -0
- package/dist/holmes/hooks/stop.js +39 -2
- package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
- package/dist/holmes/mcp/elicit-approval.js +5 -2
- package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
- package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
- package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
- package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
- package/dist/holmes/mcp/handlers/entity-store.js +7 -2
- package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
- package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
- package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
- package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
- package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
- package/dist/holmes/mcp/handlers/test-execution.js +4 -2
- package/dist/holmes/mcp/handlers.d.ts +5 -5
- package/dist/holmes/mcp/handlers.js +2 -1
- package/dist/holmes/mcp/tool-schemas.js +4 -4
- package/dist/holmes/project/playbook-reference.d.ts +50 -0
- package/dist/holmes/project/playbook-reference.js +259 -0
- package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
- package/dist/holmes/project/playbook-skill-states.js +396 -0
- package/dist/holmes/project/root.d.ts +9 -1
- package/dist/holmes/project/root.js +23 -2
- package/dist/holmes/project/running-package.d.ts +15 -0
- package/dist/holmes/project/running-package.js +87 -0
- package/dist/holmes/review/test-runner.d.ts +2 -0
- package/dist/holmes/review/test-runner.js +27 -10
- package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
- package/dist/holmes/spec/entity-integration-transaction.js +68 -7
- package/package.json +5 -2
|
@@ -0,0 +1,1102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.MAX_LISTED = void 0;
|
|
37
|
+
exports.renderFinding = renderFinding;
|
|
38
|
+
exports.judgeOutward = judgeOutward;
|
|
39
|
+
exports.outwardActsOf = outwardActsOf;
|
|
40
|
+
// @implements A-SPEC-794.92, A-SPEC-794.87, A-SPEC-794.82, A-SPEC-794.80, A-SPEC-794.78, A-SPEC-794.77, A-SPEC-794.76, A-SPEC-794.75, A-SPEC-794.74, A-SPEC-794.71, A-SPEC-794.70, A-SPEC-794.69
|
|
41
|
+
/**
|
|
42
|
+
* The outward judgement: which outward acts (push, publish) a shell command performs, for a full profile's push and
|
|
43
|
+
* publish flags (REQ-792). It carries forward A-SPEC-794.49–794.54, 794.65, 794.66, 794.68 and 794.69.
|
|
44
|
+
*
|
|
45
|
+
* A-SPEC-794.70: a registry write is read where a program takes its subcommand (argv positions), over one shell lexer
|
|
46
|
+
* (shell-lexer.ts) and one traits table (command-traits.ts). A-SPEC-794.71: only the programs the table lists as taking
|
|
47
|
+
* data exempt their arguments; any other program (an unknown wrapper included) is read again from the first registry
|
|
48
|
+
* token among its arguments, and an argument that is a command string starting with one is judged as a command.
|
|
49
|
+
* Commands carried in arguments (eval, a shell's -c, xargs, find -exec, rg --pre, git -c, an editor variable, a command
|
|
50
|
+
* option), substitutions, a shell's stdin program and package scripts are judged as commands. Package scripts are read
|
|
51
|
+
* where npm reads them, for a publish and for a push; a directory the gate cannot resolve is searched across the
|
|
52
|
+
* repository's packages. An interpreter's program (node -e, python -) is another language: it is searched for a
|
|
53
|
+
* registry tool followed by a registry write (a named limit, not an argv reading).
|
|
54
|
+
*
|
|
55
|
+
* Scope (owner decision 2026-11-03): accident prevention, not a barrier against a determined agent. The barrier to a
|
|
56
|
+
* registry write is the npm account's two-factor authentication and its token scopes. Pure apart from the two ports.
|
|
57
|
+
*/
|
|
58
|
+
const path = __importStar(require("node:path"));
|
|
59
|
+
const shell_lexer_1 = require("./shell-lexer");
|
|
60
|
+
const risk_classifier_1 = require("./risk-classifier");
|
|
61
|
+
const unresolved_write_1 = require("./unresolved-write");
|
|
62
|
+
const command_traits_1 = require("./command-traits");
|
|
63
|
+
const MAX_DEPTH = 8;
|
|
64
|
+
/** A-SPEC-794.80 — the judgement's budget. The longest of 14,531 real session commands had 153 words and 38 clauses. */
|
|
65
|
+
const BUDGET_WORDS = 400_000;
|
|
66
|
+
const BUDGET_DIRS = 2_000;
|
|
67
|
+
const BUDGET_MS = 900;
|
|
68
|
+
/** A-SPEC-794.82 — one clause's words: a longer clause is not judged (the longest real command had 1,553 words). */
|
|
69
|
+
const BUDGET_CLAUSE_WORDS = 20_000;
|
|
70
|
+
/** A-SPEC-794.82 — the clock is read every this many steps (clauses, findings, folders). */
|
|
71
|
+
const CLOCK_EVERY = 64;
|
|
72
|
+
/** A-SPEC-794.87 — how many findings a verdict's reasons and a refusal list. */
|
|
73
|
+
exports.MAX_LISTED = 200;
|
|
74
|
+
/** At most this many candidate subcommands after options the table does not know; past it the command is too large. */
|
|
75
|
+
const MAX_CANDIDATES = 8;
|
|
76
|
+
const TOO_MANY = '\u0000too-many-options';
|
|
77
|
+
/**
|
|
78
|
+
* A-SPEC-794.80, A-SPEC-794.82 — a command past the budget stops being judged, with what it exceeded. It is not a
|
|
79
|
+
* publish: the verdict carries `unjudged`, which no profile flag lets through (794.80 recorded a publish finding, so a
|
|
80
|
+
* profile with the publish flag let a push through).
|
|
81
|
+
*/
|
|
82
|
+
function overBudget(run, what) {
|
|
83
|
+
if (run.memo.budget.closed)
|
|
84
|
+
return;
|
|
85
|
+
run.memo.budget.closed = true;
|
|
86
|
+
run.memo.budget.why = `the command is too large to judge (${what}); split it into smaller commands and run them one at a time`;
|
|
87
|
+
}
|
|
88
|
+
/** A-SPEC-794.82 — one step of work: past the time budget the judgement closes. True when it is closed. */
|
|
89
|
+
function spent(run) {
|
|
90
|
+
const b = run.memo.budget;
|
|
91
|
+
if (b.closed)
|
|
92
|
+
return true;
|
|
93
|
+
if (++b.steps % CLOCK_EVERY === 0 && Date.now() - b.t0 > BUDGET_MS)
|
|
94
|
+
overBudget(run, `more than ${BUDGET_MS} ms`);
|
|
95
|
+
return b.closed;
|
|
96
|
+
}
|
|
97
|
+
const REGISTRY_TOOLS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
|
|
98
|
+
const SKIP_WORDS = new Set(['{', '}', 'then', 'do', 'else', 'elif', 'fi', 'done', 'esac', '!']);
|
|
99
|
+
const OPENERS = new Set(['if', 'while', 'until', 'for', 'case', 'select']);
|
|
100
|
+
const CLOSERS = new Set(['fi', 'done', 'esac']);
|
|
101
|
+
const NPM_FLAGS = new Set(['--silent', '-s', '--quiet', '-q', '--verbose', '-d', '--json', '--yes', '-y', '--global', '-g',
|
|
102
|
+
'--no-color', '--color', '--offline', '--prefer-offline', '--prefer-online', '--ignore-scripts', '--force', '-f', '-ws',
|
|
103
|
+
'--workspaces', '-r', '--recursive', '--if-present', '--include-workspace-root', '-iwr', '--dry-run', '--no-dry-run', '--help', '-h']);
|
|
104
|
+
const UNRESOLVED_FLAGS = new Set(['-ws', '--workspaces', '-r', '--recursive']);
|
|
105
|
+
const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path']);
|
|
106
|
+
const PUSH_INERT = new Set(['--help', '-h', '--dry-run', '-n']);
|
|
107
|
+
/** An interpreter's program naming a registry tool and, within three tokens, a registry write (a named limit). */
|
|
108
|
+
const INTERPRETER_WRITE = /\b(?:npm|pnpm|yarn|bun)\b(?:[\s'",[\]()]+[\w@./:=-]+){0,3}?[\s'",[\]()]+(publish|unpublish|deprecate|dist-tag|owner|access|token|team|org|profile|stage|trust|star)\b(?!-)/;
|
|
109
|
+
const HOOK_PATH = /(?:^|\/)\.git\/hooks\/|(?:^|\/)\.husky\//;
|
|
110
|
+
/** A command the lexer cannot read is closed when it names one of these. */
|
|
111
|
+
const NAMES_REGISTRY = /(?:^|[^\w-])(?:npm|pnpm|yarn|bun|npx|pnpx|bunx|semantic-release|np|release-it|lerna|nx|changesets?)(?![\w-])/;
|
|
112
|
+
const NAMES_PUSH = /(?:^|[^\w-])git(?![\w-])[\s\S]*?(?:^|[^\w-])push(?![\w-])/;
|
|
113
|
+
/** Programs that pass their stdin on (followed to the source of a shell's stdin program). */
|
|
114
|
+
const PASS_THROUGH = new Set(['tee', 'cat']);
|
|
115
|
+
const ECHOES = new Set(['echo', 'printf', 'cat']);
|
|
116
|
+
const WRITE_VERB = /\b(?:publish|unpublish|deprecate)\b/;
|
|
117
|
+
const ASSIGNMENT = /^([A-Za-z_]\w*)(\+?)=([\s\S]*)$/;
|
|
118
|
+
const DECLARERS = new Set(['export', 'declare', 'local', 'readonly', 'typeset']);
|
|
119
|
+
/**
|
|
120
|
+
* A clause's text around a word: the whole clause up to 80 characters, else 30 characters each side; backticks escaped.
|
|
121
|
+
* A-SPEC-794.82 — only a window around the word is folded (folding the whole clause per finding was quadratic).
|
|
122
|
+
*/
|
|
123
|
+
function around(clause, word) {
|
|
124
|
+
if (clause.length <= 16_384) {
|
|
125
|
+
const one = clause.replace(/\s+/g, ' ').trim();
|
|
126
|
+
let shown = one;
|
|
127
|
+
if (one.length > 80) {
|
|
128
|
+
const at = Math.max(0, one.indexOf(word));
|
|
129
|
+
const from = Math.max(0, at - 30);
|
|
130
|
+
const to = Math.min(one.length, at + word.length + 30);
|
|
131
|
+
shown = `${from > 0 ? '…' : ''}${one.slice(from, to)}${to < one.length ? '…' : ''}`;
|
|
132
|
+
}
|
|
133
|
+
return shown.replace(/`/g, '\\`');
|
|
134
|
+
}
|
|
135
|
+
const at = Math.max(0, word === '' ? 0 : clause.indexOf(word));
|
|
136
|
+
const raw = clause.slice(Math.max(0, at - 120), Math.min(clause.length, at + word.length + 120));
|
|
137
|
+
const lead = clause.slice(Math.max(0, at - 120), at).replace(/\s+/g, ' ');
|
|
138
|
+
const one = raw.replace(/\s+/g, ' ');
|
|
139
|
+
const pos = lead.length;
|
|
140
|
+
const from = Math.max(0, pos - 30);
|
|
141
|
+
const to = Math.min(one.length, pos + word.length + 30);
|
|
142
|
+
const head = at - 120 > 0 || from > 0;
|
|
143
|
+
const tail = at + word.length + 120 < clause.length || to < one.length;
|
|
144
|
+
return `${head ? '…' : ''}${one.slice(from, to).trim()}${tail ? '…' : ''}`.replace(/`/g, '\\`');
|
|
145
|
+
}
|
|
146
|
+
const REWRITE_DIR = 'name the directory literally (cd <path> or --prefix <path>)';
|
|
147
|
+
const REWRITE_PUSH = 'check it with git push --dry-run, or ask the owner to push';
|
|
148
|
+
const rewriteFor = (honoursDry) => (honoursDry
|
|
149
|
+
? 'run it with --dry-run to check, or ask the owner'
|
|
150
|
+
: 'this subcommand does not follow --dry-run: check with its reading form (ls, list, get), or ask the owner');
|
|
151
|
+
/** The value of a valued option (`--prefix x`, `--prefix=x`), or undefined; every value with `all`. */
|
|
152
|
+
function optionValues(words, names) {
|
|
153
|
+
const out = [];
|
|
154
|
+
for (let k = 0; k < words.length; k++) {
|
|
155
|
+
for (const n of names) {
|
|
156
|
+
if (words[k].value === n && words[k + 1] !== undefined)
|
|
157
|
+
out.push(words[k + 1]);
|
|
158
|
+
else if (words[k].value.startsWith(`${n}=`))
|
|
159
|
+
out.push({ ...words[k], value: words[k].value.slice(n.length + 1) });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
/** The subcommand candidates of a package manager's arguments: the first positional word, and, after an option the
|
|
165
|
+
* table does not know (it may take a value), the word after it too. Each with the words that follow it. */
|
|
166
|
+
function subcommands(args) {
|
|
167
|
+
const out = [];
|
|
168
|
+
for (let k = 0; k < args.length; k++) {
|
|
169
|
+
const w = args[k];
|
|
170
|
+
if (w === '--') {
|
|
171
|
+
if (args[k + 1] !== undefined)
|
|
172
|
+
out.push({ sub: args[k + 1], rest: args.slice(k + 2) });
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
if (command_traits_1.NPM_VALUED_OPTIONS.has(w)) {
|
|
176
|
+
k++;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (w.startsWith('-')) {
|
|
180
|
+
if (w.includes('=') || NPM_FLAGS.has(w))
|
|
181
|
+
continue;
|
|
182
|
+
// an option the table does not know may take the next word as its value — but never a word that is itself an
|
|
183
|
+
// option (A-SPEC-794.76: `yarn --frozen-lockfile --cwd x` made `x` the subcommand)
|
|
184
|
+
if (args[k + 1] === undefined || args[k + 1].startsWith('-'))
|
|
185
|
+
continue;
|
|
186
|
+
// A-SPEC-794.80 — at most MAX_CANDIDATES ambiguous candidates (each slice is linear; unbounded they were
|
|
187
|
+
// quadratic and ran out of memory); past it the caller closes the command as too large to judge
|
|
188
|
+
if (out.length >= MAX_CANDIDATES) {
|
|
189
|
+
out.push({ sub: TOO_MANY, rest: [] });
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
out.push({ sub: args[k + 1], rest: args.slice(k + 2) });
|
|
193
|
+
k++;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
out.push({ sub: w, rest: args.slice(k + 1) });
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
const firstPositional = (args) => args.find((a) => !a.startsWith('-'));
|
|
202
|
+
/** A shell word quoted back so a list of values can be judged again as a command. */
|
|
203
|
+
const quote = (v) => (/^[\w@%+=:,./-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`);
|
|
204
|
+
/** A program word as a name: its basename, a scoped package kept whole, the version dropped. */
|
|
205
|
+
const programToken = (v) => (/^@[^/\s]+\/[^/\s]+$/.test(v) ? v : path.basename(v)).replace(/(?!^)@[^@/]*$/, '');
|
|
206
|
+
/** A directory word resolved: literal, or a `$NAME` (with a literal suffix) whose literal value is known. */
|
|
207
|
+
function resolveDir(word, base, vars) {
|
|
208
|
+
if (word === undefined || !base.known || base.dir === undefined)
|
|
209
|
+
return { dir: undefined, known: false };
|
|
210
|
+
if (word.literal && word.value !== '')
|
|
211
|
+
return { dir: path.resolve(base.dir, word.value), known: true };
|
|
212
|
+
const m = /^\$\{?([A-Za-z_]\w*)\}?((?:\/[^$`*?~\u0000]*)?)$/.exec(word.raw.replace(/"/g, ''));
|
|
213
|
+
if (m !== null && vars.has(m[1]))
|
|
214
|
+
return { dir: path.resolve(base.dir, `${vars.get(m[1])}${m[2]}`), known: true };
|
|
215
|
+
return { dir: undefined, known: false };
|
|
216
|
+
}
|
|
217
|
+
function judge(command, run, start, depth) {
|
|
218
|
+
const closeUnread = (why) => {
|
|
219
|
+
if (NAMES_REGISTRY.test(command))
|
|
220
|
+
run.findings.push({ act: 'publish', clause: around(command, 'npm'), word: '', why: `the gate could not read the command's structure (${why}) and it names a registry program`, rewrite: 'write the command without the unclosed quote or the deep nesting' });
|
|
221
|
+
if (NAMES_PUSH.test(command))
|
|
222
|
+
run.findings.push({ act: 'push', clause: around(command, 'push'), word: 'push', why: `the gate could not read the command's structure (${why}) and it names a git push`, rewrite: REWRITE_PUSH });
|
|
223
|
+
};
|
|
224
|
+
if (depth > MAX_DEPTH) {
|
|
225
|
+
closeUnread('it nests too deeply');
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (run.memo.budget.closed)
|
|
229
|
+
return;
|
|
230
|
+
const { clauses, ok, tooDeep } = (0, shell_lexer_1.lexShell)(command);
|
|
231
|
+
// A-SPEC-794.87 — groups nested past the lexer's bound: unjudged, naming the depth (45,000 ran the hook to its deadline)
|
|
232
|
+
if (tooDeep === true) {
|
|
233
|
+
overBudget(run, 'subshell groups nested more than 64 deep');
|
|
234
|
+
return;
|
|
235
|
+
} // A-SPEC-794.92: the bound is 64
|
|
236
|
+
if (!ok) {
|
|
237
|
+
closeUnread('an unclosed quote, substitution or group, or nesting past the bound');
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
// A-SPEC-794.80 — the judgement's budget: words judged (nested judgements included)
|
|
241
|
+
let words = 0;
|
|
242
|
+
for (const c of clauses)
|
|
243
|
+
words += c.words.length;
|
|
244
|
+
run.memo.budget.words += words;
|
|
245
|
+
if (run.memo.budget.words > BUDGET_WORDS) {
|
|
246
|
+
overBudget(run, `more than ${BUDGET_WORDS.toLocaleString('en-US')} words`);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
let place = { ...start };
|
|
250
|
+
const saved = new Map();
|
|
251
|
+
const stack = [];
|
|
252
|
+
const vars = new Map();
|
|
253
|
+
const shape = { open: 0, prevSep: '' };
|
|
254
|
+
let groups = [];
|
|
255
|
+
clauses.forEach((clause, index) => {
|
|
256
|
+
if (spent(run))
|
|
257
|
+
return;
|
|
258
|
+
// A-SPEC-794.82 — one clause's words: the whole budget alone let one pathological clause recurse out of memory
|
|
259
|
+
if (clause.words.length > BUDGET_CLAUSE_WORDS) {
|
|
260
|
+
overBudget(run, `a clause of more than ${BUDGET_CLAUSE_WORDS.toLocaleString('en-US')} words`);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
// A-SPEC-794.87 — group stacks are prefixes of one another: equal ones (same length, same innermost id) cost O(1),
|
|
264
|
+
// others are compared over their common prefix (the per-clause `includes` scans were depth squared)
|
|
265
|
+
const same = groups.length === clause.groups.length && groups[groups.length - 1] === clause.groups[clause.groups.length - 1];
|
|
266
|
+
if (!same) {
|
|
267
|
+
let k = 0;
|
|
268
|
+
while (k < groups.length && k < clause.groups.length && groups[k] === clause.groups[k])
|
|
269
|
+
k++;
|
|
270
|
+
if (k < groups.length)
|
|
271
|
+
place = saved.get(groups[k]) ?? place;
|
|
272
|
+
for (let j = k; j < clause.groups.length; j++)
|
|
273
|
+
saved.set(clause.groups[j], { ...place });
|
|
274
|
+
}
|
|
275
|
+
groups = clause.groups;
|
|
276
|
+
place = judgeClause(clause, clauses, index, run, place, stack, vars, shape, depth);
|
|
277
|
+
shape.prevSep = clause.sep;
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/** A-SPEC-794.71 — what a clause does to the variables it names: only a literal simple assignment, unconditional, at
|
|
281
|
+
* the top level, gives a value; any other touch makes the name unknown. */
|
|
282
|
+
function noteVariables(clause, words, vars, shape) {
|
|
283
|
+
// A-SPEC-794.72 — an assignment in a pipe element or in the background runs in a subshell: it changes nothing here
|
|
284
|
+
if (clause.pipedFrom !== null || clause.sep === '|' || clause.sep === '|&' || clause.sep === '&')
|
|
285
|
+
return;
|
|
286
|
+
const conditional = shape.open > 0 || clause.groups.length > 0 || shape.prevSep === '&&' || shape.prevSep === '||'
|
|
287
|
+
|| clause.words.some((w, k) => k < clause.words.length - words.length && SKIP_WORDS.has(w.value));
|
|
288
|
+
const assign = (w, unknown = false) => {
|
|
289
|
+
const m = ASSIGNMENT.exec(w.value);
|
|
290
|
+
if (m === null)
|
|
291
|
+
return;
|
|
292
|
+
if (unknown || conditional || m[2] === '+' || !w.literal || w.value.endsWith('=') && w.raw.endsWith('='))
|
|
293
|
+
vars.delete(m[1]);
|
|
294
|
+
else
|
|
295
|
+
vars.set(m[1], m[3]);
|
|
296
|
+
};
|
|
297
|
+
if (words.length > 0 && words.every((w) => ASSIGNMENT.test(w.value))) {
|
|
298
|
+
for (const w of words)
|
|
299
|
+
assign(w);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
// the command after prefix assignments (`IFS=, read W`)
|
|
303
|
+
// A-SPEC-794.74 — found in one pass (the earlier filter rescanned the prefix for every word: quadratic)
|
|
304
|
+
const firstCommand = words.findIndex((w) => !ASSIGNMENT.test(w.value));
|
|
305
|
+
const body = firstCommand < 0 ? [] : words.slice(firstCommand);
|
|
306
|
+
const first = body[0]?.value;
|
|
307
|
+
if (first !== undefined && DECLARERS.has(first)) {
|
|
308
|
+
const opaque = body.slice(1).some((w) => /^-[a-zA-Z]*[aAn]/.test(w.value)); // arrays and name references
|
|
309
|
+
for (const w of body.slice(1))
|
|
310
|
+
if (!w.value.startsWith('-'))
|
|
311
|
+
assign(w, opaque);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (first === 'printf') {
|
|
315
|
+
const k = body.findIndex((w) => w.value === '-v');
|
|
316
|
+
if (k >= 0 && body[k + 1] !== undefined)
|
|
317
|
+
vars.delete(body[k + 1].value);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (first === 'eval') {
|
|
321
|
+
for (const w of body.slice(1))
|
|
322
|
+
for (const m of w.value.matchAll(/(?:^|[\s;])([A-Za-z_]\w*)\+?=/g))
|
|
323
|
+
vars.delete(m[1]);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
words = body;
|
|
327
|
+
if (first === 'for' || first === 'select') {
|
|
328
|
+
if (words[1] !== undefined)
|
|
329
|
+
vars.delete(words[1].value);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (first === 'read' || first === 'unset' || first === 'mapfile' || first === 'readarray') {
|
|
333
|
+
for (let k = 1; k < words.length; k++) {
|
|
334
|
+
const v = words[k].value;
|
|
335
|
+
if (/^-[pdntua]$/.test(v) && first === 'read') {
|
|
336
|
+
if (v === '-a')
|
|
337
|
+
vars.delete(words[k + 1]?.value ?? '');
|
|
338
|
+
k++;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (!v.startsWith('-'))
|
|
342
|
+
vars.delete(v);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function judgeClause(clause, all, index, run, place, stack, vars, shape, depth) {
|
|
347
|
+
const asCommand = (text, at = place) => judge(text, run, at, depth + 1);
|
|
348
|
+
for (const sub of clause.substitutions)
|
|
349
|
+
asCommand(sub.body);
|
|
350
|
+
// A-SPEC-794.92 — a here-document substitution the lexer could not read makes the command unjudged: it ended the scan,
|
|
351
|
+
// and every later substitution went unread (a deep group then hid a push)
|
|
352
|
+
for (const h of clause.heredocs) {
|
|
353
|
+
if (h.quoted || h.hereString)
|
|
354
|
+
continue;
|
|
355
|
+
const read = (0, shell_lexer_1.heredocExpansionsRead)(h.body);
|
|
356
|
+
for (const body of read.bodies)
|
|
357
|
+
asCommand(body);
|
|
358
|
+
if (!read.ok) {
|
|
359
|
+
overBudget(run, read.tooDeep ? 'subshell groups nested more than 64 deep' : 'a here-document holds a substitution the gate cannot read');
|
|
360
|
+
return place;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
// shell words open and close conditions and loops; leading assignments are skipped (an editor variable is a command)
|
|
364
|
+
let words = clause.words;
|
|
365
|
+
const firstWord = words[0]?.value;
|
|
366
|
+
if (firstWord !== undefined && CLOSERS.has(firstWord))
|
|
367
|
+
shape.open = Math.max(0, shape.open - 1);
|
|
368
|
+
if (firstWord !== undefined && OPENERS.has(firstWord))
|
|
369
|
+
shape.open++;
|
|
370
|
+
// A-SPEC-794.75 — the prefix walks advance an index and slice once (slicing per word was quadratic)
|
|
371
|
+
let skip = 0;
|
|
372
|
+
while (skip < words.length && (unresolved_write_1.KEYWORD.test(words[skip].value) || SKIP_WORDS.has(words[skip].value)))
|
|
373
|
+
skip++;
|
|
374
|
+
words = words.slice(skip);
|
|
375
|
+
noteVariables(clause, words, vars, shape);
|
|
376
|
+
skip = 0;
|
|
377
|
+
while (skip < words.length && ASSIGNMENT.test(words[skip].value)) {
|
|
378
|
+
const m = ASSIGNMENT.exec(words[skip].value);
|
|
379
|
+
if (m !== null && command_traits_1.COMMAND_VARIABLES.has(m[1]))
|
|
380
|
+
asCommand(m[3]);
|
|
381
|
+
skip++;
|
|
382
|
+
}
|
|
383
|
+
words = words.slice(skip);
|
|
384
|
+
const values = words.map((w) => w.value);
|
|
385
|
+
// a command option of the first word, before any unwrapping (npx -c "…")
|
|
386
|
+
const opts0 = command_traits_1.COMMAND_OPTIONS[programToken(values[0] ?? '')];
|
|
387
|
+
if (opts0 !== undefined)
|
|
388
|
+
for (const v of optionValues(words.slice(1), opts0))
|
|
389
|
+
asCommand(v.value);
|
|
390
|
+
// `env -C dir` / `--chdir dir` run the command in dir (A-SPEC-794.72)
|
|
391
|
+
let at = place;
|
|
392
|
+
if (programToken(values[0] ?? '') === 'env') {
|
|
393
|
+
const k = words.findIndex((w) => w.value === '-C' || w.value === '--chdir' || w.value.startsWith('--chdir='));
|
|
394
|
+
if (k >= 0)
|
|
395
|
+
at = resolveDir(words[k].value.startsWith('--chdir=') ? { ...words[k], value: words[k].value.slice(8) } : words[k + 1], place, vars);
|
|
396
|
+
}
|
|
397
|
+
// a package manager as the first word is read even where programOf finds no program after it (`npm exec --call=…`)
|
|
398
|
+
const head0 = programToken(values[0] ?? '');
|
|
399
|
+
const prog = (0, risk_classifier_1.programOf)(values) ?? (REGISTRY_TOOLS.has(head0) ? { name: head0, args: values.slice(1), word: values[0] } : null);
|
|
400
|
+
let next = place;
|
|
401
|
+
if (prog !== null) {
|
|
402
|
+
const progWord = words.find((w) => w.value === prog.word);
|
|
403
|
+
const literalProgram = progWord?.literal !== false && !(0, shell_lexer_1.holdsSubstitution)(prog.word) && !prog.word.includes('$');
|
|
404
|
+
let name = /^@[^/\s]+\/[^/\s]+/.test(prog.word) ? programToken(prog.word) : programToken(prog.name); // a scoped package kept whole
|
|
405
|
+
let args = [...prog.args];
|
|
406
|
+
// a package manager as the first word is read by its own table (programOf unwraps `npm exec`, `pnpm dlx`, …)
|
|
407
|
+
const head = programToken(values[0] ?? '');
|
|
408
|
+
if (REGISTRY_TOOLS.has(head) && words[0]?.literal !== false) {
|
|
409
|
+
name = head;
|
|
410
|
+
args = values.slice(1);
|
|
411
|
+
}
|
|
412
|
+
// A-SPEC-794.72 — the command strings of the first word and of every wrapper level are read before unwrapping
|
|
413
|
+
// (programOf unwraps watch and parallel; doppler --command leaves no positional command)
|
|
414
|
+
const strings = new Set([...(0, command_traits_1.commandStrings)(head, values.slice(1)), ...(0, command_traits_1.commandStrings)(name, args)]);
|
|
415
|
+
// one unwrapping for push and publish: programOf, then the wrappers table
|
|
416
|
+
let unwrapFailed = false;
|
|
417
|
+
for (let hops = 0; hops < 8 && command_traits_1.WRAPPERS[name] !== undefined; hops++) {
|
|
418
|
+
for (const s of (0, command_traits_1.commandStrings)(name, args))
|
|
419
|
+
strings.add(s);
|
|
420
|
+
const inner = (0, command_traits_1.unwrapWith)(command_traits_1.WRAPPERS[name], args);
|
|
421
|
+
// A-SPEC-794.74 — a wrapper whose words do not unwrap falls to the independent-token reading
|
|
422
|
+
if (inner === null || inner.length === 0) {
|
|
423
|
+
unwrapFailed = true;
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
const p = (0, risk_classifier_1.programOf)(inner);
|
|
427
|
+
if (p === null)
|
|
428
|
+
break;
|
|
429
|
+
name = /^@[^/\s]+\/[^/\s]+/.test(p.word) ? programToken(p.word) : programToken(p.name);
|
|
430
|
+
args = [...p.args];
|
|
431
|
+
if (REGISTRY_TOOLS.has(programToken(inner[0]))) {
|
|
432
|
+
name = programToken(inner[0]);
|
|
433
|
+
args = inner.slice(1);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (name === 'yarnpkg')
|
|
437
|
+
name = 'yarn';
|
|
438
|
+
if (command_traits_1.PACKAGE_RUNNERS.has(name) && args.length > 0) {
|
|
439
|
+
name = programToken(args[0]);
|
|
440
|
+
args = args.slice(1);
|
|
441
|
+
}
|
|
442
|
+
if (command_traits_1.PACKAGE_BINS[name] !== undefined)
|
|
443
|
+
name = command_traits_1.PACKAGE_BINS[name];
|
|
444
|
+
if (command_traits_1.INTERPRETERS.test(name) && args[0] !== undefined && ((0, shell_lexer_1.holdsSubstitution)(args[0]) || /(?:^|\/)(?:npm-cli\.js|npm)$/.test(args[0]))) {
|
|
445
|
+
name = 'npm';
|
|
446
|
+
args = args.slice(1);
|
|
447
|
+
}
|
|
448
|
+
if (!literalProgram)
|
|
449
|
+
name = 'npm'; // "$NPM" publish, $(which npm) publish: read as a registry tool
|
|
450
|
+
const argWords = words.slice(words.length - args.length);
|
|
451
|
+
// directories
|
|
452
|
+
if (name === 'cd' || name === 'pushd') {
|
|
453
|
+
const target = argWords.find((w) => !w.value.startsWith('-'));
|
|
454
|
+
if (name === 'pushd')
|
|
455
|
+
stack.push({ ...place });
|
|
456
|
+
// a cd under a condition or loop leaves the directory unknown (A-SPEC-794.72)
|
|
457
|
+
next = shape.open > 0 || (name === 'pushd' && target !== undefined && /^[+-]\d+$/.test(target.value)) ? { dir: undefined, known: false } : resolveDir(target, place, vars);
|
|
458
|
+
}
|
|
459
|
+
else if (name === 'popd')
|
|
460
|
+
next = stack.pop() ?? { dir: undefined, known: false };
|
|
461
|
+
// commands carried in arguments
|
|
462
|
+
const carried = command_traits_1.COMMAND_OPTIONS[name];
|
|
463
|
+
if (carried !== undefined && name !== programToken(values[0] ?? ''))
|
|
464
|
+
for (const v of optionValues(argWords, carried))
|
|
465
|
+
asCommand(v.value);
|
|
466
|
+
for (const s of (0, command_traits_1.commandStrings)(name, args))
|
|
467
|
+
strings.add(s);
|
|
468
|
+
for (const text of strings)
|
|
469
|
+
asCommand(text, at);
|
|
470
|
+
if (name === 'eval')
|
|
471
|
+
asCommand(args.join(' '));
|
|
472
|
+
if (command_traits_1.SHELL_PROGRAMS.test(name)) {
|
|
473
|
+
const inner = shellCommandArg(args);
|
|
474
|
+
if (inner !== null)
|
|
475
|
+
asCommand(inner);
|
|
476
|
+
else if (args.some((a) => /^-[a-z]*s[a-z]*$/.test(a)) || args.every((a) => a.startsWith('-') || a.startsWith('+') || a === 'pipefail' || a === 'errexit')) {
|
|
477
|
+
for (const text of stdinProgram(clause, all))
|
|
478
|
+
asCommand(text);
|
|
479
|
+
const up = source(clause, all);
|
|
480
|
+
const upName = up?.words[0]?.value;
|
|
481
|
+
if (up !== null && upName !== undefined && !ECHOES.has(upName) && WRITE_VERB.test(up.source)) {
|
|
482
|
+
run.findings.push({ act: 'publish', clause: around(`${up.source} | ${clause.source}`, 'publish'), word: name, why: `a shell runs the output of \`${upName}\`, which the gate cannot read, and the command names a registry write`, rewrite: 'run the command itself instead of piping it into a shell' });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (command_traits_1.INTERPRETERS.test(name) && name !== 'npm') {
|
|
487
|
+
const flag = args.findIndex((a) => command_traits_1.INLINE_FLAGS.has(a));
|
|
488
|
+
const programs = flag >= 0 ? [args[flag + 1] ?? ''] : args.length === 0 || args[0] === '-' ? stdinProgram(clause, all) : [];
|
|
489
|
+
for (const text of programs) {
|
|
490
|
+
const m = INTERPRETER_WRITE.exec(text);
|
|
491
|
+
if (m !== null)
|
|
492
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, name), word: m[1], why: `the ${name} program it runs calls a registry tool's \`${m[1]}\``, rewrite: 'run the registry tool as its own command' });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (name === 'find') {
|
|
496
|
+
const k = args.findIndex((a) => /^-(?:exec|execdir|ok|okdir)$/.test(a));
|
|
497
|
+
if (k >= 0) {
|
|
498
|
+
const end = args.findIndex((a, j) => j > k && (a === ';' || a === '+'));
|
|
499
|
+
asCommand(args.slice(k + 1, end < 0 ? undefined : end).map(quote).join(' '));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (name === 'rg')
|
|
503
|
+
for (const pre of optionValues(argWords, ['--pre']))
|
|
504
|
+
asCommand(pre.value);
|
|
505
|
+
if (name === 'git') {
|
|
506
|
+
for (let k = 0; k < args.length && args[k].startsWith('-'); k++) {
|
|
507
|
+
if ((args[k] === '-c' || args[k] === '--config-env') && args[k + 1] !== undefined) {
|
|
508
|
+
asCommand(args[k + 1].replace(/^[^=]*=!?/, ''));
|
|
509
|
+
k++;
|
|
510
|
+
}
|
|
511
|
+
else if (/^-c.+=/.test(args[k]))
|
|
512
|
+
asCommand(args[k].replace(/^-c[^=]*=!?/, ''));
|
|
513
|
+
else if (GIT_VALUED.has(args[k]))
|
|
514
|
+
k++;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
// registry tools, release tools, runners
|
|
518
|
+
if (REGISTRY_TOOLS.has(name))
|
|
519
|
+
registryClause(name, args, argWords, clause, run, at, depth);
|
|
520
|
+
releaseTool(name, args, clause, run);
|
|
521
|
+
const runs = (0, command_traits_1.runnerScripts)(name, args);
|
|
522
|
+
if (runs !== null)
|
|
523
|
+
scriptsAnywhere(runs, clause, name, run, depth);
|
|
524
|
+
if (command_traits_1.SCRIPT_NAME_RUNNERS.has(name))
|
|
525
|
+
scriptsByName(args, clause, name, run, at, depth);
|
|
526
|
+
// A-SPEC-794.72 — an unknown program: only independent tokens are read. Wherever a registry program is followed
|
|
527
|
+
// by a write subcommand, or git by push, the words from there are judged; a string argument is data.
|
|
528
|
+
const handled = command_traits_1.DATA_PROGRAMS.has(name) || REGISTRY_TOOLS.has(name) || command_traits_1.RELEASE_TOOLS[name] !== undefined || command_traits_1.SHELL_PROGRAMS.test(name)
|
|
529
|
+
|| command_traits_1.INTERPRETERS.test(name) || name === 'eval' || name === 'find' || name === 'git' || runs !== null || command_traits_1.SCRIPT_NAME_RUNNERS.has(name)
|
|
530
|
+
|| command_traits_1.POSITIONAL_COMMANDS.has(name) || command_traits_1.COMMAND_STRING_PROGRAMS.has(name) || (command_traits_1.WRAPPERS[name] !== undefined && !unwrapFailed);
|
|
531
|
+
if (!handled) {
|
|
532
|
+
// one pass for the candidate positions (A-SPEC-794.74), then each candidate is judged over its own window — the
|
|
533
|
+
// words up to the next candidate — until a publish (and a push) is found: a position that passed (a dry run, a
|
|
534
|
+
// help) does not hide a later one, and every word is judged at most once (A-SPEC-794.75)
|
|
535
|
+
const candidates = [];
|
|
536
|
+
for (let k = 0; k < args.length; k++) {
|
|
537
|
+
const tok = args[k];
|
|
538
|
+
if (/\s/.test(tok))
|
|
539
|
+
continue;
|
|
540
|
+
const bare = !tok.includes('/') || /(?:^|\/)node_modules\/\.bin\/[^/]+$/.test(tok);
|
|
541
|
+
const t = programToken(tok);
|
|
542
|
+
const writes = bare && command_traits_1.REGISTRY_PROGRAMS.has(t) ? writesAfter(t === 'yarnpkg' ? 'yarn' : t, args.slice(k + 1, k + 33)) : false;
|
|
543
|
+
// A-SPEC-794.82 — more readings than the table allows is not a silent pass (794.80 ignored it; 794.78 refused it)
|
|
544
|
+
if (writes === 'unjudged') {
|
|
545
|
+
overBudget(run, `more than ${MAX_CANDIDATES} options the gate does not know before a subcommand`);
|
|
546
|
+
break;
|
|
547
|
+
}
|
|
548
|
+
if (writes)
|
|
549
|
+
candidates.push({ k, act: 'publish' });
|
|
550
|
+
else if (tok === 'git' && gitSubcommand(args.slice(k + 1, k + 33)) === 'push')
|
|
551
|
+
candidates.push({ k, act: 'push' });
|
|
552
|
+
}
|
|
553
|
+
const found = new Set();
|
|
554
|
+
for (let c = 0; c < candidates.length && found.size < 2; c++) {
|
|
555
|
+
const { k, act } = candidates[c];
|
|
556
|
+
if (found.has(act))
|
|
557
|
+
continue;
|
|
558
|
+
// capped at 64 words in every case (A-SPEC-794.77, B-L1)
|
|
559
|
+
const end = Math.min(c + 1 < candidates.length ? candidates[c + 1].k : args.length, k + 64);
|
|
560
|
+
const inner = { ctx: run.ctx, findings: [], depth: run.depth, memo: run.memo };
|
|
561
|
+
judge(args.slice(k, end).map(quote).join(' '), inner, place, depth + 1);
|
|
562
|
+
run.findings.push(...inner.findings);
|
|
563
|
+
for (const f of inner.findings)
|
|
564
|
+
found.add(f.act);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
// push: git's words after the one unwrapping (A-SPEC-794.49, 794.72)
|
|
568
|
+
if (name === 'git' && gitSubcommand(args) === 'push') {
|
|
569
|
+
const rest = args.slice(args.indexOf('push') + 1);
|
|
570
|
+
const end = rest.indexOf('--');
|
|
571
|
+
if (!rest.slice(0, end < 0 ? rest.length : end).some((w) => PUSH_INERT.has(w))) {
|
|
572
|
+
run.findings.push({ act: 'push', clause: around(clause.source, 'push'), word: 'push', why: 'git push sends commits to a remote', rewrite: REWRITE_PUSH });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
// a write into a git hook is a command
|
|
577
|
+
for (const r of clause.redirects) {
|
|
578
|
+
if (r.target === null || !HOOK_PATH.test(r.target.value))
|
|
579
|
+
continue;
|
|
580
|
+
const data = [values.slice(1).join(' '), ...clause.heredocs.map((h) => h.body)].join('\n');
|
|
581
|
+
if (actsOf(data, run, place, depth).has('publish')) {
|
|
582
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, r.target.value), word: r.target.value, why: `it writes a git hook (${r.target.value}) that publishes`, rewrite: 'do not write registry commands into a hook' });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return next;
|
|
586
|
+
}
|
|
587
|
+
/** git's subcommand after its global options. */
|
|
588
|
+
function gitSubcommand(args) {
|
|
589
|
+
let i = 0;
|
|
590
|
+
while ((args[i] ?? '').startsWith('-'))
|
|
591
|
+
i += GIT_VALUED.has(args[i]) ? 2 : 1;
|
|
592
|
+
return args[i];
|
|
593
|
+
}
|
|
594
|
+
/** Whether a registry program's following words begin a registry write (A-SPEC-794.72, unknown programs). */
|
|
595
|
+
function writesAfter(tool, rest) {
|
|
596
|
+
for (const { sub, rest: after } of subcommands(rest)) {
|
|
597
|
+
if (sub === TOO_MANY)
|
|
598
|
+
return 'unjudged'; // A-SPEC-794.82
|
|
599
|
+
if (tool === 'npm') {
|
|
600
|
+
const cmd = (0, command_traits_1.npmCommand)(sub);
|
|
601
|
+
if (cmd !== undefined) {
|
|
602
|
+
const w = writeOf(command_traits_1.NPM_WRITES[cmd], after);
|
|
603
|
+
if (w !== undefined && w !== null)
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
if (sub === 'publish')
|
|
609
|
+
return true;
|
|
610
|
+
if (tool === 'yarn' && sub === 'npm') {
|
|
611
|
+
const g = firstPositional(after);
|
|
612
|
+
if (g !== undefined) {
|
|
613
|
+
const w = writeOf(command_traits_1.YARN_NPM_WRITES[g], after.slice(after.indexOf(g) + 1));
|
|
614
|
+
if (w !== undefined && w !== null)
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const w = writeOf(tool === 'yarn' ? command_traits_1.YARN_WRITES[sub] : command_traits_1.NPM_WRITES[sub], after);
|
|
620
|
+
if (w !== undefined && w !== null)
|
|
621
|
+
return true;
|
|
622
|
+
}
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
/** The command a shell's `-c` (or a cluster holding `c`, such as `-lc`) runs, or null. `-o <opt>` takes a value. */
|
|
626
|
+
function shellCommandArg(args) {
|
|
627
|
+
for (let k = 0; k < args.length; k++) {
|
|
628
|
+
if (args[k] === '-o' || args[k] === '+o') {
|
|
629
|
+
k++;
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
if (/^-[A-Za-z]*c[A-Za-z]*$/.test(args[k]))
|
|
633
|
+
return args[k + 1] ?? null;
|
|
634
|
+
if (args[k] === '--')
|
|
635
|
+
return null;
|
|
636
|
+
if (!args[k].startsWith('-') && !args[k].startsWith('+'))
|
|
637
|
+
return null;
|
|
638
|
+
}
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
/** The clause whose output reaches a shell's stdin, through tee and cat (without a file). */
|
|
642
|
+
function source(clause, all) {
|
|
643
|
+
let up = clause.pipedFrom !== null ? all[clause.pipedFrom] : null;
|
|
644
|
+
for (let hops = 0; up !== null && hops < 16; hops++) {
|
|
645
|
+
const n = up.words[0]?.value ?? '';
|
|
646
|
+
const passes = n === 'tee' || (n === 'cat' && up.words.slice(1).every((w) => w.value === '-' || w.value.startsWith('-')));
|
|
647
|
+
if (!passes || up.pipedFrom === null)
|
|
648
|
+
break;
|
|
649
|
+
up = all[up.pipedFrom];
|
|
650
|
+
}
|
|
651
|
+
return up;
|
|
652
|
+
}
|
|
653
|
+
/** The program a shell or interpreter reads from stdin: its here-documents and here-strings, and the data words of the
|
|
654
|
+
* clause whose output reaches it. */
|
|
655
|
+
function stdinProgram(clause, all) {
|
|
656
|
+
const out = clause.heredocs.map((h) => h.body);
|
|
657
|
+
const up = source(clause, all);
|
|
658
|
+
if (up !== null) {
|
|
659
|
+
out.push(up.words.slice(1).map((w) => w.value).filter((v) => !v.startsWith('-')).join(' '));
|
|
660
|
+
out.push(...up.heredocs.map((h) => h.body));
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
function releaseTool(name, args, clause, run) {
|
|
665
|
+
const tool = command_traits_1.RELEASE_TOOLS[name];
|
|
666
|
+
if (tool === undefined || !(tool.needs?.(args) ?? true) || (tool.dry.length > 0 && (0, command_traits_1.dryFlagOn)(args, tool.dry)))
|
|
667
|
+
return;
|
|
668
|
+
if (args.some((a) => command_traits_1.RELEASE_HELP.has(a)))
|
|
669
|
+
return; // its help or version (A-SPEC-794.74)
|
|
670
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, name), word: name, why: `\`${name}\` is a release tool that publishes`, rewrite: tool.dry.length > 0 ? `run it with ${tool.dry[0]} first, or ask the owner` : 'ask the owner' });
|
|
671
|
+
}
|
|
672
|
+
/** A write rule's verdict for a subcommand's remaining words: the writing word, null (reads), or undefined (no rule). */
|
|
673
|
+
function writeOf(rule, rest) {
|
|
674
|
+
if (rule === undefined)
|
|
675
|
+
return undefined;
|
|
676
|
+
if (rule === true)
|
|
677
|
+
return '';
|
|
678
|
+
const ss = firstPositional(rest);
|
|
679
|
+
if (ss === undefined || rule.reads.includes(ss))
|
|
680
|
+
return null;
|
|
681
|
+
return ss;
|
|
682
|
+
}
|
|
683
|
+
function registryClause(tool, args, argWords, clause, run, place, depth) {
|
|
684
|
+
const end = args.indexOf('--');
|
|
685
|
+
const before = end < 0 ? args : args.slice(0, end);
|
|
686
|
+
if (before.some((a) => a === '--help' || a === '-h'))
|
|
687
|
+
return;
|
|
688
|
+
const ignoreScripts = before.some((a) => a === '--ignore-scripts' || a === '--ignore-scripts=true');
|
|
689
|
+
const dry = (0, command_traits_1.dryFlagOn)(args, ['--dry-run']);
|
|
690
|
+
// where its scripts run: every --prefix, -C, --dir, --cwd and -w the command names (A-SPEC-794.71: all of them)
|
|
691
|
+
let places = [{ at: { ...place }, explicit: false }];
|
|
692
|
+
if (before.some((a) => UNRESOLVED_FLAGS.has(a) || a === '--filter' || a === '-F' || a.startsWith('--filter=')))
|
|
693
|
+
places = [{ at: { dir: undefined, known: false }, explicit: false }];
|
|
694
|
+
const named = optionValues(argWords, ['--prefix', '-C', '--dir', '--cwd']);
|
|
695
|
+
if (named.length > 0)
|
|
696
|
+
places = named.map((w) => ({ at: resolveDir(w, place, new Map()), explicit: true }));
|
|
697
|
+
const ws = optionValues(argWords, ['-w', '--workspace']);
|
|
698
|
+
if (ws.length > 0) {
|
|
699
|
+
places = ws.map((w) => {
|
|
700
|
+
const p = resolveDir(w, place, new Map());
|
|
701
|
+
return { at: p.known && p.dir !== undefined && readAt(run, p.dir, true) !== null ? p : { dir: undefined, known: false }, explicit: false };
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
// A-SPEC-794.82 — a finding is a step of the budget
|
|
705
|
+
const found = (word, why, rewrite) => { if (!spent(run))
|
|
706
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, word), word, why, rewrite }); };
|
|
707
|
+
const runScripts = (sr, rest, word) => {
|
|
708
|
+
if (ignoreScripts && sr.ignoreSkips === 'all')
|
|
709
|
+
return;
|
|
710
|
+
// A-SPEC-794.75 — a global install reads no directory's lifecycle; an install into a --prefix without a package.json
|
|
711
|
+
// has no root lifecycle; a publish of a folder reads that folder's lifecycle
|
|
712
|
+
const install = sr.names !== 'named' && sr.names.includes('postinstall');
|
|
713
|
+
let at = places;
|
|
714
|
+
// A-SPEC-794.76 — a global install of registry names reads no lifecycle; with no argument, `.` or a folder it installs
|
|
715
|
+
// that folder (as a link) and runs its lifecycle (npm lib/commands/install.js)
|
|
716
|
+
if (install && before.some((a) => a === '-g' || a === '--global' || a === '--location=global')) {
|
|
717
|
+
const pkgs = rest.filter((a, i) => !a.startsWith('-') && !(i > 0 && command_traits_1.NPM_VALUED_OPTIONS.has(rest[i - 1])));
|
|
718
|
+
const isFolder = (p) => /^(?:\.{1,2}(?:\/|$)|\/|~)/.test(p) || (p.includes('/') && !p.startsWith('@') && !p.includes(':'));
|
|
719
|
+
if (pkgs.length > 0 && !pkgs.some(isFolder))
|
|
720
|
+
return;
|
|
721
|
+
// each folder's word from a map built once (A-SPEC-794.80: a find per folder was quadratic)
|
|
722
|
+
const wordOf = new Map();
|
|
723
|
+
for (const w of argWords)
|
|
724
|
+
if (!wordOf.has(w.value))
|
|
725
|
+
wordOf.set(w.value, w);
|
|
726
|
+
// each folder is resolved only when it is read, so a closed budget stops the rest (A-SPEC-794.80)
|
|
727
|
+
at = pkgs.length === 0 ? places : pkgs.filter(isFolder).map((f) => () => ({ at: resolveDir(wordOf.get(f), place, new Map()), explicit: f !== '.' }));
|
|
728
|
+
}
|
|
729
|
+
if (sr === command_traits_1.NPM_SCRIPT_RUNS.publish) {
|
|
730
|
+
const folder = subcommands(rest)[0]?.sub;
|
|
731
|
+
const w = folder === undefined ? undefined : argWords.find((x) => x.value === folder);
|
|
732
|
+
if (folder !== undefined && !/\.t(?:ar\.)?gz$/.test(folder) && /^\.|\//.test(folder))
|
|
733
|
+
at = [{ at: resolveDir(w, place, new Map()), explicit: true }];
|
|
734
|
+
}
|
|
735
|
+
let names;
|
|
736
|
+
if (sr.names === 'named') {
|
|
737
|
+
// the script name after the run's own options, valued ones skipping their value (A-SPEC-794.74)
|
|
738
|
+
const s = subcommands(rest)[0]?.sub;
|
|
739
|
+
if (s === undefined)
|
|
740
|
+
return;
|
|
741
|
+
names = ignoreScripts ? [s] : [`pre${s}`, s, `post${s}`];
|
|
742
|
+
}
|
|
743
|
+
else
|
|
744
|
+
names = ignoreScripts ? sr.names.filter((n) => !/^(?:pre|post)/.test(n) || n === 'prepare') : [...sr.names];
|
|
745
|
+
for (const q of at) {
|
|
746
|
+
if (spent(run))
|
|
747
|
+
return; // A-SPEC-794.82 — the clock is read in this loop too
|
|
748
|
+
const p = typeof q === 'function' ? q() : q;
|
|
749
|
+
scriptsAt(names, p.at, p.explicit, clause, word, run, depth, false, install);
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
// a bare `yarn` installs (A-SPEC-794.74)
|
|
753
|
+
if (tool === 'yarn' && subcommands(args).length === 0)
|
|
754
|
+
runScripts(command_traits_1.NPM_SCRIPT_RUNS.install, [], 'yarn');
|
|
755
|
+
for (const { sub, rest } of subcommands(args)) {
|
|
756
|
+
if (sub === TOO_MANY) {
|
|
757
|
+
overBudget(run, `more than ${MAX_CANDIDATES} options the gate does not know before the subcommand`);
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (tool === 'npm' || tool === 'bun' && sub === 'x') {
|
|
761
|
+
const cmd = tool === 'bun' ? 'exec' : (0, command_traits_1.npmCommand)(sub);
|
|
762
|
+
if (cmd === undefined)
|
|
763
|
+
continue;
|
|
764
|
+
if (cmd === 'exec') {
|
|
765
|
+
execCall(rest, run, place, depth);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
if (cmd === 'explore') {
|
|
769
|
+
// the command runs in the explored dependency's directory, node_modules/<pkg>
|
|
770
|
+
const k = rest.indexOf('--');
|
|
771
|
+
const pkg = firstPositional(rest);
|
|
772
|
+
const at = pkg !== undefined && place.known && place.dir !== undefined ? { dir: path.join(place.dir, 'node_modules', pkg), known: true } : { dir: undefined, known: false };
|
|
773
|
+
if (k >= 0)
|
|
774
|
+
judge(rest.slice(k + 1).map(quote).join(' '), run, at, depth + 1);
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
const w = writeOf(command_traits_1.NPM_WRITES[cmd], rest);
|
|
778
|
+
if (w !== undefined && w !== null) {
|
|
779
|
+
const honours = (0, command_traits_1.npmHonoursDryRun)(cmd) || (w !== '' && (command_traits_1.NPM_DRY_RUN_SUBCOMMANDS[cmd] ?? []).includes(w));
|
|
780
|
+
if (!(dry && honours)) {
|
|
781
|
+
const said = w === '' ? `npm ${sub}` : `npm ${sub} ${w}`;
|
|
782
|
+
found(w === '' ? sub : w, dry ? `\`${said}\` writes to the registry, and \`npm ${cmd}${w === '' ? '' : ` ${w}`}\` does not follow --dry-run` : `\`${said}\` writes to the registry`, rewriteFor(honours));
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const sr = command_traits_1.NPM_SCRIPT_RUNS[cmd];
|
|
786
|
+
if (sr !== undefined)
|
|
787
|
+
runScripts(sr, rest, sub);
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
// A-SPEC-794.74 — pnpm's recursive aliases run in every package
|
|
791
|
+
if (tool === 'pnpm' && command_traits_1.PNPM_RECURSIVE.has(sub)) {
|
|
792
|
+
// a run of recursive aliases and -r is skipped by an index, then judged once (A-SPEC-794.80: recursion per alias
|
|
793
|
+
// was quadratic and overflowed the stack)
|
|
794
|
+
// A-SPEC-794.82 — the options between the links are kept and the alias words dropped, in the same index loop
|
|
795
|
+
// (794.80 stopped at the first option, and `m --verbose m …` recursed out of memory); an option the table does
|
|
796
|
+
// not know ends the chain
|
|
797
|
+
const keep = [];
|
|
798
|
+
let i = 0;
|
|
799
|
+
for (; i < rest.length; i++) {
|
|
800
|
+
const v = rest[i];
|
|
801
|
+
if (command_traits_1.PNPM_RECURSIVE.has(v) || v === '-r' || v === '--recursive')
|
|
802
|
+
continue;
|
|
803
|
+
if (command_traits_1.NPM_VALUED_OPTIONS.has(v) && rest[i + 1] !== undefined) {
|
|
804
|
+
keep.push(i, i + 1);
|
|
805
|
+
i++;
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
if (v.startsWith('-') && (v.includes('=') || NPM_FLAGS.has(v))) {
|
|
809
|
+
keep.push(i);
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
break;
|
|
813
|
+
}
|
|
814
|
+
const base = argWords.length - rest.length;
|
|
815
|
+
const idx = [...keep, ...Array.from({ length: rest.length - i }, (_, j) => i + j)];
|
|
816
|
+
registryClause('pnpm', idx.map((j) => rest[j]), idx.map((j) => argWords[base + j]), clause, run, { dir: undefined, known: false }, depth);
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
// the install family and version run the lifecycle of the package they act on
|
|
820
|
+
if (tool !== 'npm' && ['install', 'i', 'add', 'version'].includes(sub)) {
|
|
821
|
+
runScripts(command_traits_1.NPM_SCRIPT_RUNS[sub === 'version' ? 'version' : 'install'], rest, sub);
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (tool === 'yarn' && sub === 'workspace') {
|
|
825
|
+
// a chain `workspace a workspace b …` is followed by an index, then judged once (A-SPEC-794.80)
|
|
826
|
+
// A-SPEC-794.82 — options between the links are kept, the `workspace <pkg>` pairs dropped, in one index loop
|
|
827
|
+
const keep = [];
|
|
828
|
+
let i = 1;
|
|
829
|
+
for (; i < rest.length; i++) {
|
|
830
|
+
const v = rest[i];
|
|
831
|
+
if (v === 'workspace' && rest[i + 1] !== undefined) {
|
|
832
|
+
i++;
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
if (command_traits_1.NPM_VALUED_OPTIONS.has(v) && rest[i + 1] !== undefined) {
|
|
836
|
+
keep.push(i, i + 1);
|
|
837
|
+
i++;
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (v.startsWith('-') && (v.includes('=') || NPM_FLAGS.has(v))) {
|
|
841
|
+
keep.push(i);
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
break;
|
|
845
|
+
}
|
|
846
|
+
const base = argWords.length - rest.length;
|
|
847
|
+
const idx = [...keep, ...Array.from({ length: rest.length - i }, (_, j) => i + j)];
|
|
848
|
+
registryClause('yarn', idx.map((j) => rest[j]), idx.map((j) => argWords[base + j]), clause, run, { dir: undefined, known: false }, depth);
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
if (tool === 'yarn' && sub === 'workspaces') {
|
|
852
|
+
// v1 `yarn workspaces run <s>`, and berry's `foreach` after its own valued options (A-SPEC-794.75)
|
|
853
|
+
let k = rest[0] === 'run' ? 0 : -1;
|
|
854
|
+
if (rest[0] === 'foreach') {
|
|
855
|
+
for (let j = 1; j < rest.length; j++) {
|
|
856
|
+
if (command_traits_1.YARN_FOREACH_VALUED.has(rest[j])) {
|
|
857
|
+
j++;
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
if (!rest[j].startsWith('-')) {
|
|
861
|
+
k = j;
|
|
862
|
+
break;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
if (k >= 0)
|
|
867
|
+
registryClause('yarn', rest.slice(k), argWords.slice(argWords.length - rest.length + k), clause, run, { dir: undefined, known: false }, depth);
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
if ((tool === 'pnpm' || tool === 'yarn') && (sub === 'exec' || sub === 'dlx')) {
|
|
871
|
+
execCall(rest, run, place, depth);
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
const rule = tool === 'yarn' ? (sub === 'npm' ? undefined : command_traits_1.YARN_WRITES[sub]) : sub === 'publish' ? true : tool === 'pnpm' ? command_traits_1.NPM_WRITES[sub] : undefined;
|
|
875
|
+
const npmGroup = tool === 'yarn' && sub === 'npm' ? firstPositional(rest) : undefined;
|
|
876
|
+
const w = npmGroup !== undefined ? writeOf(command_traits_1.YARN_NPM_WRITES[npmGroup], rest.slice(rest.indexOf(npmGroup) + 1)) : writeOf(rule, rest);
|
|
877
|
+
if (w !== undefined && w !== null) {
|
|
878
|
+
const honours = sub === 'publish' || npmGroup === 'publish';
|
|
879
|
+
if (!(dry && honours))
|
|
880
|
+
found(npmGroup ?? sub, `\`${tool} ${npmGroup !== undefined ? `npm ${npmGroup}` : sub}${w === '' ? '' : ` ${w}`}\` writes to the registry`, rewriteFor(honours));
|
|
881
|
+
if (sub === 'publish' || npmGroup === 'publish')
|
|
882
|
+
runScripts(command_traits_1.NPM_SCRIPT_RUNS.publish, rest, sub); // its pre/postpublish (A-SPEC-794.74)
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
if (command_traits_1.RELEASE_TOOLS[sub] !== undefined || command_traits_1.PACKAGE_BINS[sub] !== undefined) {
|
|
886
|
+
releaseTool(command_traits_1.PACKAGE_BINS[sub] ?? sub, rest, clause, run);
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
if (sub === 'run' || sub === 'run-script')
|
|
890
|
+
runScripts({ names: 'named', ignoreSkips: 'prepost' }, rest, sub);
|
|
891
|
+
else if (tool === 'bun' && (0, command_traits_1.managerBuiltins)('bun').has(sub))
|
|
892
|
+
continue; // bun test is its runner, not a script
|
|
893
|
+
else if (['test', 'start', 'stop', 'restart'].includes(sub))
|
|
894
|
+
runScripts({ names: [`pre${sub}`, sub, `post${sub}`], ignoreSkips: 'prepost' }, rest, sub);
|
|
895
|
+
else if (!(0, command_traits_1.managerBuiltins)(tool).has(sub)) { // each manager's own built-ins (A-SPEC-794.76)
|
|
896
|
+
if (ignoreScripts)
|
|
897
|
+
continue;
|
|
898
|
+
for (const p of places)
|
|
899
|
+
scriptsAt([`pre${sub}`, sub, `post${sub}`], p.at, p.explicit, clause, sub, run, depth, true);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
/** `npm exec`, `npm x`, `bun x`, `pnpm exec|dlx`: `-c <command>` is a command; otherwise the package runs its args. */
|
|
904
|
+
function execCall(rest, run, place, depth) {
|
|
905
|
+
for (let k = 0; k < rest.length; k++) {
|
|
906
|
+
if ((rest[k] === '-c' || rest[k] === '--call') && rest[k + 1] !== undefined) {
|
|
907
|
+
judge(rest[k + 1], run, place, depth + 1);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
if (rest[k].startsWith('--call=')) {
|
|
911
|
+
judge(rest[k].slice('--call='.length), run, place, depth + 1);
|
|
912
|
+
return;
|
|
913
|
+
} // A-SPEC-794.74
|
|
914
|
+
if (rest[k] === '--package' || rest[k] === '-p') {
|
|
915
|
+
k++;
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
if (command_traits_1.NPM_VALUED_OPTIONS.has(rest[k])) {
|
|
919
|
+
k++;
|
|
920
|
+
continue;
|
|
921
|
+
} // -w X, --prefix X, --loglevel X before -c (A-SPEC-794.75)
|
|
922
|
+
if (rest[k] === '--') {
|
|
923
|
+
judge(rest.slice(k + 1).map(quote).join(' '), run, place, depth + 1);
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
if (!rest[k].startsWith('-')) {
|
|
927
|
+
judge(rest.slice(k).map(quote).join(' '), run, place, depth + 1);
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
/** run-s, run-p, npm-run-all: the named scripts (globs matched) of the package the command runs in. */
|
|
933
|
+
function scriptsByName(args, clause, word, run, place, depth) {
|
|
934
|
+
const patterns = args.filter((a) => !a.startsWith('-'));
|
|
935
|
+
if (patterns.length === 0)
|
|
936
|
+
return;
|
|
937
|
+
if (!place.known || place.dir === undefined) {
|
|
938
|
+
scriptsAnywhere(patterns.filter((p) => !/[*?]/.test(p)), clause, word, run, depth, true);
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
const scripts = readAt(run, place.dir, false) ?? {};
|
|
942
|
+
const names = new Set();
|
|
943
|
+
for (const p of patterns) {
|
|
944
|
+
if (!/[*?]/.test(p)) {
|
|
945
|
+
names.add(p);
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
const re = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^:]*').replace(/\?/g, '.')}$`);
|
|
949
|
+
for (const n of Object.keys(scripts))
|
|
950
|
+
if (re.test(n))
|
|
951
|
+
names.add(n);
|
|
952
|
+
}
|
|
953
|
+
scriptsAt([...names].flatMap((n) => [`pre${n}`, n, `post${n}`]), place, false, clause, word, run, depth);
|
|
954
|
+
}
|
|
955
|
+
/** One directory's scripts, read once per judgement. */
|
|
956
|
+
function readAt(run, dir, explicit) {
|
|
957
|
+
const key = `${explicit ? 'x' : 'w'}:${dir}`;
|
|
958
|
+
if (run.memo.dirs.has(key))
|
|
959
|
+
return run.memo.dirs.get(key) ?? null;
|
|
960
|
+
// A-SPEC-794.80 — the directory budget: past it, the judgement stops with the named refusal (and reads no more)
|
|
961
|
+
if (run.memo.dirs.size >= BUDGET_DIRS) {
|
|
962
|
+
overBudget(run, `more than ${BUDGET_DIRS.toLocaleString('en-US')} directories read`);
|
|
963
|
+
return {};
|
|
964
|
+
}
|
|
965
|
+
let s;
|
|
966
|
+
try {
|
|
967
|
+
s = run.ctx.readScripts === undefined ? {} : run.ctx.readScripts(dir, explicit);
|
|
968
|
+
}
|
|
969
|
+
catch {
|
|
970
|
+
s = null;
|
|
971
|
+
}
|
|
972
|
+
run.memo.dirs.set(key, s);
|
|
973
|
+
return s;
|
|
974
|
+
}
|
|
975
|
+
/** The acts a script body performs in a directory, judged once per judgement. */
|
|
976
|
+
function actsOf(body, run, at, depth, name) {
|
|
977
|
+
// A-SPEC-794.77 — a package script is keyed by (directory, script name); the body is never part of a key
|
|
978
|
+
// A-SPEC-794.78 — the two kinds of key carry their own prefix, so a body never equals a name key
|
|
979
|
+
const key = name !== undefined ? `n:${at.known ? at.dir : '?'}\u0000${name}` : `b:${at.known ? at.dir : '?'}\u0000${body}`;
|
|
980
|
+
const memo = run.memo.acts.get(key);
|
|
981
|
+
if (memo !== undefined)
|
|
982
|
+
return memo;
|
|
983
|
+
const inner = { ctx: run.ctx, findings: [], depth, memo: run.memo };
|
|
984
|
+
run.memo.acts.set(key, new Set()); // a script that runs itself ends here
|
|
985
|
+
judge(body, inner, at, depth + 1);
|
|
986
|
+
const acts = new Set(inner.findings.map((f) => f.act));
|
|
987
|
+
run.memo.acts.set(key, acts);
|
|
988
|
+
return acts;
|
|
989
|
+
}
|
|
990
|
+
function scriptFinding(act, n, clause, word, run, where = '') {
|
|
991
|
+
if (spent(run))
|
|
992
|
+
return; // A-SPEC-794.82 — a finding is a step of the budget
|
|
993
|
+
run.findings.push({
|
|
994
|
+
act, clause: around(clause.source, word), word: n, // the word is the script that publishes or pushes (A-SPEC-794.72)
|
|
995
|
+
why: `${where}the package script \`${n}\` it runs ${act === 'push' ? 'pushes' : 'publishes'}`,
|
|
996
|
+
rewrite: act === 'push' ? REWRITE_PUSH : 'run the script\'s other steps directly, or ask the owner',
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
/** The bodies of the named scripts: judged where they run; in an unresolved directory, in every package. */
|
|
1000
|
+
function scriptsAt(names, at, explicit, clause, word, run, depth, bare = false, missingOk = false) {
|
|
1001
|
+
if (!at.known || at.dir === undefined) {
|
|
1002
|
+
scriptsAnywhere(names, clause, word, run, depth, bare);
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const scripts = readAt(run, at.dir, explicit);
|
|
1006
|
+
if (scripts === null && missingOk && explicit)
|
|
1007
|
+
return; // an install into a directory without a package.json (A-SPEC-794.75)
|
|
1008
|
+
if (scripts === null) {
|
|
1009
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, word), word, why: 'it runs package scripts the gate cannot read (a malformed or missing package.json)', rewrite: 'fix the package.json, or name an existing directory' });
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
const done = new Set();
|
|
1013
|
+
for (const n of names) {
|
|
1014
|
+
const body = scripts[n];
|
|
1015
|
+
if (typeof body !== 'string')
|
|
1016
|
+
continue;
|
|
1017
|
+
for (const act of actsOf(body, run, at, depth, n))
|
|
1018
|
+
if (!done.has(act)) {
|
|
1019
|
+
done.add(act);
|
|
1020
|
+
scriptFinding(act, n, clause, word, run);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
function listing(run) {
|
|
1025
|
+
if (run.memo.listing !== undefined)
|
|
1026
|
+
return run.memo.listing;
|
|
1027
|
+
const got = run.ctx.allScripts?.() ?? null;
|
|
1028
|
+
run.memo.listing = got === null ? null : Array.isArray(got) ? { packages: got, unreadable: [] } : got;
|
|
1029
|
+
return run.memo.listing;
|
|
1030
|
+
}
|
|
1031
|
+
/** A script run whose directory is unresolved: closed when some package's script of that name publishes or pushes. */
|
|
1032
|
+
function scriptsAnywhere(names, clause, word, run, depth, bare = false) {
|
|
1033
|
+
const list = listing(run);
|
|
1034
|
+
if (list === null || list.limit !== undefined) {
|
|
1035
|
+
run.findings.push({ act: 'publish', clause: around(clause.source, word), word, why: `it runs package scripts in a directory the gate cannot resolve, and the repository's packages cannot be listed${list?.limit !== undefined ? ` (${list.limit})` : ''}`, rewrite: REWRITE_DIR });
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
const skipped = list.unreadable.length > 0 ? `; unreadable, skipped: ${list.unreadable.slice(0, 3).join(', ')}${list.unreadable.length > 3 ? ', …' : ''}` : '';
|
|
1039
|
+
const expanded = [...new Set(bare ? names : names.flatMap((n) => (/^(?:pre|post)/.test(n) ? [n] : [`pre${n}`, n, `post${n}`])))];
|
|
1040
|
+
// A-SPEC-794.75 — a name→packages index, built once per judgement: a clause looks up only the packages that hold
|
|
1041
|
+
// the names it runs (the scan of every package per clause was 3.5 s on 1 MB over 2,000 packages)
|
|
1042
|
+
if (run.memo.byName === undefined) {
|
|
1043
|
+
const index = new Map();
|
|
1044
|
+
for (const { dir, scripts } of list.packages) {
|
|
1045
|
+
for (const [n, body] of Object.entries(scripts)) {
|
|
1046
|
+
if (typeof body !== 'string')
|
|
1047
|
+
continue;
|
|
1048
|
+
let at = index.get(n);
|
|
1049
|
+
if (at === undefined) {
|
|
1050
|
+
at = [];
|
|
1051
|
+
index.set(n, at);
|
|
1052
|
+
}
|
|
1053
|
+
at.push({ dir, body });
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
run.memo.byName = index;
|
|
1057
|
+
}
|
|
1058
|
+
// A-SPEC-794.77 — the result for a set of names is computed once per judgement and reused by every clause that runs
|
|
1059
|
+
// the same names; only the clause text is the clause's own
|
|
1060
|
+
const setKey = expanded.join('\u0000');
|
|
1061
|
+
let found = run.memo.anywhere?.get(setKey);
|
|
1062
|
+
if (found === undefined) {
|
|
1063
|
+
found = [];
|
|
1064
|
+
const done = new Set();
|
|
1065
|
+
outer: for (const n of expanded) {
|
|
1066
|
+
for (const { dir, body } of run.memo.byName.get(n) ?? []) {
|
|
1067
|
+
for (const act of actsOf(body, run, { dir, known: true }, depth, n)) {
|
|
1068
|
+
if (done.has(act))
|
|
1069
|
+
continue;
|
|
1070
|
+
done.add(act);
|
|
1071
|
+
const rel = run.ctx.projectRoot !== undefined ? path.relative(run.ctx.projectRoot, dir) || '.' : dir;
|
|
1072
|
+
found.push({ act, n, why: `it runs package scripts in a directory the gate cannot resolve, and \`${rel}\`'s script \`${n}\` ${act === 'push' ? 'pushes' : 'publishes'}${skipped}` });
|
|
1073
|
+
}
|
|
1074
|
+
if (done.size === 2)
|
|
1075
|
+
break outer;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
(run.memo.anywhere ??= new Map()).set(setKey, found);
|
|
1079
|
+
}
|
|
1080
|
+
for (const f of found)
|
|
1081
|
+
run.findings.push({ act: f.act, clause: around(clause.source, word), word: f.n, why: f.why, rewrite: REWRITE_DIR });
|
|
1082
|
+
}
|
|
1083
|
+
function renderFinding(f) {
|
|
1084
|
+
return `${f.act}: \`${f.clause}\`${f.word ? ` (word \`${f.word.replace(/`/g, '\\`')}\`)` : ''} — ${f.why}${f.rewrite ? `; ${f.rewrite}` : ''}`;
|
|
1085
|
+
}
|
|
1086
|
+
function judgeOutward(command, ctx = {}) {
|
|
1087
|
+
const run = { ctx, findings: [], depth: ctx.depth ?? 0, memo: { dirs: new Map(), acts: new Map(), budget: { words: 0, t0: Date.now(), closed: false, steps: 0 } } };
|
|
1088
|
+
const start = ctx.cwd ?? ctx.projectRoot;
|
|
1089
|
+
judge(command, run, { dir: start, known: start !== undefined }, run.depth);
|
|
1090
|
+
const acts = [...new Set(run.findings.map((f) => f.act))];
|
|
1091
|
+
const unjudged = run.memo.budget.why;
|
|
1092
|
+
// A-SPEC-794.87 — at most 200 findings are listed, the rest counted
|
|
1093
|
+
const rendered = [...new Set(run.findings.map(renderFinding))];
|
|
1094
|
+
const listed = rendered.length > exports.MAX_LISTED ? [...rendered.slice(0, exports.MAX_LISTED), `… and ${rendered.length - exports.MAX_LISTED} more`] : rendered;
|
|
1095
|
+
return { acts, reasons: [...listed, ...(unjudged === undefined ? [] : [unjudged])], findings: run.findings,
|
|
1096
|
+
...(unjudged === undefined ? {} : { unjudged }) };
|
|
1097
|
+
}
|
|
1098
|
+
/** The acts, both of them when the command could not be judged whole (A-SPEC-794.82: closed, never open). */
|
|
1099
|
+
function outwardActsOf(command, ctx = {}) {
|
|
1100
|
+
const v = judgeOutward(command, ctx);
|
|
1101
|
+
return v.unjudged === undefined ? v.acts : ['push', 'publish'];
|
|
1102
|
+
}
|