@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
package/src/hcl.mjs ADDED
@@ -0,0 +1,94 @@
1
+ // A small HCL reader (Terraform's language), no library: a file is a body of attributes (`name = value`) and blocks
2
+ // (`resource "type" "name" { … }`), each with its lines and the comment written just above it. Values are parsed by
3
+ // infra-expr.mjs. A block Thunder cannot parse is kept as an error with its line and skipped, never guessed.
4
+ import { tokenize, lineIndex, Parser, ParseError } from './infra-expr.mjs';
5
+
6
+ /** Comments that end right above `line`, joined (an author's note), or ''. */
7
+ export function docAbove(comments, line) {
8
+ const byEnd = new Map(comments.map((c) => [c.endLine, c]));
9
+ const out = [];
10
+ for (let l = line - 1; byEnd.has(l); l = byEnd.get(l).line - 1) out.unshift(byEnd.get(l).text);
11
+ return out.filter((t) => t && !/^(disable-|tflint-ignore|checkov:|tfsec:|trivy:)/.test(t)).join(' ').trim();
12
+ }
13
+
14
+ /**
15
+ * Parse HCL source. Returns { body, comments, errors }: body items are
16
+ * { kind: 'attr', name, value, line, endLine }
17
+ * { kind: 'block', type, labels, body, line, endLine, doc? }
18
+ * and errors are [{ line, why }] for top-level blocks that could not be parsed (they are skipped).
19
+ */
20
+ export function parseHcl(src) {
21
+ const text = String(src ?? '').replace(/^/, '');
22
+ const lineAt = lineIndex(text);
23
+ const { toks, comments } = tokenize(text, 'hcl', 0, text.length, lineAt);
24
+ const p = new Parser(text, toks, 'hcl', lineAt);
25
+ const errors = [];
26
+ const body = [];
27
+ for (;;) {
28
+ p.newlines();
29
+ if (p.peek().k === 'eof') break;
30
+ const start = p.i;
31
+ try { body.push(item(p, comments)); }
32
+ catch (e) {
33
+ if (!(e instanceof ParseError)) throw e;
34
+ errors.push({ line: e.line, why: e.why });
35
+ p.i = resync(toks, start);
36
+ }
37
+ }
38
+ return { body, comments, errors, lineAt, src: text };
39
+ }
40
+
41
+ /** Past the end of the top-level item that starts at token `i` (its braces matched), for skipping one that failed. */
42
+ function resync(toks, i) {
43
+ let depth = 0, seen = false;
44
+ for (; i < toks.length; i++) {
45
+ const t = toks[i];
46
+ if (t.k === 'eof') return i;
47
+ if (t.k === 'p' && (t.v === '{' || t.v === '[' || t.v === '(')) { depth++; seen = true; }
48
+ else if (t.k === 'p' && (t.v === '}' || t.v === ']' || t.v === ')')) { depth--; if (depth <= 0 && seen) return i + 1; }
49
+ else if (t.k === 'nl' && depth <= 0 && !seen) return i + 1;
50
+ }
51
+ return i;
52
+ }
53
+
54
+ function body(p, comments) {
55
+ const out = [];
56
+ return p.withNl(false, () => {
57
+ for (;;) {
58
+ p.newlines();
59
+ const t = p.peek();
60
+ if (t.k === 'eof') throw new ParseError('A block is not closed', p.lineOf(t));
61
+ if (t.k === 'p' && t.v === '}') return out;
62
+ out.push(item(p, comments));
63
+ }
64
+ });
65
+ }
66
+
67
+ function item(p, comments) {
68
+ return p.withNl(false, () => {
69
+ const t = p.next();
70
+ if (t.k !== 'id') throw new ParseError(`Expected a name, found "${p.src.slice(t.s, t.e).slice(0, 20)}"`, p.lineOf(t));
71
+ const line = p.lineOf(t);
72
+ if (p.is('=') || p.is(':')) {
73
+ p.next();
74
+ const value = p.expr();
75
+ const end = p.peek();
76
+ if (!(end.k === 'nl' || end.k === 'eof' || (end.k === 'p' && end.v === '}'))) throw new ParseError(`Expected the end of the line after ${t.v} = …`, p.lineOf(end));
77
+ return { kind: 'attr', name: t.v, value, line, endLine: p.lineAt(Math.max(value.s, value.e - 1)) };
78
+ }
79
+ const labels = [];
80
+ while (p.peek().k === 'str' || p.peek().k === 'id') {
81
+ const l = p.next();
82
+ labels.push(l.k === 'str' ? p.string(l).v ?? p.src.slice(l.s + 1, l.e - 1) : l.v);
83
+ }
84
+ p.expect('{');
85
+ const inner = body(p, comments);
86
+ const close = p.expect('}');
87
+ const doc = docAbove(comments, line);
88
+ return { kind: 'block', type: t.v, labels, body: inner, line, endLine: p.lineOf(close), ...(doc ? { doc } : {}) };
89
+ });
90
+ }
91
+
92
+ /** Attributes of a body by name, and its blocks by type. */
93
+ export const attrOf = (bodyItems, name) => bodyItems?.find((x) => x.kind === 'attr' && x.name === name);
94
+ export const blocksOf = (bodyItems, type) => (bodyItems ?? []).filter((x) => x.kind === 'block' && x.type === type);
package/src/index.d.ts CHANGED
@@ -742,11 +742,17 @@ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES }
742
742
  export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText } from './visual.mjs';
