@skillstech/thunderlang 0.5.10 → 0.5.12

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 (66) hide show
  1. package/CHANGELOG.md +450 -0
  2. package/dist/core.cjs +30434 -7577
  3. package/dist/index.cjs +28576 -5328
  4. package/dist/learn.cjs +24201 -5367
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +49 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +65 -14
  34. package/src/model.mjs +496 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1017 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
@@ -0,0 +1,811 @@
1
+ // Words for the commands, expressions, and schedules that infrastructure and delivery files are made of, shared by
2
+ // the Dockerfile and GitHub Actions readers: `npm ci` -> "Installs what it needs (npm ci)", `${{ secrets.NPM_TOKEN }}`
3
+ // -> "the secret NPM_TOKEN", `0 2 * * *` -> "every day at 02:00 UTC". Unknown commands are kept ("Runs `x`"), never
4
+ // dropped; a secret is only ever named. Walks text character by character: no regex here can backtrack.
5
+
6
+ export const cap = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
7
+ export const lc = (s) => (s && !/^[A-Z]{2}|^[A-Z][a-z]*[A-Z]/.test(s) ? s.charAt(0).toLowerCase() + s.slice(1) : s);
8
+ export const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
9
+ export const orWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} or ${xs.at(-1)}`);
10
+ const short = (s, n = 80) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
11
+
12
+ /** Names that hold secrets: passwords, tokens, keys, credentials. */
13
+ export const SECRET_NAME = /(pass(word|wd)?|secret|token|api[_-]?key|private[_-]?key|access[_-]?key|credential|auth|pwd)(?![a-z])/i;
14
+
15
+ // ── GitHub Actions expressions: ${{ … }} ───────────────────────────────────────────────────────────────────
16
+
17
+ const GITHUB_WORDS = {
18
+ 'github.ref': 'the branch or tag', 'github.ref_name': 'the branch or tag name', 'github.head_ref': "the pull request's branch",
19
+ 'github.base_ref': 'the branch it will be merged into', 'github.event_name': 'the event that started it', 'github.actor': 'the person who started it',
20
+ 'github.triggering_actor': 'the person who started it', 'github.repository': 'the repository', 'github.repository_owner': "the repository's owner",
21
+ 'github.sha': 'the commit', 'github.run_id': 'the run', 'github.run_number': 'the run number', 'github.run_attempt': 'the attempt number',
22
+ 'github.workspace': 'the working folder', 'github.token': "the workflow's own token", 'github.server_url': 'the GitHub address', 'github.job': 'the job',
23
+ 'github.workflow': 'the workflow', 'github.ref_type': 'whether it is a branch or a tag', 'github.event.pull_request.head.sha': "the pull request's latest commit",
24
+ 'github.event.pull_request.head.ref': "the pull request's branch", 'github.event.pull_request.number': 'the pull request number',
25
+ 'github.event.pull_request.draft': 'whether the pull request is a draft', 'github.event.pull_request.merged': 'whether the pull request was merged',
26
+ 'github.event.release.tag_name': "the release's tag", 'github.event.action': 'what happened', 'runner.os': "the computer's system",
27
+ 'runner.temp': 'the temporary folder', 'runner.arch': "the computer's processor type", 'job.status': 'how the job is going',
28
+ };
29
+ const EVENT_WORDS = { push: 'a push', pull_request: 'a pull request', pull_request_target: 'a pull request', workflow_dispatch: 'someone starting it by hand', schedule: 'the schedule', release: 'a release', workflow_call: 'another workflow', workflow_run: 'another workflow finishing', merge_group: 'the merge queue', issues: 'an issue', issue_comment: 'a comment', repository_dispatch: 'another system' };
30
+
31
+ /** A context value (`steps.check.outputs.version`) in words. Secrets are named, never shown. */
32
+ export function valueWords(path) {
33
+ const p = String(path).trim();
34
+ if (GITHUB_WORDS[p]) return GITHUB_WORDS[p];
35
+ let m;
36
+ if ((m = /^secrets\.([\w-]+)$/.exec(p))) return `the secret ${m[1]}`;
37
+ if ((m = /^vars\.([\w-]+)$/.exec(p))) return `the variable ${m[1]}`;
38
+ if ((m = /^env\.([\w-]+)$/.exec(p))) return m[1];
39
+ if ((m = /^(?:github\.event\.)?inputs\.([\w-]+)$/.exec(p))) return `the ${m[1].replace(/[_-]+/g, ' ')} given when it starts`;
40
+ if ((m = /^matrix\.([\w-]+)$/.exec(p))) return `the ${m[1].replace(/[_-]+/g, ' ')} for this run`;
41
+ if ((m = /^steps\.([\w-]+)\.outputs\.([\w-]+)$/.exec(p))) return `the ${m[1].replace(/[_-]+/g, ' ')} step's ${m[2].replace(/[_-]+/g, ' ')}`;
42
+ if ((m = /^steps\.([\w-]+)\.(outcome|conclusion)$/.exec(p))) return `how the ${m[1].replace(/[_-]+/g, ' ')} step went`;
43
+ if ((m = /^needs\.([\w-]+)\.outputs\.([\w-]+)$/.exec(p))) return `the ${m[1].replace(/[_-]+/g, ' ')} job's ${m[2].replace(/[_-]+/g, ' ')}`;
44
+ if ((m = /^needs\.([\w-]+)\.result$/.exec(p))) return `how the ${m[1].replace(/[_-]+/g, ' ')} job went`;
45
+ if ((m = /^github\.event\.([\w.]+)$/.exec(p))) return `the event's ${m[1].split('.').join(' ').replace(/[_-]+/g, ' ')}`;
46
+ return null;
47
+ }
48
+
49
+ /** The secrets an expression or text names: `${{ secrets.NPM_TOKEN }}` -> ['NPM_TOKEN']. */
50
+ export function secretsIn(text) {
51
+ const out = [];
52
+ const s = String(text ?? '');
53
+ for (let i = s.indexOf('secrets.'); i >= 0; i = s.indexOf('secrets.', i + 8)) {
54
+ if (i > 0 && /[\w.]/.test(s[i - 1])) continue;
55
+ let j = i + 8;
56
+ while (j < s.length && /[\w-]/.test(s[j])) j++;
57
+ const name = s.slice(i + 8, j);
58
+ if (name && !out.includes(name)) out.push(name);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** Each `${{ … }}` in a text, with where it starts and ends. */
64
+ export function expressionsIn(text) {
65
+ const out = [];
66
+ const s = String(text ?? '');
67
+ for (let i = s.indexOf('${{'); i >= 0; i = s.indexOf('${{', i + 3)) {
68
+ const end = s.indexOf('}}', i + 3);
69
+ if (end < 0) break;
70
+ out.push({ at: i, end: end + 2, expr: s.slice(i + 3, end).trim() });
71
+ i = end;
72
+ }
73
+ return out;
74
+ }
75
+ export const hasExpression = (text) => String(text ?? '').includes('${{');
76
+
77
+ /** A text with each `${{ … }}` in words: a secret by name, anything else "(worked out when it runs)". */
78
+ export function sayExpressions(text) {
79
+ const s = String(text ?? '');
80
+ const xs = expressionsIn(s);
81
+ if (!xs.length) return s;
82
+ let out = '', last = 0;
83
+ for (const x of xs) {
84
+ const secret = /^secrets\.[\w-]+$/.exec(x.expr);
85
+ out += s.slice(last, x.at) + (secret ? `‹${valueWords(x.expr)}›` : '(worked out when it runs)');
86
+ last = x.end;
87
+ }
88
+ return out + s.slice(last);
89
+ }
90
+
91
+ // A tiny expression reader for `if:` conditions: ||, &&, !, ==, !=, <, >, calls, literals, context paths, ( ).
92
+ function exprTokens(src) {
93
+ const toks = [];
94
+ const s = String(src);
95
+ let i = 0;
96
+ while (i < s.length) {
97
+ const c = s[i];
98
+ if (c === ' ' || c === '\t' || c === '\n') { i++; continue; }
99
+ const two = s.slice(i, i + 2);
100
+ if (['||', '&&', '==', '!=', '<=', '>='].includes(two)) { toks.push({ op: two }); i += 2; continue; }
101
+ if ('!()<>,'.includes(c)) { toks.push({ op: c }); i++; continue; }
102
+ if (c === "'") { let j = i + 1, v = ''; while (j < s.length) { if (s[j] === "'" && s[j + 1] === "'") { v += "'"; j += 2; continue; } if (s[j] === "'") break; v += s[j++]; } toks.push({ str: v }); i = j + 1; continue; }
103
+ let j = i;
104
+ while (j < s.length && /[\w.\-*[\]]/.test(s[j])) j++;
105
+ if (j === i) return null; // something this reader does not know
106
+ toks.push({ word: s.slice(i, j) });
107
+ i = j;
108
+ }
109
+ return toks;
110
+ }
111
+ function exprTree(src) {
112
+ const t = exprTokens(src);
113
+ if (!t) return null;
114
+ let i = 0;
115
+ const peek = (op) => t[i]?.op === op;
116
+ const or = () => { let l = and(); while (l && peek('||')) { i++; const r = and(); l = r && { or: [l, r] }; } return l; };
117
+ const and = () => { let l = not(); while (l && peek('&&')) { i++; const r = not(); l = r && { and: [l, r] }; } return l; };
118
+ const not = () => { if (peek('!')) { i++; const x = not(); return x && { not: x }; } return cmp(); };
119
+ const cmp = () => { const l = prim(); if (l && ['==', '!=', '<', '>', '<=', '>='].includes(t[i]?.op)) { const op = t[i++].op; const r = prim(); return r && { cmp: op, l, r }; } return l; };
120
+ const prim = () => {
121
+ const x = t[i];
122
+ if (!x) return null;
123
+ if (x.op === '(') { i++; const e = or(); if (!peek(')')) return null; i++; return e; }
124
+ if (x.str != null) { i++; return { lit: x.str }; }
125
+ if (x.word) {
126
+ i++;
127
+ if (peek('(')) {
128
+ i++;
129
+ const args = [];
130
+ while (!peek(')')) { const a = or(); if (!a) return null; args.push(a); if (peek(',')) i++; else if (!peek(')')) return null; }
131
+ i++;
132
+ return { call: x.word, args };
133
+ }
134
+ if (/^(true|false|null)$/.test(x.word)) return { lit: x.word === 'null' ? '' : x.word };
135
+ if (/^-?\d+(\.\d+)?$/.test(x.word)) return { lit: x.word };
136
+ return { path: x.word };
137
+ }
138
+ return null;
139
+ };
140
+ const e = or();
141
+ return e && i === t.length ? e : null;
142
+ }
143
+ const valueOf = (n) => (n.lit != null ? (n.lit === '' ? 'empty' : n.lit) : n.path ? (valueWords(n.path) ?? n.path) : n.call ? callWords(n) : 'a value worked out when it runs');
144
+ function callWords(n) {
145
+ const a = n.args.map(valueOf);
146
+ switch (n.call.toLowerCase()) {
147
+ case 'hashfiles': return `a fingerprint of ${listWords(n.args.map((x) => x.lit ?? valueOf(x)))}`;
148
+ case 'format': return 'a text made from several values';
149
+ case 'fromjson': case 'tojson': return a[0] ?? 'a value';
150
+ case 'join': return `${a[0]}, joined`;
151
+ default: return `the result of ${n.call}`;
152
+ }
153
+ }
154
+
155
+ /** One condition as a clause: "the branch is main", "an earlier step failed". */
156
+ function clause(n, negate = false) {
157
+ if (n.not) return clause(n.not, !negate);
158
+ if (n.and || n.or) {
159
+ const parts = (n.and ?? n.or).map((x) => clause(x, false));
160
+ const joined = parts.join(n.and ? ' and ' : ' or ');
161
+ return negate ? `not (${joined})` : joined;
162
+ }
163
+ if (n.cmp) {
164
+ const l = n.l, r = n.r;
165
+ const path = l.path ?? r.path, lit = l.path ? r.lit : l.lit;
166
+ const isNot = (n.cmp === '!=') !== negate;
167
+ if (['<', '>', '<=', '>='].includes(n.cmp)) {
168
+ const words = { '<': 'less than', '>': 'more than', '<=': 'at most', '>=': 'at least' }[n.cmp];
169
+ return `${valueOf(l)} is ${negate ? 'not ' : ''}${words} ${valueOf(r)}`;
170
+ }
171
+ if (path === 'github.ref' && lit != null) {
172
+ if (lit.startsWith('refs/heads/')) return `the branch is ${isNot ? 'not ' : ''}${lit.slice(11)}`;
173
+ if (lit.startsWith('refs/tags/')) return `the tag is ${isNot ? 'not ' : ''}${lit.slice(10)}`;
174
+ }
175
+ if (path === 'github.event_name' && lit != null) return `it was ${isNot ? 'not ' : ''}started by ${EVENT_WORDS[lit] ?? `the ${lit.replace(/_/g, ' ')} event`}`;
176
+ if (lit === 'true' || lit === 'false') {
177
+ const v = valueOf(l.path ? l : r);
178
+ const yes = (lit === 'true') !== isNot;
179
+ // "whether the pull request is a draft" == false -> "the pull request is not a draft".
180
+ const w = /^whether (.+?) (is|was) (.+)$/.exec(v);
181
+ if (w) return `${w[1]} ${w[2]} ${yes ? '' : 'not '}${w[3]}`;
182
+ return `${v} is ${yes ? 'true' : 'false'}`;
183
+ }
184
+ return `${valueOf(l)} is ${isNot ? 'not ' : ''}${valueOf(r)}`;
185
+ }
186
+ if (n.call) {
187
+ const name = n.call.toLowerCase();
188
+ const a = n.args.map(valueOf);
189
+ if (name === 'success') return negate ? 'an earlier step failed' : 'every earlier step worked';
190
+ if (name === 'failure') return negate ? 'every earlier step worked' : 'an earlier step failed';
191
+ if (name === 'cancelled') return negate ? 'the run was not cancelled' : 'the run was cancelled';
192
+ if (name === 'always') return negate ? 'never' : 'always';
193
+ if (name === 'contains') return `${a[0]} ${negate ? 'does not contain' : 'contains'} ${a[1]}`;
194
+ if (name === 'startswith') {
195
+ if (n.args[0].path === 'github.ref' && n.args[1].lit === 'refs/tags/') return negate ? 'it is not a tag' : 'it is a tag';
196
+ return `${a[0]} ${negate ? 'does not start' : 'starts'} with ${a[1]}`;
197
+ }
198
+ if (name === 'endswith') return `${a[0]} ${negate ? 'does not end' : 'ends'} with ${a[1]}`;
199
+ return `${callWords(n)} is ${negate ? 'not ' : ''}true`;
200
+ }
201
+ return `${valueOf(n)} is ${negate ? 'not ' : ''}set`;
202
+ }
203
+
204
+ /**
205
+ * An `if:` condition as a question a person can answer with Yes or No. `always: true` means it runs even after a
206
+ * failure (not a question at all); `known: false` means Thunder could not read it, and the question quotes the code.
207
+ */
208
+ export function conditionQuestion(raw) {
209
+ const src = String(raw).trim().replace(/^\$\{\{\s*/, '').replace(/\s*\}\}$/, '');
210
+ const tree = exprTree(src);
211
+ if (!tree) return { question: `Is \`${short(src, 60)}\` true?`, known: false };
212
+ if (tree.call && /^always$/i.test(tree.call)) return { always: true, known: true };
213
+ // `always() && x`, `!cancelled() && x`: runs even after a failure, when x.
214
+ const parts = tree.and ? flatAnd(tree) : [tree];
215
+ const always = parts.some((p) => (p.call && /^always$/i.test(p.call)) || (p.not?.call && /^cancelled$/i.test(p.not.call)));
216
+ const rest = parts.filter((p) => !(p.call && /^always$/i.test(p.call)) && !(p.not?.call && /^cancelled$/i.test(p.not.call)) && !(p.call && /^success$/i.test(p.call)));
217
+ if (!rest.length) return always ? { always: true, known: true } : { question: 'Did every earlier step work?', known: true };
218
+ // Each part asked on its own, then joined: "Is the branch main, and was it started by a push?"
219
+ const ask = (p) => (p.or ? flatOr(p).map((x) => ask(x)).map((q, k) => (k ? lc(q) : q)).join(', or ') : questionOf(clause(p)).replace(/\?$/, ''));
220
+ const qs = rest.map(ask);
221
+ const question = `${qs.map((q, k) => (k ? lc(q) : q)).join(', and ')}?`;
222
+ return { question, known: true, ...(always ? { evenAfterFailure: true } : {}) };
223
+ }
224
+ const flatAnd = (n) => (n.and ? n.and.flatMap(flatAnd) : [n]);
225
+ const flatOr = (n) => (n.or ? n.or.flatMap(flatOr) : [n]);
226
+ function questionOf(text) {
227
+ let m;
228
+ if ((m = /^(.+?) is (not )?(.+)$/.exec(text))) return `Is ${m[1]} ${m[2] ?? ''}${m[3]}?`;
229
+ if ((m = /^(an earlier step|every earlier step) (failed|worked)$/.exec(text))) return `Did ${m[1]} ${m[2] === 'failed' ? 'fail' : 'work'}?`;
230
+ if ((m = /^the run was (not )?cancelled$/.exec(text))) return `Was the run ${m[1] ?? ''}cancelled?`;
231
+ if ((m = /^it was (not )?started by (.+)$/.exec(text))) return `Was it ${m[1] ?? ''}started by ${m[2]}?`;
232
+ if ((m = /^(.+?) (contains|starts with|ends with|does not contain) (.+)$/.exec(text)) && !/ (and|or) /.test(text)) return `Does ${m[1]} ${m[2] === 'contains' ? 'contain' : m[2] === 'starts with' ? 'start with' : m[2] === 'ends with' ? 'end with' : 'not contain'} ${m[3]}?`;
233
+ if ((m = /^it is (not )?a tag$/.exec(text))) return `Is it ${m[1] ?? ''}a tag?`;
234
+ return `${cap(text)}?`;
235
+ }
236
+
237
+ // ── Schedules: cron in words ─────────────────────────────────────────────────────────────────────────────
238
+
239
+ const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
240
+ const DAY_ABBR = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
241
+ const dayOf = (d) => (/^\d$/.test(d) ? DAYS[Number(d) % 7] : DAY_ABBR[d.toLowerCase().slice(0, 3)] != null ? DAYS[DAY_ABBR[d.toLowerCase().slice(0, 3)]] : null);
242
+ const num = (x) => /^\d{1,2}$/.test(x);
243
+ const hhmm = (h, m) => `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
244
+
245
+ /** A cron schedule in words ("every day at 02:00 UTC"), or null when it is not a simple one. GitHub runs cron in UTC. */
246
+ export function cronWords(cron) {
247
+ const f = String(cron).trim().split(/\s+/);
248
+ if (f.length !== 5) return null;
249
+ const [mi, h, dom, mon, dow] = f;
250
+ if (mon !== '*') return null;
251
+ if (num(mi) && num(h)) {
252
+ const at = `at ${hhmm(h, mi)} UTC`;
253
+ if (dom === '*' && dow === '*') return `every day ${at}`;
254
+ if (dom === '*') {
255
+ if (dow === '1-5') return `every weekday (Monday to Friday) ${at}`;
256
+ if (dow === '0,6' || dow === '6,0') return `every Saturday and Sunday ${at}`;
257
+ const days = dow.split(',').map(dayOf);
258
+ if (days.every(Boolean)) return `every ${listWords(days)} ${at}`;
259
+ return null;
260
+ }
261
+ if (dow === '*' && num(dom)) return `on day ${Number(dom)} of every month ${at}`;
262
+ return null;
263
+ }
264
+ if (dom !== '*' || dow !== '*') return null;
265
+ if (num(mi) && h === '*') return `every hour, at ${Number(mi)} minutes past`;
266
+ let m;
267
+ if ((m = /^\*\/(\d+)$/.exec(mi)) && h === '*') return `every ${m[1]} minutes`;
268
+ if (num(mi) && (m = /^\*\/(\d+)$/.exec(h))) return `every ${m[1]} hours, at ${Number(mi)} minutes past`;
269
+ return null;
270
+ }
271
+
272
+ // ── Shell commands in words ──────────────────────────────────────────────────────────────────────────────
273
+
274
+ /** Split a shell line into words, keeping quotes, $( ), ${ }, and ${{ }} together. */
275
+ export function shellWords(line) {
276
+ const out = [];
277
+ let cur = '', i = 0, has = false;
278
+ const s = String(line);
279
+ while (i < s.length) {
280
+ const c = s[i];
281
+ if (c === ' ' || c === '\t') { if (has) { out.push(cur); cur = ''; has = false; } i++; continue; }
282
+ has = true;
283
+ if (c === '\\' && i + 1 < s.length) { cur += s[i + 1]; i += 2; continue; }
284
+ if (c === "'") { const e = s.indexOf("'", i + 1); const end = e < 0 ? s.length : e; cur += s.slice(i + 1, end); i = end + 1; continue; }
285
+ if (c === '"') { let j = i + 1; while (j < s.length && s[j] !== '"') { if (s[j] === '\\') j++; j++; } cur += s.slice(i + 1, j).replace(/\\(["\\$`])/g, '$1'); i = j + 1; continue; }
286
+ if (c === '$' && (s[i + 1] === '(' || s[i + 1] === '{')) { const close = s[i + 1] === '(' ? ')' : '}'; const open = s[i + 1]; let d = 0, j = i + 1; for (; j < s.length; j++) { if (s[j] === open) d++; else if (s[j] === close && --d === 0) break; } cur += s.slice(i, j + 1); i = j + 1; continue; }
287
+ cur += c; i++;
288
+ }
289
+ if (has) out.push(cur);
290
+ return out;
291
+ }
292
+
293
+ /** Split at top-level `&&`, `||`, `;`, and `|`, outside quotes and $( ). Returns [{ text, op }] where op joins it to the next. */
294
+ export function splitCommands(line) {
295
+ const out = [];
296
+ const s = String(line);
297
+ let start = 0, q = null, d = 0;
298
+ for (let i = 0; i < s.length; i++) {
299
+ const c = s[i];
300
+ if (q) { if (c === '\\' && q === '"') { i++; continue; } if (c === q) q = null; continue; }
301
+ if (c === '\\') { i++; continue; }
302
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
303
+ if (c === '$' && (s[i + 1] === '(' || s[i + 1] === '{')) { d++; i++; continue; }
304
+ if (d && (c === ')' || c === '}')) { d--; continue; }
305
+ if (d) continue;
306
+ if (c === '#' && (i === 0 || /\s/.test(s[i - 1]))) { out.push({ text: s.slice(start, i).trim(), op: null }); return out.filter((x) => x.text); }
307
+ const two = s.slice(i, i + 2);
308
+ if (two === '&&' || two === '||') { out.push({ text: s.slice(start, i).trim(), op: two }); start = i + 2; i++; continue; }
309
+ if (c === ';' && s[i + 1] !== ';') { out.push({ text: s.slice(start, i).trim(), op: ';' }); start = i + 1; continue; }
310
+ if (c === '|' && s[i - 1] !== '>' ) { out.push({ text: s.slice(start, i).trim(), op: '|' }); start = i + 1; continue; }
311
+ if (c === '&' && s[i + 1] !== '>' && s[i - 1] !== '>' && s[i - 1] !== '&') { out.push({ text: s.slice(start, i).trim(), op: '&' }); start = i + 1; continue; }
312
+ }
313
+ out.push({ text: s.slice(start).trim(), op: null });
314
+ return out.filter((x) => x.text);
315
+ }
316
+
317
+ const pkgList = (args) => args.filter((a) => !a.startsWith('-') && !/^[A-Z_]+=/.test(a));
318
+ const firstArg = (args) => pkgList(args)[0];
319
+ const installs = (pkgs, how) => (pkgs.length ? `Installs ${listWords(pkgs.map((p) => p.replace(/=.*$/, '')))}` : `Installs what it needs (${how})`);
320
+ const hostOf = (url) => { const m = /^[a-z]+:\/\/([^/:?#]+)/i.exec(url); return m ? m[1] : url; };
321
+ const scriptName = (w) => w.replace(/^\.\//, '');
322
+
323
+ const JS_TOOLS = {
324
+ vsce: (a) => (a.includes('publish') ? 'Publishes the extension to the VS Code Marketplace' : a.includes('package') ? 'Packages the extension' : a.includes('show') ? 'Looks up the extension on the VS Code Marketplace' : null),
325
+ tsc: () => 'Checks the types (tsc)', eslint: () => 'Checks the code style (eslint)', prettier: (a) => (a.includes('--check') ? 'Checks the formatting (prettier)' : 'Formats the code (prettier)'),
326
+ jest: () => 'Runs the tests', vitest: () => 'Runs the tests', mocha: () => 'Runs the tests', playwright: (a) => (a.includes('install') ? 'Installs the test browsers' : 'Runs the browser tests'),
327
+ next: (a) => (a.includes('build') ? 'Builds it' : null), vercel: (a) => (a.some((x) => x === 'deploy' || x === '--prod') || !a.length ? 'Deploys to Vercel' : null),
328
+ 'semantic-release': () => 'Works out the next version and releases it', changeset: (a) => (a.includes('publish') ? 'Publishes the changed packages' : null),
329
+ };
330
+
331
+ function npmLike(tool, all) {
332
+ // Options that only say where to run (`--prefix compiler`, `-C web`, `--workspace x`) do not change what it does.
333
+ const args = [];
334
+ for (let i = 0; i < all.length; i++) { if (/^(--prefix|-C|--dir|--cwd|--workspace|-w|--filter|-F)$/.test(all[i])) { i++; continue; } if (/^(--prefix|--dir|--cwd|--workspace|--filter)=/.test(all[i]) || all[i] === '--silent' || all[i] === '-s') continue; args.push(all[i]); }
335
+ const [sub, ...rest] = args;
336
+ const run = sub === 'run' || sub === 'run-script' ? rest[0] : null;
337
+ const script = run ?? (tool !== 'npm' && sub && !['install', 'i', 'ci', 'add', 'publish', 'test', 't', 'view', 'info', 'version', 'exec', 'dlx', 'link', 'audit', 'remove', 'uninstall'].includes(sub) && !sub.startsWith('-') ? sub : null);
338
+ if (!sub || (tool !== 'npm' && sub === 'install' && !pkgList(rest).length)) return `Installs what it needs (${tool}${sub ? ` ${sub}` : ''})`;
339
+ if (sub === 'ci') return `Installs what it needs (${tool} ci)`;
340
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
341
+ const pkgs = pkgList(rest).filter((p) => !p.startsWith('$')).map((p) => p.replace(/@\$\(.*$|@\$\{.*$/, ''));
342
+ if (!pkgs.length) return `Installs what it needs (${tool} ${sub})`;
343
+ return `${installs(pkgs)}${rest.includes('-g') || rest.includes('--global') ? ' for the whole computer' : ''}`;
344
+ }
345
+ if (sub === 'test' || sub === 't' || script === 'test') return 'Runs the tests';
346
+ if (script === 'build') return 'Builds it';
347
+ if (script === 'lint') return `Checks the code style (${tool} ${run ? 'run ' : ''}lint)`;
348
+ if (script === 'typecheck' || script === 'type-check' || script === 'types') return `Checks the types (${tool} ${run ? 'run ' : ''}${script})`;
349
+ if (script) return `Runs the ${script} script`;
350
+ if (sub === 'publish') return 'Publishes the package to npm';
351
+ if (sub === 'view' || sub === 'info') return `Looks up ${firstArg(rest) ?? 'a package'} on npm`;
352
+ if (sub === 'version') return "Changes the package's version";
353
+ if (sub === 'prune') return 'Removes packages it no longer needs (npm prune)';
354
+ if (sub === 'audit') return 'Checks what it uses for known security problems';
355
+ if (sub === 'exec' || sub === 'dlx') return commandSays(rest.join(' ')).says;
356
+ return null;
357
+ }
358
+
359
+ /**
360
+ * One shell command in words. Returns { says, kind } where kind is 'call', 'set', 'fail', or 'return'. Anything it
361
+ * does not know reads "Runs `<command>`", so nothing is dropped.
362
+ */
363
+ export function commandSays(cmd) {
364
+ let text = String(cmd).trim();
365
+ let tail = '';
366
+ // `name=$(…)` and `name=value`: a value worked out or set, for later commands.
367
+ let m;
368
+ if ((m = /^(?:export\s+|local\s+|readonly\s+)?([A-Za-z_]\w*)=(.*)$/.exec(text)) && shellWords(m[2]).length <= 1) {
369
+ const v = m[2];
370
+ // Arithmetic: n=$((n + 1)) -> "Adds 1 to n"; total=$((a * b)) -> "Sets total to a times b".
371
+ const ar = /^"?\$\(\(\s*(.*?)\s*\)\)"?$/.exec(v);
372
+ if (ar) {
373
+ const e = ar[1].replace(/\$\{?(\w+)\}?/g, '$1');
374
+ let x;
375
+ if ((x = new RegExp(`^${m[1]}\\s*([-+])\\s*(\\w+)$`).exec(e))) return { kind: 'set', says: `${x[1] === '+' ? 'Adds' : 'Takes'} ${x[2]} ${x[1] === '+' ? 'to' : 'from'} ${m[1]}` };
376
+ return { kind: 'set', says: `Sets ${m[1]} to ${e.replace(/\s*\*\s*/g, ' times ').replace(/\s*\/\s*/g, ' divided by ').replace(/\s*\+\s*/g, ' plus ').replace(/\s*-\s*/g, ' minus ').replace(/\s*%\s*/g, ' remainder ')}` };
377
+ }
378
+ if (/^\$\([\s\S]*\)$/.test(v) || /^"\$\([\s\S]*\)"$/.test(v)) {
379
+ const inner = v.replace(/^"|"$/g, '').slice(2, -1);
380
+ const iw = shellWords(inner);
381
+ if ((iw[0] === 'echo' || iw[0] === 'printf') && !/[|]/.test(inner)) return { kind: 'set', says: `Works out ${m[1]}: the text "${short(iw.slice(1).filter((a) => !/^-[neE]+$/.test(a)).join(' '), 60)}"` };
382
+ return { kind: 'set', says: `Works out ${m[1]}: ${lc(commandSays(inner).says)}` };
383
+ }
384
+ if (SECRET_NAME.test(m[1]) && v && !/\$/.test(v)) return { kind: 'set', says: `Sets ${m[1]} (its value is written here, not shown)` };
385
+ return { kind: 'set', says: `Sets ${m[1]} to ${v.replace(/^["']|["']$/g, '') || 'nothing'}` };
386
+ }
387
+ let words = shellWords(text);
388
+ // Leading settings for one command (`CI=true npm test`) and `sudo` do not change what it does.
389
+ while (words.length > 1 && (/^[A-Za-z_]\w*=/.test(words[0]) || words[0] === 'sudo' || words[0] === 'time' || words[0] === 'exec' || words[0] === 'command')) words.shift();
390
+ // Redirections: GitHub's special files mean "for later steps"; other files say where the output goes.
391
+ const redir = [];
392
+ for (let i = 0; i < words.length; i++) {
393
+ const w = words[i];
394
+ const r = /^(\d?>>?|&>|<)(.*)$/.exec(w);
395
+ if (!r || w === '>' && false) continue;
396
+ const target = r[2] || words[i + 1] || '';
397
+ redir.push({ op: r[1], target });
398
+ words.splice(i, r[2] ? 1 : 2); i--;
399
+ }
400
+ for (const r of redir) {
401
+ const t = r.target.replace(/^["']|["']$/g, '');
402
+ if (/GITHUB_OUTPUT/.test(t)) tail = 'output';
403
+ else if (/GITHUB_ENV/.test(t)) tail = 'env';
404
+ else if (/GITHUB_PATH/.test(t)) tail = 'path';
405
+ else if (/GITHUB_STEP_SUMMARY/.test(t)) tail = 'summary';
406
+ else if (r.op.includes('>') && !/^\/dev\/(null|stderr|stdout)$|^&\d$/.test(t) && t) tail = tail || `file:${t}`;
407
+ }
408
+ let [tool0, ...args] = words; // eslint-disable-line prefer-const
409
+ if (tool0 === '[' || tool0 === '[[' || tool0 === 'test') return { kind: 'check', says: `Checks: ${lc(shellQuestion(text))}` };
410
+ if (!tool0) return { kind: 'call', says: `Runs \`${short(text)}\`` };
411
+ const tool = tool0.replace(/^.*\//, '');
412
+ const said = (s) => ({ kind: 'call', says: s });
413
+ const echoText = () => args.filter((a) => !/^-[neE]+$/.test(a)).join(' ');
414
+ if (tool === 'echo' || tool === 'printf') {
415
+ const t = echoText();
416
+ if (tail === 'output') { const k = /^([\w-]+)=/.exec(t); return said(k ? `Saves ${k[1]} for later steps` : 'Saves a value for later steps'); }
417
+ if (tail === 'env') { const k = /^([\w-]+)=/.exec(t); return said(k ? `Sets ${k[1]} for later steps` : 'Sets a value for later steps'); }
418
+ if (tail === 'path') return said(`Adds ${t} to the programs later steps can run`);
419
+ if (tail === 'summary') return said("Adds a line to the run's summary");
420
+ let w;
421
+ if ((w = /^::(notice|warning|error)(?:\s[^:]*)?::(.*)$/.exec(t))) return said(`Writes ${w[1] === 'notice' ? 'a note' : w[1] === 'warning' ? 'a warning' : 'an error'} in the log: "${w[2]}"`);
422
+ if (/^::add-mask::/.test(t)) return said('Hides a value in the log');
423
+ if (/^::(end)?group::/.test(t)) return said(t.startsWith('::group') ? 'Starts a group of log lines' : 'Ends a group of log lines');
424
+ if (tail.startsWith('file:')) return said(`Writes "${short(t, 60)}" to ${tail.slice(5)}`);
425
+ return said(`Writes a log line: "${short(t, 70)}"`);
426
+ }
427
+ const fileTail = tail.startsWith('file:') ? ` and writes the output to ${tail.slice(5)}` : '';
428
+ const out = (s) => (s ? said(`${s}${fileTail}`) : null);
429
+ const sub = args[0];
430
+ const r = (() => {
431
+ switch (tool) {
432
+ case 'npm': case 'yarn': case 'pnpm': case 'bun': return npmLike(tool, args);
433
+ case 'npx': case 'bunx': { const rest = args.filter((a) => a !== '--yes' && a !== '-y' && !a.startsWith('--package')); const name = (rest[0] ?? '').replace(/^(@[^/]+\/)?([^@]+).*$/, '$2'); const known = JS_TOOLS[name]?.(rest.slice(1)); return known ?? (name ? `Runs ${name}` : null); }
434
+ case 'node': {
435
+ if (args[0] === '-p' || args[0] === '-e' || args[0] === '--eval' || args[0] === '--print') {
436
+ const code = args[1] ?? '';
437
+ const v = /require\(['"]\.?\/?([\w./-]*package\.json)['"]\)\.(\w+)/.exec(code);
438
+ return v ? `Reads the ${v[2]} from ${v[1].replace(/^\.\//, '')}` : 'Runs a small Node script';
439
+ }
440
+ return args[0] ? `Runs ${scriptName(args.find((a) => !a.startsWith('-')) ?? args[0])}` : null;
441
+ }
442
+ case 'pip': case 'pip3': return pipWords(args);
443
+ case 'python': case 'python3': case 'py': {
444
+ if (args[0] === '-m') { const mod = args[1]; if (mod === 'pip') return pipWords(args.slice(2)); if (mod === 'pytest' || mod === 'unittest') return 'Runs the tests'; if (mod === 'build') return 'Builds the package'; if (mod === 'venv') return 'Makes a separate place for its Python packages'; return `Runs the Python module ${mod}`; }
445
+ if (args[0] === '-c') return 'Runs a small Python script';
446
+ return args[0] ? `Runs ${scriptName(args[0])}` : null;
447
+ }
448
+ case 'pytest': case 'rspec': case 'phpunit': case 'jest': case 'vitest': case 'mocha': return 'Runs the tests';
449
+ case 'tox': case 'nox': return `Runs the tests in several environments (${tool})`;
450
+ case 'twine': return sub === 'upload' ? 'Publishes the package to PyPI' : null;
451
+ case 'poetry': case 'uv': case 'pipenv': case 'pdm': case 'hatch':
452
+ if (sub === 'install' || sub === 'sync') return `Installs what it needs (${tool} ${sub})`;
453
+ if (sub === 'pip') return pipWords(args.slice(2));
454
+ if (sub === 'build') return 'Builds the package';
455
+ if (sub === 'publish') return 'Publishes the package to PyPI';
456
+ if (sub === 'run') return commandSays(args.slice(1).join(' ')).says;
457
+ return null;
458
+ case 'apt-get': case 'apt': case 'yum': case 'dnf': case 'microdnf': case 'zypper': case 'brew': case 'choco': case 'winget': {
459
+ const at = args.findIndex((a) => !a.startsWith('-'));
460
+ const sub = args[at];
461
+ args = args.slice(at);
462
+ if (sub === 'install') return installs(pkgList(args.slice(1)), `${tool} install`);
463
+ if (sub === 'update' && tool !== 'brew') return 'Updates the list of packages it can install';
464
+ if (sub === 'upgrade' || (sub === 'update' && tool === 'brew')) return 'Updates the installed packages';
465
+ if (sub === 'clean' || sub === 'autoremove') return 'Cleans up after installing';
466
+ if (sub === 'remove' || sub === 'purge') return `Removes ${listWords(pkgList(args.slice(1)))}`;
467
+ return null;
468
+ }
469
+ case 'apk':
470
+ if (sub === 'add') return installs(pkgList(args.slice(1)), 'apk add');
471
+ if (sub === 'update') return 'Updates the list of packages it can install';
472
+ if (sub === 'del') return `Removes ${listWords(pkgList(args.slice(1)))}`;
473
+ return null;
474
+ case 'go':
475
+ return { build: 'Builds it', test: 'Runs the tests', vet: 'Checks the code (go vet)', generate: 'Makes generated code (go generate)' }[sub]
476
+ ?? (sub === 'mod' && args[1] === 'download' ? 'Downloads what it needs' : sub === 'mod' && args[1] === 'tidy' ? 'Tidies the list of what it needs' : sub === 'run' ? `Runs ${args[1] ?? 'the program'}` : sub === 'install' ? `Installs ${args[1] ?? 'the program'}` : null);
477
+ case 'cargo':
478
+ return { build: 'Builds it', test: 'Runs the tests', clippy: 'Checks the code (cargo clippy)', publish: 'Publishes the package to crates.io', run: 'Runs the program', check: 'Checks that it compiles' }[sub] ?? (sub === 'fmt' ? (args.includes('--check') ? 'Checks the formatting' : 'Formats the code') : sub === 'install' ? `Installs ${args[1] ?? 'a program'}` : null);
479
+ case 'dotnet':
480
+ if (sub === 'nuget' && args[1] === 'push') return 'Publishes the package to NuGet';
481
+ return { restore: 'Installs what it needs (dotnet restore)', build: 'Builds it', test: 'Runs the tests', publish: 'Packages it for release (dotnet publish)', pack: 'Packages it (dotnet pack)', run: 'Runs the program', format: 'Checks the formatting (dotnet format)' }[sub] ?? null;
482
+ case 'mvn': case 'mvnw': case 'gradle': case 'gradlew': {
483
+ const goals = args.filter((a) => !a.startsWith('-'));
484
+ if (goals.includes('deploy') || goals.includes('publish')) return `Publishes it (${tool} ${goals.join(' ')})`;
485
+ if (goals.some((g) => /^(test|check|verify)$/.test(g))) return goals.some((g) => /^(package|build|install|assemble)$/.test(g)) ? 'Builds it and runs the tests' : 'Runs the tests';
486
+ if (goals.some((g) => /^(package|build|install|assemble|compile|bootJar|jar)$/.test(g))) return 'Builds it';
487
+ return goals.length ? `Runs ${tool} ${goals.join(' ')}` : null;
488
+ }
489
+ case 'make': { const target = args.find((a) => !a.startsWith('-') && !a.includes('=')); return target ? (target === 'test' || target === 'check' ? 'Runs the tests (make test)' : target === 'build' || target === 'all' ? `Builds it (make ${target})` : `Runs the make target ${target}`) : 'Runs make'; }
490
+ case 'bundle': if (sub === 'install') return 'Installs what it needs (bundle install)'; if (sub === 'exec') return commandSays(args.slice(1).join(' ')).says; return null;
491
+ case 'rake': return sub === 'test' || sub === 'spec' || !sub ? 'Runs the tests' : `Runs the rake task ${sub}`;
492
+ case 'composer': return sub === 'install' ? 'Installs what it needs (composer install)' : null;
493
+ case 'docker': case 'podman': return dockerWords(args);
494
+ case 'docker-compose': return composeWords(args);
495
+ case 'az': return azWords(args);
496
+ case 'aws': return awsWords(args);
497
+ case 'gcloud': return sub === 'auth' ? 'Signs in to Google Cloud' : sub === 'run' && args[1] === 'deploy' ? `Deploys ${args[2] ?? 'the service'} to Cloud Run` : `Runs the Google Cloud command gcloud ${args.slice(0, 2).join(' ')}`;
498
+ case 'kubectl': return kubectlWords(args);
499
+ case 'helm': return helmWords(args);
500
+ case 'terraform': case 'tofu':
501
+ return { init: 'Gets Terraform ready (terraform init)', plan: 'Works out what Terraform would change', apply: 'Applies the Terraform changes', destroy: 'Removes everything Terraform made', validate: 'Checks the Terraform files', fmt: 'Checks the Terraform formatting' }[sub] ?? null;
502
+ case 'git': return gitWords(args);
503
+ case 'gh': return sub === 'release' && args[1] === 'create' ? 'Makes a GitHub release' : sub === 'pr' && args[1] === 'create' ? 'Opens a pull request' : `Runs the GitHub command gh ${args.slice(0, 2).join(' ')}`;
504
+ case 'curl': case 'wget': { const url = args.find((a) => /^https?:\/\//i.test(a)); const sends = args.some((a, i) => (a === '-X' && /^(POST|PUT|PATCH|DELETE)$/i.test(args[i + 1] ?? '')) || a === '-d' || a === '--data' || a.startsWith('--data')); return url ? `${sends ? 'Sends a request to' : 'Downloads from'} ${hostOf(url)}` : 'Downloads a file'; }
505
+ case 'cat': if (tail === 'summary') return "Adds text to the run's summary"; if (tail === 'output' || tail === 'env') return 'Saves values for later steps'; return args.length ? `Shows ${listWords(args.filter((a) => !a.startsWith('-')))}` : null;
506
+ case 'mkdir': return `Makes the folder ${listWords(pkgList(args))}`;
507
+ case 'cd': case 'pushd': return `Goes into the folder ${args[0] ?? 'home'}`;
508
+ case 'popd': return 'Goes back to the folder it was in';
509
+ case 'cp': { const p = pkgList(args); return p.length >= 2 ? `Copies ${listWords(p.slice(0, -1))} to ${p.at(-1)}` : null; }
510
+ case 'mv': { const p = pkgList(args); return p.length >= 2 ? `Moves ${listWords(p.slice(0, -1))} to ${p.at(-1)}` : null; }
511
+ case 'rm': { const p = pkgList(args); if (p.length && p.every((x) => x.startsWith('/var/lib/apt/lists') || x.startsWith('/var/cache'))) return 'Cleans up after installing'; return p.length ? `Removes ${listWords(p)}` : null; }
512
+ case 'chmod': { const p = pkgList(args.slice(1)); return /\+x/.test(args[0] ?? '') ? `Lets ${listWords(p)} run as a program` : `Changes who can use ${listWords(p)}`; }
513
+ case 'chown': return `Changes who owns ${listWords(pkgList(args.slice(1)))}`;
514
+ case 'touch': return `Makes the file ${listWords(pkgList(args))}`;
515
+ case 'ln': return `Links ${pkgList(args).join(' to ')}`;
516
+ case 'tar': return /x/.test(args[0] ?? '') ? 'Unpacks an archive' : 'Packs files into an archive';
517
+ case 'unzip': return `Unpacks ${args.find((a) => !a.startsWith('-')) ?? 'an archive'}`;
518
+ case 'ls': return 'Lists the files';
519
+ case 'sleep': return `Waits ${sub ?? 'a moment'} second${sub === '1' ? '' : 's'}`;
520
+ case 'set': return args.some((a) => /^-\w*e/.test(a)) ? 'Stops at the first command that fails' : args.some((a) => /^-\w*x/.test(a)) ? 'Shows each command as it runs' : null;
521
+ case 'true': case ':': return 'Does nothing';
522
+ case 'false': return null;
523
+ case 'continue': return 'Skips to the next one';
524
+ case 'break': return 'Stops repeating';
525
+ case 'bash': case 'sh': case 'zsh': case 'pwsh': case 'powershell': {
526
+ if (args[0] === '-c' || args[0] === '-Command') return args[1] ? commandSays(args[1]).says : null;
527
+ const script = args.find((a) => !a.startsWith('-'));
528
+ return script ? `Runs ${scriptName(script)}` : null;
529
+ }
530
+ case 'source': case '.': return `Loads settings from ${sub}`;
531
+ case 'useradd': case 'adduser': return `Makes the user ${args.filter((a) => !a.startsWith('-')).at(-1)}`;
532
+ case 'groupadd': case 'addgroup': return `Makes the group ${args.filter((a) => !a.startsWith('-')).at(-1)}`;
533
+ case 'export': return args.length ? `Sets ${listWords(args.map((a) => a.split('=')[0]))}` : null;
534
+ default: return null;
535
+ }
536
+ })();
537
+ if (tool === 'exit') {
538
+ const code = Number(sub ?? 0);
539
+ return code ? { kind: 'fail', says: `Fails: the step stops with exit code ${code}`, error: `exit code ${code}` } : { kind: 'return', says: 'Finishes here, successfully' };
540
+ }
541
+ if (r) return out(r);
542
+ // A script in the repository: ./scripts/deploy.sh -> "Runs scripts/deploy.sh".
543
+ if (/^\.{0,2}\//.test(tool0) || /\.(sh|ps1|py|js|mjs|rb|bash)$/.test(tool0)) return out(`Runs ${scriptName(tool0)}`);
544
+ return said(`Runs \`${short(text)}\``);
545
+ }
546
+
547
+ function pipWords(args) {
548
+ const sub = args[0];
549
+ if (sub !== 'install') return sub ? `Runs pip ${sub}` : null;
550
+ const rest = args.slice(1);
551
+ const req = rest.indexOf('-r') >= 0 ? rest[rest.indexOf('-r') + 1] : rest.find((a) => a.startsWith('--requirement='))?.split('=')[1];
552
+ if (req) return `Installs what ${req} lists`;
553
+ const pkgs = pkgList(rest);
554
+ if (rest.includes('-e') || pkgs.includes('.')) return 'Installs this project';
555
+ if (rest.includes('--upgrade') && pkgs.length === 1 && pkgs[0] === 'pip') return 'Updates pip';
556
+ return installs(pkgs, 'pip install');
557
+ }
558
+ function dockerWords(args) {
559
+ const sub = args[0] === 'buildx' || args[0] === 'image' ? args[1] : args[0];
560
+ const rest = args[0] === 'buildx' || args[0] === 'image' ? args.slice(2) : args.slice(1);
561
+ const tagAt = rest.findIndex((a) => a === '-t' || a === '--tag');
562
+ const tag = tagAt >= 0 ? rest[tagAt + 1] : rest.find((a) => a.startsWith('--tag='))?.slice(6);
563
+ if (sub === 'build') return `Builds the image${tag ? ` ${tag}` : ''}${rest.includes('--push') ? ' and pushes it to its registry' : ''}`;
564
+ if (sub === 'push') return `Pushes the image ${firstArg(rest) ?? ''} to its registry`.replace(' ', ' ');
565
+ if (sub === 'pull') return `Downloads the image ${firstArg(rest)}`;
566
+ if (sub === 'run') return `Runs the image ${rest.filter((a, i) => !a.startsWith('-') && !(rest[i - 1] ?? '').match(/^-(e|p|v|w|-name|-env|-network|-volume|-publish)$/))[0] ?? ''}`.trim();
567
+ if (sub === 'login') return 'Signs in to the image registry';
568
+ if (sub === 'tag') return `Also names the image ${rest[0]} as ${rest[1]}`;
569
+ if (sub === 'compose') return composeWords(args.slice(1));
570
+ return sub ? `Runs docker ${sub}` : null;
571
+ }
572
+ function composeWords(args) {
573
+ const sub = args.find((a) => !a.startsWith('-'));
574
+ return sub === 'up' ? 'Starts the services (docker compose up)' : sub === 'down' ? 'Stops the services (docker compose down)' : sub === 'build' ? 'Builds the services\' images' : sub ? `Runs docker compose ${sub}` : null;
575
+ }
576
+ function azWords(args) {
577
+ const [a, b, c] = args;
578
+ if (a === 'login') return 'Signs in to Azure';
579
+ if (a === 'account' && b === 'set') return 'Chooses the Azure subscription';
580
+ if (a === 'group' && b === 'create') return 'Makes an Azure resource group';
581
+ if (a === 'deployment') return 'Deploys an Azure template';
582
+ if ((a === 'webapp' || a === 'functionapp') && (b === 'deploy' || b === 'up' || (b === 'deployment' && c))) return 'Deploys the app to Azure';
583
+ if (a === 'acr' && b === 'login') return 'Signs in to the Azure image registry';
584
+ if (a === 'acr' && b === 'build') return 'Builds the image in Azure';
585
+ if (a === 'aks' && b === 'get-credentials') return 'Gets the sign-in for the Kubernetes cluster in Azure';
586
+ return `Runs the Azure command az ${args.filter((x) => !x.startsWith('-')).slice(0, 3).join(' ')}`;
587
+ }
588
+ function awsWords(args) {
589
+ const [a, b] = args;
590
+ if (a === 'configure') return 'Sets up the AWS sign-in';
591
+ if (a === 's3' && (b === 'cp' || b === 'sync')) return 'Copies files to or from Amazon S3';
592
+ if (a === 'ecr' && b === 'get-login-password') return 'Gets a sign-in for the Amazon image registry';
593
+ if (a === 'ecs' && b === 'update-service') return 'Updates the Amazon ECS service';
594
+ if (a === 'cloudformation' && b === 'deploy') return 'Deploys an AWS CloudFormation stack';
595
+ if (a === 'lambda' && b === 'update-function-code') return 'Updates the AWS Lambda function';
596
+ return `Runs the AWS command aws ${args.filter((x) => !x.startsWith('-')).slice(0, 2).join(' ')}`;
597
+ }
598
+ function kubectlWords(args) {
599
+ const [a, ...rest] = args;
600
+ const f = rest.indexOf('-f') >= 0 ? rest[rest.indexOf('-f') + 1] : null;
601
+ if (a === 'apply') return `Applies ${f ?? 'the files'} to the Kubernetes cluster`;
602
+ if (a === 'rollout' && rest[0] === 'status') return 'Waits for the rollout to finish';
603
+ if (a === 'rollout' && rest[0] === 'restart') return 'Restarts what runs in the cluster';
604
+ if (a === 'set' && rest[0] === 'image') return 'Changes the image the cluster runs';
605
+ if (a === 'delete') return `Removes ${f ?? listWords(pkgList(rest))} from the cluster`;
606
+ if (a === 'create') return `Makes ${listWords(pkgList(rest).slice(0, 2))} in the cluster`;
607
+ if (a === 'get' || a === 'describe') return `Shows ${listWords(pkgList(rest).slice(0, 2))} in the cluster`;
608
+ return `Runs kubectl ${a ?? ''}`.trim();
609
+ }
610
+ function helmWords(args) {
611
+ const [a, ...rest] = args;
612
+ const p = pkgList(rest);
613
+ if (a === 'upgrade' && rest.includes('--install')) return `Installs or upgrades the Helm release ${p[0]}`;
614
+ if (a === 'upgrade') return `Upgrades the Helm release ${p[0]}`;
615
+ if (a === 'install') return `Installs the Helm release ${p[0]}`;
616
+ if (a === 'repo' && rest[0] === 'add') return `Adds the Helm chart source ${rest[1]}`;
617
+ if (a === 'lint') return 'Checks the Helm chart';
618
+ if (a === 'template') return 'Writes out the Kubernetes files from the chart';
619
+ if (a === 'uninstall') return `Removes the Helm release ${p[0]}`;
620
+ return `Runs helm ${a ?? ''}`.trim();
621
+ }
622
+ function gitWords(args) {
623
+ const [a, ...rest] = args;
624
+ return { clone: `Downloads the repository ${pkgList(rest)[0] ?? ''}`.trim(), config: 'Sets a git setting', commit: 'Records a commit', push: 'Pushes commits to the repository', tag: 'Tags the commit', add: 'Adds files to the next commit', fetch: 'Fetches the latest changes', pull: 'Pulls the latest changes', diff: 'Shows what changed', status: 'Shows what changed' }[a]
625
+ ?? (a === 'checkout' || a === 'switch' ? `Switches to ${pkgList(rest)[0] ?? 'a branch'}` : a ? `Runs git ${a}` : null);
626
+ }
627
+
628
+ /** Where a shell text leaves off: an open quote and how many `$(` are still open. Comments end the scan. */
629
+ function lineState(text, st = { q: null, d: 0 }) {
630
+ let { q, d } = st;
631
+ for (let i = 0; i < text.length; i++) {
632
+ const c = text[i];
633
+ if (q) { if (c === '\\' && q !== "'") { i++; continue; } if (c === q) q = null; continue; }
634
+ if (c === '\\') { i++; continue; }
635
+ if (c === '#' && (i === 0 || /\s/.test(text[i - 1]))) break;
636
+ if (c === "'" || c === '"' || c === '`') q = c;
637
+ else if (c === '$' && text[i + 1] === '(') { d++; i++; }
638
+ else if (c === ')' && d) d--;
639
+ }
640
+ return { q, d };
641
+ }
642
+ const isOpen = (st) => !!st && (st.q || st.d > 0);
643
+
644
+ /**
645
+ * Join backslash-continued lines and quotes that span lines (an awk or python -c script); skip heredoc bodies
646
+ * (`cat <<EOF … EOF` is one command whose body is text). Returns [{ text, line }], skipping comments and blanks.
647
+ */
648
+ export function logicalLines(text, firstLine) {
649
+ const out = [];
650
+ const lines = String(text).split('\n');
651
+ let cur = null;
652
+ let quote = null;
653
+ for (let i = 0; i < lines.length; i++) {
654
+ const raw = lines[i];
655
+ const t = raw.trim();
656
+ if (cur == null && (!t || t.startsWith('#'))) continue;
657
+ if (cur != null && !isOpen(quote) && t.startsWith('#')) continue;
658
+ if (cur == null) cur = { text: '', line: firstLine + i };
659
+ if (isOpen(quote)) { cur.text = /\\$/.test(cur.text) ? `${cur.text.slice(0, -1).trimEnd()} ${t}` : `${cur.text}\n${raw}`; quote = lineState(raw, quote); if (isOpen(quote)) continue; }
660
+ else {
661
+ quote = lineState(t);
662
+ if (isOpen(quote)) { cur.text += t; continue; }
663
+ if (t.endsWith('\\') && !t.endsWith('\\\\')) { cur.text += `${t.slice(0, -1).trim()} `; continue; }
664
+ cur.text += t;
665
+ }
666
+ const doc = /<<-?\s*["']?([A-Za-z_]\w*)["']?/.exec(cur.text.replace(/'[^']*'|"[^"]*"/g, (m) => (/<</.test(m) ? '' : m)));
667
+ if (doc) {
668
+ // The heredoc body is text the command is given, not commands.
669
+ while (i + 1 < lines.length && lines[i + 1].trim() !== doc[1]) i++;
670
+ i++;
671
+ cur.heredoc = true;
672
+ }
673
+ out.push({ text: cur.text.trim(), line: cur.line, ...(cur.heredoc ? { heredoc: true } : {}) });
674
+ cur = null;
675
+ }
676
+ if (cur) out.push({ text: cur.text.trim(), line: cur.line });
677
+ return out;
678
+ }
679
+
680
+ /** A shell test (`[ "$A" = "$B" ]`) or command used as a condition, as a question. */
681
+ function shellQuestion(cond) {
682
+ let c = cond.trim();
683
+ let negate = false;
684
+ if (c.startsWith('! ')) { negate = true; c = c.slice(2).trim(); }
685
+ let m;
686
+ if ((m = /^\[\[?\s+(.*?)\s+\]\]?$/.exec(c)) || (m = /^test\s+(.*)$/.exec(c))) {
687
+ const w = shellWords(m[1]).map((x) => x.replace(/^\$\{?(\w+)\}?$/, '$1'));
688
+ const not = (b) => (b !== negate ? 'not ' : '');
689
+ if (w.length === 3 && ['=', '==', '!='].includes(w[1])) return `Is ${w[0] || 'empty'} ${not(w[1] === '!=')}${w[2] || 'empty'}?`;
690
+ if (w.length === 3 && ['-eq', '-ne', '-lt', '-gt', '-le', '-ge'].includes(w[1])) return `Is ${w[0]} ${negate ? 'not ' : ''}${{ '-eq': '', '-ne': 'not ', '-lt': 'less than ', '-gt': 'more than ', '-le': 'at most ', '-ge': 'at least ' }[w[1]]}${w[2]}?`;
691
+ if (w.length === 2 && w[0] === '-z') return `Is ${w[1]} ${negate ? 'set' : 'empty'}?`;
692
+ if (w.length === 2 && w[0] === '-n') return `Is ${w[1]} ${negate ? 'empty' : 'set'}?`;
693
+ if (w.length === 2 && (w[0] === '-f' || w[0] === '-e')) return `Does the file ${w[1]} ${negate ? 'not ' : ''}exist?`;
694
+ if (w.length === 2 && w[0] === '-d') return `Does the folder ${w[1]} ${negate ? 'not ' : ''}exist?`;
695
+ }
696
+ if (/^(\[\[?|test)(\s|$)/.test(c)) return `Is \`${short(c, 60)}\` true?`;
697
+ const said = commandSays(c).says;
698
+ return `${negate ? 'Does this fail' : 'Does this work'}: ${lc(said)}?`;
699
+ }
700
+
701
+ /**
702
+ * The steps of a shell script (a `run:` block or a Dockerfile RUN): one step per command, `&&` chains split, `if`
703
+ * and `for` read as a question and a repeat. `line` of each step is the line the command starts on.
704
+ */
705
+ export function shellSteps(text, firstLine) {
706
+ const stmts = [];
707
+ const lls = logicalLines(text, firstLine);
708
+ for (let n = 0; n < lls.length; n++) {
709
+ const l = lls[n];
710
+ // A shell function (`name() { … }`) runs only when it is called: one step, its body skipped to the closing brace.
711
+ if (/^(function\s+)?[\w-]+\s*\(\)\s*\{?$/.test(l.text) || /^function\s+[\w-]+\s*\{?$/.test(l.text)) {
712
+ let depth = l.text.endsWith('{') ? 1 : 0;
713
+ while (n + 1 < lls.length) { const t = lls[++n].text; if (t === '{' || /\{$/.test(t)) depth++; if (t === '}' || /^\}/.test(t)) depth--; if (depth <= 0 && /^\}/.test(t)) break; }
714
+ stmts.push({ text: l.text, line: l.line, fn: true });
715
+ continue;
716
+ }
717
+ const parts = l.heredoc ? [{ text: l.text, op: null }] : splitCommands(l.text);
718
+ for (let k = 0; k < parts.length; k++) {
719
+ let p = parts[k].text;
720
+ let kw;
721
+ // `then echo x`, `do echo x`, `else echo x`: the keyword and the command after it.
722
+ while ((kw = /^(then|do|else)\s+(.+)$/.exec(p))) { stmts.push({ text: kw[1], line: l.line }); p = kw[2]; }
723
+ // `{` / `}` group commands and `( … )` runs them apart: the commands inside are what matter.
724
+ let open = false, close = false;
725
+ if (/^[{(](\s+|$)/.test(p)) { open = true; p = p.slice(1).trim(); }
726
+ if (/^\}\s*(>|$)/.test(p)) { close = true; p = ''; }
727
+ if (/(^|\s)\}$/.test(p) && !p.includes('{')) { close = true; p = p.slice(0, -1).trim(); }
728
+ if (/(^|\s)\)$/.test(p) && !p.includes('(')) { close = true; p = p.slice(0, -1).trim(); }
729
+ if (open) stmts.push({ text: '{', line: l.line });
730
+ if (p && !/^>>?\s*\S+$/.test(p)) stmts.push({ text: p, line: l.line, op: parts[k].op, next: parts[k + 1]?.text, ...(l.heredoc ? { heredoc: true } : {}) });
731
+ if (close) stmts.push({ text: '}', line: l.line });
732
+ }
733
+ }
734
+ // Skip heredoc bodies: a command with `<<WORD` swallows lines up to WORD.
735
+ let i = 0;
736
+ const block = (stops) => {
737
+ const out = [];
738
+ while (i < stmts.length) {
739
+ const s = stmts[i];
740
+ const head = s.text.split(/\s+/)[0];
741
+ if (stops.includes(head)) return out;
742
+ i++;
743
+ if (s.fn) { out.push({ kind: 'call', says: `Defines the command ${/^(?:function\s+)?([\w-]+)/.exec(s.text)[1]}, for later lines to use`, code: s.text, line: s.line }); continue; }
744
+ if (head === 'case') {
745
+ const what = /^case\s+(.+?)\s+in\b/.exec(s.text)?.[1] ?? 'a value';
746
+ while (i < stmts.length && stmts[i].text !== 'esac' && !/^esac\b/.test(stmts[i].text)) i++;
747
+ i++;
748
+ out.push({ kind: 'call', says: `Chooses what to do by ${shellWords(what)[0]?.replace(/^\$\{?(\w+)\}?$/, '$1') ?? what}`, code: s.text, line: s.line, unknownCommand: true });
749
+ continue;
750
+ }
751
+ if ((head === '[' || head === '[[' || head === 'test') && (s.op === '&&' || s.op === '||') && s.next && !/^\{/.test(s.next)) {
752
+ // `[ -f x ] && cmd`: a question with the command on its Yes side (or its No side for ||).
753
+ const q = shellQuestion(s.op === '||' ? `! ${s.text}` : s.text);
754
+ i++;
755
+ const r = commandSays(s.next);
756
+ out.push({ kind: 'branch', says: q, code: `${s.text} ${s.op} ${s.next}`, line: s.line, children: [{ kind: r.kind, says: r.says, code: s.next, line: s.line, ...(r.kind === 'fail' ? { error: 'The job fails' } : {}), ...(/^Runs `/.test(r.says) ? { unknownCommand: true } : {}) }] });
757
+ continue;
758
+ }
759
+ if (head === 'if' || head === 'elif') {
760
+ const q = shellQuestion(s.text.replace(/^(if|elif)\s+/, ''));
761
+ if (stmts[i]?.text === 'then') i++;
762
+ const step = { kind: 'branch', says: q, code: s.text, line: s.line, children: block(['elif', 'else', 'fi']) };
763
+ if (stmts[i]?.text.startsWith('elif')) step.otherwise = block(['fi']);
764
+ else if (stmts[i]?.text === 'else') { i++; step.otherwise = block(['fi']); }
765
+ if (stmts[i]?.text === 'fi') i++;
766
+ out.push(step);
767
+ continue;
768
+ }
769
+ if (head === 'for' || head === 'while' || head === 'until') {
770
+ const m = /^for\s+(\w+)\s+in\s+(.*)$/.exec(s.text);
771
+ if (stmts[i]?.text === 'do') i++;
772
+ const loopCond = s.text.replace(/^(while|until)\s+/, '').replace(/;\s*do\s*$/, '').trim();
773
+ // "Is n at least 3?" -> "n is at least 3"; "Does the file x exist?" -> "the file x exists".
774
+ const q = shellQuestion(loopCond);
775
+ const asWords = /^Is (\S+) (.+)\?$/.test(q) ? q.replace(/^Is (\S+) (.+)\?$/, '$1 is $2') : /^Does (.+) (not )?exist\?$/.test(q) ? q.replace(/^Does (.+?) (not )?exist\?$/, (x, a, n) => `${a} ${n ? 'does not exist' : 'exists'}`) : q;
776
+ const readable = !/`/.test(asWords) ? asWords.replace(/\?$/, '') : loopCond;
777
+ out.push({ kind: 'loop', says: m ? `For each ${m[1]} in ${m[2]}` : `Repeats ${head === 'until' ? 'until' : 'while'} ${readable}`, code: s.text, line: s.line, children: block(['done']) });
778
+ if (stmts[i]?.text === 'done') i++;
779
+ continue;
780
+ }
781
+ if (['then', 'do', 'fi', 'done', 'else', 'esac', '{', '}'].includes(s.text)) continue;
782
+ // `cmd || { …; exit 1; }` and `cmd && { … }`: a question whose one side is the group.
783
+ if ((s.op === '||' || s.op === '&&') && /^\{/.test(s.next ?? '') && stmts[i]?.text === '{') {
784
+ const r0 = commandSays(s.text);
785
+ i++;
786
+ const inside = block(['}']);
787
+ if (stmts[i]?.text === '}') i++;
788
+ out.push({ kind: 'branch', says: `${s.op === '||' ? 'Does this fail' : 'Does this work'}: ${lc(r0.says)}?`, code: s.text, line: s.line, children: inside, ...(r0.kind === 'set' ? {} : {}) });
789
+ continue;
790
+ }
791
+ const r = commandSays(s.text);
792
+ const step = { kind: r.kind, says: r.says, code: s.text, line: s.line, ...(r.kind === 'call' && /^Runs `/.test(r.says) ? { unknownCommand: true } : {}) };
793
+ if (s.op === '||' && s.next) {
794
+ // `a || true`: a failure is ignored; `a || exit 1`: a failure stops; otherwise the other command runs instead.
795
+ const alt = commandSays(s.next);
796
+ i++;
797
+ if (/^(true|:)$/.test(s.next.trim())) step.says += ' (a failure here is ignored)';
798
+ else if (alt.kind === 'fail') { out.push({ kind: 'branch', says: `Does this fail: ${lc(step.says)}?`, code: `${s.text} || ${s.next}`, line: s.line, children: [{ kind: 'fail', says: alt.says, code: s.next, line: s.line, error: 'The job fails' }] }); continue; }
799
+ else step.says += `; if that fails, ${lc(alt.says)}`;
800
+ } else if (s.op === '|' && s.next) {
801
+ const alt = commandSays(s.next);
802
+ i++;
803
+ step.says += `, then ${lc(alt.says)}`;
804
+ }
805
+ if (r.kind === 'fail') step.error = 'The job fails';
806
+ out.push(step);
807
+ }
808
+ return out;
809
+ };
810
+ return block([]);
811
+ }