743
743
  export { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
744
744
  export { sameMeaning, renderSame } from './same.mjs';
745
+ export { thunderReview, renderReview, REVIEW_SCHEMA } from './review.mjs';
746
+ export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from './meaning.mjs';
747
+ export type { Expr } from './meaning.mjs';
748
+ export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from './round-trip.mjs';
745
749
  export type { Reading, ReadItem, ReadKind } from './read.mjs';
746
- export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
750
+ export { readRepo, searchRepo, groupByFile, readableLanguage, readableFile, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
747
751
  export type { RepoItem, RepoFacet, RepoReading, RepoFilter } from './read-repo.mjs';
748
752
  export function collectReadableFiles(root: string, options?: { maxFiles?: number; maxFileBytes?: number }): Array<{ path: string; source: string; size?: number }>;
749
753
  export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
750
754
  export type { Promotion } from './promote.mjs';
751
755
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
752
756
  export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
757
+ export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from './write-steps.mjs';
758
+ export type { ThunderEdit, ThunderWriteResult, WriteProof } from './write-steps.mjs';
package/src/index.mjs CHANGED
@@ -193,8 +193,13 @@ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES }
193
193
  export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText } from "./visual.mjs";
194
194
  export { thunderizeFiles, THUNDER_TEXT_EXT } from "./thunderize.mjs";
195
195
  export { sameMeaning, renderSame } from "./same.mjs";
196
- export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from "./read-repo.mjs";
196
+ export { thunderReview, renderReview, REVIEW_SCHEMA } from "./review.mjs";
197
+ // Every step's meaning tree, and code → Thunder → code for steps.
198
+ export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from "./meaning.mjs";
199
+ export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from "./round-trip.mjs";
200
+ export { readRepo, searchRepo, groupByFile, readableLanguage, readableFile, READ_REPO_SCHEMA, READ_SKIP_DIRS } from "./read-repo.mjs";
197
201
  export { collectReadableFiles } from "./read-repo-fs.mjs";
198
202
  export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
199
203
  // Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
200
204
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
205
+ export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from "./write-steps.mjs";
@@ -0,0 +1,312 @@
1
+ // Bicep in Thunder (spec section 12): what a deployment makes in Azure, where, and who can do what. Each `resource`
2
+ // is a Resource (its type as written, 'Microsoft.Storage/storageAccounts', and its symbolic name as its address) that
3
+ // knows its properties in words; an `existing` resource is looked up, not made; a `module` is a group of its own;
4
+ // `param` (a `@secure()` one only named), `var`, and `output` are Settings. Symbolic references (`storage.id`),
5
+ // `parent`, and `dependsOn` are links with their lines; `for` and `if` read "for each …" and "only when …"; the order
6
+ // things are created is one Steps card. Role assignments are Permissions, with well-known role ids named (Owner,
7
+ // Storage Blob Data Reader, …) and called wide when they can change everything; the same Facts as Terraform.
8
+ // Deterministic, browser-safe; reads the file, not what is deployed.
9
+ import { parseBicep } from './bicep.mjs';
10
+ import { refsIn, isLiteral, entryOf } from './infra-expr.mjs';
11
+ import {
12
+ APPLIED, words, typeWords, resourceLabel, roleCan, roleIn, WIDE_ROLES, linkKind, valueText, conditionWords,
13
+ keyFacts, isSecretKey, literalEntries, fromAnywhere, portsOpen, topoOrder, addLink, question, leaves, normKey,
14
+ } from './infra-cloud.mjs';
15
+ import { listWords, cap } from './infra-words.mjs';
16
+
17
+ const SCOPES = { resourceGroup: 'a resource group', subscription: 'a subscription', managementGroup: 'a management group', tenant: 'the whole tenant' };
18
+ const FN_WORDS = { resourceGroup: "the resource group's", subscription: "the subscription's", deployment: "the deployment's", tenant: "the tenant's", managementGroup: "the management group's", environment: "the Azure cloud's", deployer: "whoever deploys it's" };
19
+
20
+ /** The object a resource or module is written as, and the `for` or `if` around it. */
21
+ function unwrap(v) {
22
+ let loop = null, cond = null, obj = v;
23
+ if (obj?.t === 'for') { loop = obj; obj = obj.value; }
24
+ if (obj?.t === 'if') { cond = obj.test; obj = obj.body; }
25
+ return { obj: obj?.t === 'obj' ? obj : null, loop, cond };
26
+ }
27
+
28
+ /** Read a Bicep file. Returns { items, things, settings, facts, links, permissions, unknowns, purpose }. */
29
+ export function readBicep(src, file = 'main.bicep') {
30
+ const parsed = parseBicep(src);
31
+ const { decls } = parsed;
32
+ const text = parsed.src;
33
+ const things = [], settings = [], facts = [], links = [], permissions = [];
34
+ const unknowns = parsed.errors.map((e) => ({ file, line: e.line, why: `Not read yet: ${e.why}.` }));
35
+ const factIds = new Set();
36
+ const fact = (kind, says, line) => { const id = `${file}#${kind}#${line}`; if (!factIds.has(id)) { factIds.add(id); facts.push({ id, kind, says, file, line }); } };
37
+ const scopeDecl = decls.find((d) => d.kind === 'targetScope');
38
+ const targetScope = scopeDecl?.value?.t === 'str' ? scopeDecl.value.v : 'resourceGroup';
39
+
40
+ // Every resource and module, nested resources included (`parent` is the one they sit in).
41
+ const declared = [];
42
+ const visit = (d, parent) => {
43
+ const { obj } = unwrap(d.value);
44
+ let type = d.type ?? 'module';
45
+ if (parent && d.kind === 'resource' && !type.includes('/') && !/^Microsoft\./i.test(type)) type = `${parent.type}/${type}`;
46
+ // Nested resources under different parents may share a name; the second is addressed by its parent (parent::child).
47
+ const address = declared.some((x) => x.address === d.name) && parent ? `${parent.address}::${d.name}` : d.name;
48
+ const entry = { d, kind: d.kind, type, name: d.name, address, parent: parent?.address ?? null, existing: !!d.existing };
49
+ declared.push(entry);
50
+ for (const e of obj?.entries ?? []) if (e.nested) visit(e.nested, entry);
51
+ };
52
+ for (const d of decls) if (d.kind === 'resource' || d.kind === 'module') visit(d, null);
53
+ const bySym = new Map(declared.map((x) => [x.address, x]));
54
+ const params = new Map(decls.filter((d) => d.kind === 'param').map((d) => [d.name, d]));
55
+ const vars = new Map(decls.filter((d) => d.kind === 'var').map((d) => [d.name, d]));
56
+ const loopVars = new Set();
57
+ const collectLoops = (n) => { if (!n || typeof n !== 'object') return; if (n.t === 'for' || n.t === 'lambda') for (const v of n.vars) loopVars.add(v); for (const k of Object.values(n)) if (k && typeof k === 'object') { if (Array.isArray(k)) k.forEach(collectLoops); else if (k.t) collectLoops(k); else if (k.value) collectLoops(k.value); } };
58
+ for (const d of decls) collectLoops(d.value);
59
+
60
+ /** A reference in words: location -> "the setting location"; storage.id -> "the id of the storage account storage". */
61
+ const refWords = (n) => {
62
+ if (n.t === 'get' && n.obj.t === 'call') { const f = n.obj.name.replace(/^az\./, ''); return FN_WORDS[f] ? `${FN_WORDS[f]} ${words(n.path.filter((x) => !x.startsWith('[')).join(' '))}`.replace("deploys it's", "deploys it: its") : null; }
63
+ if (n.t !== 'ref') return null;
64
+ const [root, ...rest] = n.path;
65
+ const attr = rest.filter((x) => x !== 'properties' && x !== '*' && !x.startsWith('[')).map(words).join(' ');
66
+ if (params.has(root)) return `the setting ${root}${attr ? `'s ${attr}` : ''}`;
67
+ if (vars.has(root)) return `the value ${root}${attr ? `'s ${attr}` : ''}`;
68
+ if (loopVars.has(root)) return attr ? `each item's ${attr}` : 'each item';
69
+ const child = rest[0] && bySym.get(rest[0])?.parent === root ? rest[0] : null;
70
+ if (child) return refWords({ t: 'ref', path: n.path.slice(1) });
71
+ const r = bySym.get(root);
72
+ if (r) {
73
+ if (r.kind === 'module') return rest[0] === 'outputs' && rest[1] ? `the ${words(rest[1])} from the module ${root}` : `the module ${root}`;
74
+ return `${attr ? `the ${attr} of ` : ''}the ${r.existing ? 'existing ' : ''}${typeWords(r.type)} ${root}`;
75
+ }
76
+ return null;
77
+ };
78
+ // What each var refers to, so a resource that uses a var is linked to what the var names.
79
+ const targetsOf = (node) => {
80
+ const out = [];
81
+ const seen = new Set();
82
+ const walk = (refs, depth) => {
83
+ for (const r of refs) {
84
+ const root = r.path[0];
85
+ if (vars.has(root) && depth < 3 && !seen.has(root)) { seen.add(root); walk(refsIn(vars.get(root).value), depth + 1); continue; }
86
+ if (bySym.has(root)) out.push({ to: bySym.get(r.path[1])?.parent === root ? r.path[1] : root, ref: r });
87
+ }
88
+ };
89
+ walk(refsIn(node), 0);
90
+ return out;
91
+ };
92
+
93
+ for (const x of declared) {
94
+ const { d, type, name, address } = x;
95
+ const { obj, loop, cond } = unwrap(d.value);
96
+ const where = x.kind === 'module' ? `The module ${name}` : `The ${typeWords(type)} ${name}`;
97
+ const knows = [];
98
+ const know = (k) => knows.push({ start: null, ...k });
99
+ if (x.existing) know({ name: 'existing', label: 'Looks up', kind: `an existing ${typeWords(type)}, made elsewhere (this file only reads it)`, line: d.line });
100
+ if (x.kind === 'module') know({ name: 'path', label: 'Uses the module', kind: d.path, line: d.line });
101
+ if (loop) know({ name: 'for', label: 'One for each', kind: `item in ${valueText(loop.coll, refWords).from?.[0] ?? (isLiteral(loop.coll) ? valueText(loop.coll, refWords).text : `a list ${APPLIED}`)}`, line: loop.line, computed: true });
102
+ if (cond) know({ name: 'if', label: 'Only when', kind: conditionWords(cond, refWords), line: cond.line, computed: true });
103
+ for (const e of obj?.entries ?? []) {
104
+ if (e.nested || e.spread) continue;
105
+ if (e.key === 'properties' && e.value.t === 'obj') {
106
+ for (const pe of e.value.entries) if (!pe.spread) know(entryKnow(pe, refWords));
107
+ continue;
108
+ }
109
+ if (x.kind === 'module' && e.key === 'params' && e.value.t === 'obj') { for (const pe of e.value.entries) if (!pe.spread) know(entryKnow(pe, refWords, 'Given ')); continue; }
110
+ if (e.key === 'dependsOn') {
111
+ const ts = targetsOf(e.value);
112
+ for (const t of ts) addLink(links, file, address, t.to, 'uses', e.line);
113
+ know({ name: 'dependsOn', label: 'Waits for', kind: listWords([...new Set(ts.map((t) => refWords({ t: 'ref', path: [t.to] }) ?? t.to))]) || valueText(e.value, refWords).text, line: e.line });
114
+ continue;
115
+ }
116
+ if (e.key === 'parent') { know({ name: 'parent', label: 'Inside', kind: refWords(e.value) ?? valueText(e.value, refWords).text, line: e.line }); continue; }
117
+ if (e.key === 'scope') { know({ name: 'scope', label: x.kind === 'module' ? 'Deploys into' : 'On', kind: scopeOf(e.value, refWords, targetScope).on, line: e.line }); continue; }
118
+ know(entryKnow(e, refWords));
119
+ }
120
+ if (d.apiVersion) know({ name: 'apiVersion', label: 'API version', kind: d.apiVersion, line: d.line });
121
+ if (x.parent) addLink(links, file, address, x.parent, 'runs-in', d.line);
122
+ // Links: every symbolic reference, under the key it sits in.
123
+ if (obj) for (const lf of leaves(obj, '', d.line)) {
124
+ if (lf.key === 'dependsOn') continue;
125
+ for (const t of targetsOf(lf.value)) addLink(links, file, address, t.to, lf.key === 'parent' ? 'runs-in' : linkKind(lf.key, { toLookup: bySym.get(t.to)?.existing, fromType: type }), lf.line);
126
+ }
127
+ for (const n of [loop?.coll, cond].filter(Boolean)) for (const t of targetsOf(n)) addLink(links, file, address, t.to, 'uses', n.line);
128
+ // Facts.
129
+ if (obj) {
130
+ for (const e of literalEntries(obj)) keyFacts(e.key, e.value, (kind, says) => fact(kind, says, e.line), where);
131
+ ingressFacts(obj, where, fact, type);
132
+ }
133
+ const perms = permissionsOf(x, obj, { file, refWords, targetScope, bySym, vars, params, text });
134
+ for (const p of perms) { const k = p.role && knows.find((kn) => normKey(kn.name) === 'roledefinitionid'); if (k) { k.kind = `${p.role} (a built-in role)`; delete k.computed; } }
135
+ permissions.push(...perms);
136
+ things.push({
137
+ kind: 'resource', name: address, label: x.kind === 'module' ? `Module ${name}` : resourceLabel(type, name), resourceType: type, address, file,
138
+ lines: [d.line, d.endLine], knows, choices: [], ...(d.doc ? { doc: d.doc } : {}), ...(x.existing ? { existing: true } : {}),
139
+ });
140
+ }
141
+ for (const p of permissions) if (p.wide) fact('wide-permission', `${cap(p.who)} can ${p.can} on ${p.on}: ${p.why}.`, p.line);
142
+
143
+ // ── Settings ──
144
+ const deco = (d, n) => d.decorators?.find((x) => x.name === n);
145
+ for (const d of decls) {
146
+ const desc = deco(d, 'description')?.args[0];
147
+ const doc = desc?.t === 'str' && desc.v ? { doc: desc.v.trim() } : {};
148
+ if (d.kind === 'param') {
149
+ const secure = !!deco(d, 'secure');
150
+ const secret = secure || (isSecretKey(d.name) && /^string\b/.test(d.typeRaw ?? ''));
151
+ if (secret && d.value?.t === 'str' && !d.value.template && d.value.v) fact('secret-in-plain-config', `The setting ${d.name} is a secret, but its default value is written in the file.`, d.value.line);
152
+ const allowed = deco(d, 'allowed')?.args[0];
153
+ settings.push({ name: d.name, source: 'parameter', secret, file, line: d.line, ...(d.typeRaw ? { type: d.typeRaw } : {}),
154
+ ...(d.value && !secret ? { default: valueText(d.value, refWords).text.replace(` (${APPLIED})`, '') } : {}), ...(allowed?.t === 'list' && isLiteral(allowed) ? { allowed: allowed.items.map((i) => String(i.v)) } : {}), ...doc });
155
+ } else if (d.kind === 'var') {
156
+ const lit = isLiteral(d.value);
157
+ const secret = isSecretKey(d.name) && d.value?.t === 'str';
158
+ if (secret && lit && d.value.v) fact('secret-in-plain-config', `The value ${d.name} looks like a secret and is written in the file.`, d.line);
159
+ settings.push({ name: d.name, source: lit ? 'literal' : 'computed', secret, file, line: d.line, ...(lit ? {} : { computed: true }), ...(lit && !secret ? { default: valueText(d.value, refWords).text } : {}), ...doc });
160
+ } else if (d.kind === 'output') {
161
+ const from = valueText(d.value, refWords);
162
+ settings.push({ name: d.name, source: 'computed', secret: !!deco(d, 'secure') || (isSecretKey(d.name) && /^string\b/.test(d.typeRaw ?? '')), computed: true, output: true, file, line: d.line, ...(from.from?.length ? { from: from.from.slice(0, 3) } : {}), ...doc });
163
+ }
164
+ }
165
+
166
+ // ── The order things are created ──
167
+ const steps = [];
168
+ if (scopeDecl) steps.push({ kind: 'call', says: `Deploys to ${SCOPES[targetScope] ?? targetScope}`, code: `targetScope = ${text.slice(scopeDecl.value.s, scopeDecl.value.e)}`, line: scopeDecl.line });
169
+ const order = topoOrder(declared.map((x) => x.address), links.filter((l) => bySym.has(l.to)).map((l) => [l.from, l.to]));
170
+ for (const addr of order) {
171
+ const x = bySym.get(addr);
172
+ const { d, type, name } = x;
173
+ const { loop, cond } = unwrap(d.value);
174
+ const inLink = links.find((l) => l.from === addr && l.kind === 'runs-in' && bySym.has(l.to));
175
+ const inWords = inLink ? ` in the ${bySym.get(inLink.to).existing ? 'existing ' : ''}${typeWords(bySym.get(inLink.to).type)} ${inLink.to}` : '';
176
+ const head = x.kind === 'module' ? `module ${name} '${d.path}'` : `resource ${name} '${d.type}${d.apiVersion ? `@${d.apiVersion}` : ''}'${x.existing ? ' existing' : ''}`;
177
+ const says = x.kind === 'module' ? `Uses the module ${name} (${d.path})${inWords}` : x.existing ? `Looks up the existing ${typeWords(type)} ${name}${inWords}` : `Creates the ${typeWords(type)} ${name}${inWords}`;
178
+ let step = { kind: 'call', says, code: head, line: d.line };
179
+ if (cond) step = { kind: 'branch', says: question(conditionWords(cond, refWords)), code: `if (${text.slice(cond.s, cond.e)})`, line: cond.line, children: [step] };
180
+ if (loop) step = { kind: 'loop', says: `For each ${valueText(loop.coll, refWords).from?.length === 1 ? `item in ${valueText(loop.coll, refWords).from[0]}` : 'item in a list'}`, code: `for ${loop.vars.join(', ')} in ${text.slice(loop.coll.s, loop.coll.e)}`, line: loop.line, children: [step] };
181
+ steps.push(step);
182
+ }
183
+ const base = file.slice(file.lastIndexOf('/') + 1);
184
+ const items = [];
185
+ if (declared.length) {
186
+ const made = declared.filter((x) => x.kind === 'resource' && !x.existing).length;
187
+ const first = Math.min(...steps.map((s) => s.line)), last = Math.max(...declared.map((x) => x.d.endLine));
188
+ items.push({
189
+ id: `deploy:${first}`, name: 'deploy', label: `Deploying ${base}`, title: `What deploying ${base} makes, in order`, line: first, endLine: last,
190
+ inputs: [], returns: null, provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0, stepsReadable: 1,
191
+ says: `Deploying ${base} makes ${made} resource${made === 1 ? '' : 's'}, in the order they rely on each other.`,
192
+ headline: `Deploying ${base}: ${steps.length} step${steps.length === 1 ? '' : 's'}.`, guards: [], unread: [],
193
+ });
194
+ }
195
+ const meta = decls.find((d) => d.kind === 'metadata' && d.name === 'description') ?? decls.find((d) => d.kind === 'metadata' && d.name === 'name');
196
+ return { items, things, settings, facts, links, permissions, unknowns, purpose: meta?.value?.t === 'str' && meta.value.v ? meta.value.v.trim() : null };
197
+ }
198
+
199
+ /** One property as something a Resource knows. */
200
+ function entryKnow(e, refWords, prefix = '') {
201
+ const v = e.value;
202
+ const secret = isSecretKey(e.key) && (v.t === 'str' || !isLiteral(v));
203
+ if (v.t === 'obj' && !isLiteral(v)) {
204
+ const parts = v.entries.filter((x) => !x.nested).map((x) => (x.spread ? `everything in ${valueText(x.value.x ?? x.value, refWords).text}` : `${words(x.key)}: ${isSecretKey(x.key) && !isLiteral(x.value) ? 'a secret (not shown)' : isSecretKey(x.key) && x.value.t === 'str' ? 'a secret written in the file (not shown)' : valueText(x.value, refWords).text}`));
205
+ return { name: e.key, label: cap(`${prefix}${words(e.key)}`.trim()), kind: parts.length ? `${parts.slice(0, 4).join('; ')}${parts.length > 4 ? `; and ${parts.length - 4} more` : ''}` : 'none', line: e.line, computed: true };
206
+ }
207
+ if (secret) return { name: e.key, label: cap(`${prefix}${words(e.key)}`.trim()), kind: v.t === 'str' && !v.template ? 'a secret written in the file (its value is not shown)' : `a secret${valueText(v, refWords).from?.length ? ` from ${listWords(valueText(v, refWords).from)}` : ''} (its value is not shown)`, line: e.line, secret: true, ...(isLiteral(v) ? {} : { computed: true }) };
208
+ const t = valueText(v, refWords);
209
+ return { name: e.key, label: cap(`${prefix}${words(e.key)}`.trim()), kind: t.text, line: e.line, ...(t.computed ? { computed: true } : {}) };
210
+ }
211
+
212
+ function scopeOf(n, refWords, targetScope) {
213
+ if (!n) {
214
+ if (targetScope === 'subscription') return { on: 'the whole subscription', wide: true };
215
+ if (targetScope === 'managementGroup') return { on: 'the management group (every subscription in it)', wide: true };
216
+ if (targetScope === 'tenant') return { on: 'the whole tenant', wide: true };
217
+ return { on: 'the resource group it is deployed to' };
218
+ }
219
+ if (n.t === 'call') {
220
+ const f = n.name.replace(/^az\./, '');
221
+ if (f === 'subscription') return { on: n.args.length ? `the subscription ${valueText(n.args[0], refWords).text}` : 'the whole subscription', wide: true };
222
+ if (f === 'managementGroup') return { on: 'a management group (every subscription in it)', wide: true };
223
+ if (f === 'tenant') return { on: 'the whole tenant', wide: true };
224
+ if (f === 'resourceGroup') return { on: n.args.length ? `the resource group ${valueText(n.args.at(-1), refWords).text}` : 'the resource group it is deployed to' };
225
+ }
226
+ const w = refWords(n);
227
+ return { on: w ? w.replace(/^the id of /, '') : valueText(n, refWords).text };
228
+ }
229
+
230
+ function principalOf(n, ctx) {
231
+ if (!n) return 'someone';
232
+ if (n.t === 'get' && n.obj.t === 'call' && /deployer$/.test(n.obj.name)) return 'whoever deploys it';
233
+ if (n.t === 'ref') {
234
+ const [root, ...rest] = n.path;
235
+ const r = ctx.bySym.get(root);
236
+ if (r) {
237
+ if (rest.includes('identity')) return `the ${typeWords(r.type)} ${root} (its own identity)`;
238
+ if (/userAssignedIdentities$/i.test(r.type)) return `the managed identity ${root}`;
239
+ return `the ${typeWords(r.type)} ${root}`;
240
+ }
241
+ if (ctx.params.has(root)) return `the identity given in the setting ${root}`;
242
+ }
243
+ const w = ctx.refWords(n);
244
+ return w ?? `an identity ${APPLIED}`;
245
+ }
246
+
247
+ /** The role a roleDefinitionId names, following a var or a param's default one step. */
248
+ function roleOfNode(n, ctx) {
249
+ if (!n) return null;
250
+ const slice = (x) => ctx.text.slice(x.s, x.e);
251
+ let r = roleIn(slice(n));
252
+ if (r) return r;
253
+ for (const ref of refsIn(n)) {
254
+ const v = ctx.vars.get(ref.path[0])?.value ?? ctx.params.get(ref.path[0])?.value;
255
+ if (!v) continue;
256
+ // A var that maps role names to ids (`roles.contributor`) names the role by the key it uses.
257
+ if (v.t === 'obj' && ref.path[1]) { const e = entryOf(v, ref.path[1]); if (e) { r = roleIn(slice(e.value)); if (r) return r; } }
258
+ r = roleIn(slice(v));
259
+ if (r && v.t !== 'obj') return r;
260
+ }
261
+ return null;
262
+ }
263
+
264
+ function permissionsOf(x, obj, ctx) {
265
+ const out = [];
266
+ if (!obj) return out;
267
+ const add = (who, can, on, line, wide = false, why, role) => out.push({ id: `${ctx.file}#permission#${line}#${out.length}`, who, can, on, wide: !!wide, ...(wide && why ? { why } : {}), ...(role ? { role } : {}), file: ctx.file, line, says: `${cap(who)} can ${can} on ${on}` });
268
+ const props = entryOf(obj, 'properties')?.value;
269
+ if (/^Microsoft\.Authorization\/roleAssignments$/i.test(x.type) && !x.existing) {
270
+ const roleNode = entryOf(props, 'roleDefinitionId')?.value;
271
+ const role = roleOfNode(roleNode, ctx);
272
+ const scope = scopeOf(entryOf(obj, 'scope')?.value, ctx.refWords, ctx.targetScope);
273
+ const wide = role && WIDE_ROLES.has(role) && scope.wide;
274
+ const can = role ? roleCan(role) : `act in the role ${roleNode ? valueText(roleNode, ctx.refWords).text : 'it is given'}`;
275
+ add(principalOf(entryOf(props, 'principalId')?.value, ctx), can, scope.on, x.d.line, wide, wide ? `${role} of ${scope.on}` : undefined, role);
276
+ } else if (/^Microsoft\.KeyVault\/vaults(\/accessPolicies)?$/i.test(x.type)) {
277
+ const pols = entryOf(props, 'accessPolicies')?.value;
278
+ for (const p of pols?.t === 'list' ? pols.items : []) {
279
+ if (p.t !== 'obj') continue;
280
+ const perms = entryOf(p, 'permissions')?.value;
281
+ const kinds = (perms?.entries ?? []).filter((e) => e.value.t === 'list' && e.value.items.length).map((e) => `${listWords(e.value.items.map((i) => String(i.v ?? '…').toLowerCase()))} ${e.key}`);
282
+ if (!kinds.length) continue;
283
+ const all = kinds.some((k) => /\b(all|purge)\b/.test(k));
284
+ add(principalOf(entryOf(p, 'objectId')?.value, ctx), listWords(kinds), `the key vault ${x.name}`, p.line, all, all ? 'it can purge or do everything to them' : undefined);
285
+ }
286
+ }
287
+ return out;
288
+ }
289
+
290
+ /** NSG rules (inline or as their own resource) that let anyone on the internet in, beyond web ports. */
291
+ function ingressFacts(obj, where, fact, type) {
292
+ const rules = [];
293
+ const visit = (n) => {
294
+ if (!n) return;
295
+ if (n.t === 'obj') {
296
+ if (entryOf(n, 'direction') && entryOf(n, 'access')) rules.push(n);
297
+ for (const e of n.entries) if (!e.nested) visit(e.value);
298
+ } else if (n.t === 'list') n.items.forEach(visit);
299
+ };
300
+ if (/networkSecurityGroups/i.test(type)) visit(obj);
301
+ const str = (n) => (n?.t === 'str' && !n.template ? n.v : null);
302
+ const strs = (n) => (n?.t === 'list' ? n.items.map(str).filter((v) => v != null) : str(n) != null ? [str(n)] : []);
303
+ for (const r of rules) {
304
+ if (String(str(entryOf(r, 'direction')?.value) ?? '').toLowerCase() !== 'inbound' || String(str(entryOf(r, 'access')?.value) ?? '').toLowerCase() !== 'allow') continue;
305
+ if (!fromAnywhere([...strs(entryOf(r, 'sourceAddressPrefix')?.value), ...strs(entryOf(r, 'sourceAddressPrefixes')?.value)])) continue;
306
+ const ports = [...strs(entryOf(r, 'destinationPortRange')?.value), ...strs(entryOf(r, 'destinationPortRanges')?.value)];
307
+ for (const p of ports.length ? ports : ['*']) {
308
+ const o = p === '*' ? { says: 'every port', beyondWeb: true } : portsOpen(p, null, str(entryOf(r, 'protocol')?.value));
309
+ if (o.beyondWeb) fact('public-ingress', `${where} lets anyone on the internet reach ${o.says}.`, r.line);
310
+ }
311
+ }
312
+ }