@intentius/chant-lexicon-terraform 0.124.97 → 0.124.98

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 (104) hide show
  1. package/dist/behaviour/reference-catalog.d.ts +42 -6
  2. package/dist/behaviour/reference-catalog.d.ts.map +1 -1
  3. package/dist/behaviour/reference-catalog.js +169 -8
  4. package/dist/describe-resources.js +1 -1
  5. package/dist/hcl/evaluate.d.ts +151 -0
  6. package/dist/hcl/evaluate.d.ts.map +1 -0
  7. package/dist/hcl/evaluate.js +940 -0
  8. package/dist/hcl/instances.d.ts +11 -1
  9. package/dist/hcl/instances.d.ts.map +1 -1
  10. package/dist/hcl/instances.js +89 -3
  11. package/dist/hcl/parse.d.ts +23 -1
  12. package/dist/hcl/parse.d.ts.map +1 -1
  13. package/dist/hcl/parse.js +9 -3
  14. package/dist/hcl/redact.d.ts +5 -1
  15. package/dist/hcl/redact.d.ts.map +1 -1
  16. package/dist/hcl/redact.js +7 -3
  17. package/dist/hcl/references.d.ts +12 -1
  18. package/dist/hcl/references.d.ts.map +1 -1
  19. package/dist/hcl/references.js +33 -16
  20. package/dist/integrity.json +6 -6
  21. package/dist/lint/post-synth/tf001.d.ts +4 -1
  22. package/dist/lint/post-synth/tf001.d.ts.map +1 -1
  23. package/dist/lint/post-synth/tf001.js +20 -8
  24. package/dist/lint/post-synth/tf002.d.ts +11 -5
  25. package/dist/lint/post-synth/tf002.d.ts.map +1 -1
  26. package/dist/lint/post-synth/tf002.js +42 -8
  27. package/dist/lint/post-synth/tf006.d.ts +7 -3
  28. package/dist/lint/post-synth/tf006.d.ts.map +1 -1
  29. package/dist/lint/post-synth/tf006.js +9 -3
  30. package/dist/lint/post-synth/tf022.d.ts +6 -0
  31. package/dist/lint/post-synth/tf022.d.ts.map +1 -1
  32. package/dist/lint/post-synth/tf022.js +18 -1
  33. package/dist/lint/secret-shape.d.ts +8 -0
  34. package/dist/lint/secret-shape.d.ts.map +1 -1
  35. package/dist/lint/secret-shape.js +76 -0
  36. package/dist/manifest.json +1 -1
  37. package/dist/plugin.d.ts.map +1 -1
  38. package/dist/plugin.js +7 -2
  39. package/dist/rules/tf001.ts +21 -7
  40. package/dist/rules/tf002.ts +44 -7
  41. package/dist/rules/tf006.ts +8 -3
  42. package/dist/rules/tf022.ts +18 -1
  43. package/package.json +2 -2
  44. package/src/__fixtures__/resolved-arguments/build-trusted/extras.tf +28 -0
  45. package/src/__fixtures__/resolved-arguments/build-trusted/main.tf +22 -0
  46. package/src/__fixtures__/resolved-arguments/build-trusted/serviceaccounts.tf +26 -0
  47. package/src/__fixtures__/resolved-arguments/modules/gke-cluster/main.tf +15 -0
  48. package/src/__fixtures__/resolved-arguments/modules/gke-cluster/variables.tf +12 -0
  49. package/src/__fixtures__/resolved-arguments/modules/gke-project/main.tf +9 -0
  50. package/src/__fixtures__/resolved-arguments/modules/gke-project/outputs.tf +9 -0
  51. package/src/__fixtures__/resolved-arguments/modules/gke-project/variables.tf +7 -0
  52. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/main.tf +16 -0
  53. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/outputs.tf +4 -0
  54. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/variables.tf +21 -0
  55. package/src/behaviour/reference-catalog.plugin.test.ts +101 -2
  56. package/src/behaviour/reference-catalog.ts +162 -9
  57. package/src/describe-resources.ts +1 -1
  58. package/src/hcl/edges.test.ts +1 -1
  59. package/src/hcl/evaluate.test.ts +215 -0
  60. package/src/hcl/evaluate.ts +899 -0
  61. package/src/hcl/instances.ts +89 -3
  62. package/src/hcl/parse.test.ts +18 -0
  63. package/src/hcl/parse.ts +28 -3
  64. package/src/hcl/redact.ts +7 -3
  65. package/src/hcl/references.test.ts +68 -0
  66. package/src/hcl/references.ts +31 -15
  67. package/src/lint/post-synth/fixtures/TF001/negative-second-block.tf +17 -0
  68. package/src/lint/post-synth/fixtures/TF002/module-cycle/cdn/back/main.tf +3 -0
  69. package/src/lint/post-synth/fixtures/TF002/module-cycle/cdn/main.tf +3 -0
  70. package/src/lint/post-synth/fixtures/TF002/module-cycle/main.tf +14 -0
  71. package/src/lint/post-synth/fixtures/TF002/module-nested/cdn/edge/main.tf +8 -0
  72. package/src/lint/post-synth/fixtures/TF002/module-nested/cdn/main.tf +3 -0
  73. package/src/lint/post-synth/fixtures/TF002/module-nested/main.tf +14 -0
  74. package/src/lint/post-synth/fixtures/TF002/module-other-provider/cdn/main.tf +8 -0
  75. package/src/lint/post-synth/fixtures/TF002/module-other-provider/main.tf +14 -0
  76. package/src/lint/post-synth/fixtures/TF002/module-pinned/cdn/main.tf +12 -0
  77. package/src/lint/post-synth/fixtures/TF002/module-pinned/main.tf +14 -0
  78. package/src/lint/post-synth/fixtures/TF002/module-unpinned/cdn/main.tf +7 -0
  79. package/src/lint/post-synth/fixtures/TF002/module-unpinned/main.tf +14 -0
  80. package/src/lint/post-synth/fixtures/TF006/negative-null-default.tf +12 -0
  81. package/src/lint/post-synth/fixtures/TF006/positive-empty-default.tf +0 -6
  82. package/src/lint/post-synth/fixtures/TF007/negative-names.tf +25 -0
  83. package/src/lint/post-synth/fixtures/TF022/negative-secret-reference.tf +32 -0
  84. package/src/lint/post-synth/fixtures/TF022/positive-secret-data.tf +8 -0
  85. package/src/lint/post-synth/fixtures/TF024/live-backend-second-block/a-versions.tf +3 -0
  86. package/src/lint/post-synth/fixtures/TF024/live-backend-second-block/b-backend.tf +10 -0
  87. package/src/lint/post-synth/fixtures/TF024/live-cloud-second-block/a-versions.tf +3 -0
  88. package/src/lint/post-synth/fixtures/TF024/live-cloud-second-block/b-cloud.tf +9 -0
  89. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/a-versions.tf +3 -0
  90. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/b-backend.tf +6 -0
  91. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/estate.chdf.hcl +1 -0
  92. package/src/lint/post-synth/module-rules.test.ts +1 -1
  93. package/src/lint/post-synth/post-synth.test.ts +39 -0
  94. package/src/lint/post-synth/single-block.test.ts +23 -2
  95. package/src/lint/post-synth/tf001.ts +21 -7
  96. package/src/lint/post-synth/tf002.test.ts +45 -1
  97. package/src/lint/post-synth/tf002.ts +44 -7
  98. package/src/lint/post-synth/tf006.ts +8 -3
  99. package/src/lint/post-synth/tf022.ts +18 -1
  100. package/src/lint/post-synth/tf024.test.ts +21 -0
  101. package/src/lint/secret-shape.test.ts +30 -0
  102. package/src/lint/secret-shape.ts +75 -0
  103. package/src/plugin.ts +6 -2
  104. package/src/redact.test.ts +8 -0
@@ -0,0 +1,940 @@
1
+ /**
2
+ * Evaluate a block's arguments from the files a plan reads, per module
3
+ * instance (chant #5117).
4
+ *
5
+ * The reference catalog (`../behaviour/reference-catalog.ts`) matches values
6
+ * written on a node. A declared block mostly holds expressions instead:
7
+ * `account_id = var.name`, where the variable is set by a module call from
8
+ * `each.key`, and `project = var.project_id`, set from another module's
9
+ * output. This module follows those expressions back to a literal where the
10
+ * source alone says what it is, so the catalog has the value to match.
11
+ *
12
+ * It resolves, in one module instance:
13
+ *
14
+ * - `var.<x>` from the call's argument (evaluated in the caller), else the
15
+ * variable's default; in the root module from the tfvars files
16
+ * `./instances.ts` reads, then the default;
17
+ * - `local.<x>`, `each.key`, `each.value` and `count.index`;
18
+ * - `module.<call>.<output>`, when the output's value resolves in the child;
19
+ * - `<type>.<name>.<arg>` in the same module, when the block sets `<arg>`;
20
+ * - `"${...}"` interpolation whose every part resolves;
21
+ * - `lookup(map, key, default)`, `toset()`, `length()` and `cond ? a : b`
22
+ * over a known bool, plus list and object constructors and index steps;
23
+ * - `a == b` and `a != b` over two known values (#5094), so
24
+ * `count = var.is_prod_cluster == "true" ? 1 : 0` picks its count.
25
+ *
26
+ * Anything else is unknown, and an unknown value carries the first
27
+ * reference that stopped it: a data source (`data.google_organization.org.org_id`),
28
+ * a function (`timestamp()`), an attribute the provider computes
29
+ * (`google_service_account.sa.email`), a variable nothing sets, an operator
30
+ * this reader does not evaluate. A reference inside a child module is named
31
+ * with the module path in front, as Terraform prints addresses
32
+ * (`module.project.data.google_organization.org.org_id`). A sensitive
33
+ * variable or output is unknown, so a value marked sensitive never reaches
34
+ * the graph. No plan, state or provider is read.
35
+ *
36
+ * Pure apart from what it is handed: the parsed entities of one root, its
37
+ * tfvars values, and a module path.
38
+ */
39
+ import { isResourceDeclarable } from "@intentius/chant/declarable";
40
+ import { LOCALS_TYPE, MODULE_TYPE, OUTPUT_TYPE, RESOURCE_TYPE, VARIABLE_TYPE, scopeOfKey, } from "./parse.js";
41
+ /** A value the source does not determine, and the reference that stopped it. */
42
+ export class Unknown {
43
+ constructor(ref) {
44
+ this.ref = ref;
45
+ }
46
+ }
47
+ export const isUnknown = (v) => v instanceof Unknown;
48
+ /** Lists `toset()` made, so `for_each` can tell a set from a list. */
49
+ const SETS = new WeakSet();
50
+ /** Whether a value is a set `toset()` made. */
51
+ export const isSetValue = (v) => Array.isArray(v) && SETS.has(v);
52
+ /** The first unknown inside a value, depth first, or undefined when the value is wholly known. */
53
+ export function firstUnknown(v, depth = 0) {
54
+ if (v instanceof Unknown)
55
+ return v;
56
+ if (depth > 32)
57
+ return undefined;
58
+ if (Array.isArray(v)) {
59
+ for (const x of v) {
60
+ const u = firstUnknown(x, depth + 1);
61
+ if (u)
62
+ return u;
63
+ }
64
+ }
65
+ else if (typeof v === "object" && v !== null) {
66
+ for (const x of Object.values(v)) {
67
+ const u = firstUnknown(x, depth + 1);
68
+ if (u)
69
+ return u;
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+ /** An expression this reader does not evaluate; `text` names it, cut to 80 characters. */
75
+ class Unsupported extends Error {
76
+ constructor(text) {
77
+ const flat = text.replace(/\s+/g, " ").trim();
78
+ super(flat);
79
+ this.text = flat.length > 80 ? `${flat.slice(0, 77)}...` : flat;
80
+ }
81
+ }
82
+ /** Index just past the `}` that closes the `{` at `open`, skipping strings. -1 when unclosed. */
83
+ function closeBrace(s, open) {
84
+ let depth = 0;
85
+ for (let i = open; i < s.length; i++) {
86
+ const c = s[i];
87
+ if (c === '"') {
88
+ i = skipQuoted(s, i) - 1;
89
+ continue;
90
+ }
91
+ if (c === "{")
92
+ depth++;
93
+ else if (c === "}" && --depth === 0)
94
+ return i + 1;
95
+ }
96
+ return -1;
97
+ }
98
+ /** Index just past the string opened at `i`, its interpolations included. */
99
+ function skipQuoted(s, i) {
100
+ i++;
101
+ while (i < s.length) {
102
+ const c = s[i];
103
+ if (c === "\\")
104
+ i += 2;
105
+ else if (c === "$" && s[i + 1] === "$" && s[i + 2] === "{")
106
+ i += 3;
107
+ else if (c === "$" && s[i + 1] === "{") {
108
+ const end = closeBrace(s, i + 1);
109
+ if (end === -1)
110
+ return s.length;
111
+ i = end;
112
+ }
113
+ else if (c === '"')
114
+ return i + 1;
115
+ else
116
+ i++;
117
+ }
118
+ return s.length;
119
+ }
120
+ /**
121
+ * A template's parts: literal text and the expressions of its `${...}`.
122
+ * `$${` is a literal `${`. A `%{` directive is not read.
123
+ */
124
+ function parseTemplate(s, unescape) {
125
+ const parts = [];
126
+ let lit = "";
127
+ let i = 0;
128
+ while (i < s.length) {
129
+ if (s.startsWith("$${", i)) {
130
+ lit += "${";
131
+ i += 3;
132
+ }
133
+ else if (s.startsWith("%%{", i)) {
134
+ lit += "%{";
135
+ i += 3;
136
+ }
137
+ else if (s.startsWith("%{", i)) {
138
+ throw new Unsupported(s);
139
+ }
140
+ else if (s.startsWith("${", i)) {
141
+ const end = closeBrace(s, i + 1);
142
+ if (end === -1)
143
+ throw new Unsupported(s);
144
+ if (lit)
145
+ parts.push(unescape(lit));
146
+ lit = "";
147
+ parts.push(parseExpression(s.slice(i + 2, end - 1).replace(/^~/, "").replace(/~$/, "")));
148
+ i = end;
149
+ }
150
+ else {
151
+ lit += s[i];
152
+ i++;
153
+ }
154
+ }
155
+ if (lit)
156
+ parts.push(unescape(lit));
157
+ return parts;
158
+ }
159
+ /** The escapes of a quoted HCL string. */
160
+ function unescapeQuoted(t) {
161
+ return t.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_, e) => {
162
+ if (e === "n")
163
+ return "\n";
164
+ if (e === "t")
165
+ return "\t";
166
+ if (e === "r")
167
+ return "\r";
168
+ if (e[0] === "u" || e[0] === "U")
169
+ return String.fromCodePoint(parseInt(e.slice(1), 16));
170
+ return e;
171
+ });
172
+ }
173
+ const PUNCT = ["...", "==", "!=", "<=", ">=", "&&", "||", "=>", "(", ")", "[", "]", "{", "}", ",", ".", "?", ":", "=", "*", "!", "+", "-", "/", "%", "<", ">"];
174
+ function tokenize(s) {
175
+ const out = [];
176
+ let i = 0;
177
+ while (i < s.length) {
178
+ const c = s[i];
179
+ if (/\s/.test(c)) {
180
+ i++;
181
+ }
182
+ else if (c === "#" || s.startsWith("//", i)) {
183
+ while (i < s.length && s[i] !== "\n")
184
+ i++;
185
+ }
186
+ else if (s.startsWith("/*", i)) {
187
+ const end = s.indexOf("*/", i + 2);
188
+ i = end === -1 ? s.length : end + 2;
189
+ }
190
+ else if (/[A-Za-z_]/.test(c)) {
191
+ const m = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(s.slice(i));
192
+ out.push({ k: "id", v: m[0], at: i, end: i + m[0].length });
193
+ i += m[0].length;
194
+ }
195
+ else if (/[0-9]/.test(c)) {
196
+ const m = /^[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(s.slice(i));
197
+ out.push({ k: "num", v: m[0], at: i, end: i + m[0].length });
198
+ i += m[0].length;
199
+ }
200
+ else if (c === '"') {
201
+ const end = skipQuoted(s, i);
202
+ out.push({ k: "str", v: s.slice(i + 1, end - 1), at: i, end });
203
+ i = end;
204
+ }
205
+ else if (s.startsWith("<<", i)) {
206
+ throw new Unsupported(s.trim());
207
+ }
208
+ else {
209
+ const p = PUNCT.find((x) => s.startsWith(x, i));
210
+ if (!p)
211
+ throw new Unsupported(s.trim());
212
+ out.push({ k: "p", v: p, at: i, end: i + p.length });
213
+ i += p.length;
214
+ }
215
+ }
216
+ return out;
217
+ }
218
+ /** Parse the inside of one `${...}`. Throws {@link Unsupported} on a form this reader does not evaluate. */
219
+ function parseExpression(src) {
220
+ const toks = tokenize(src);
221
+ let pos = 0;
222
+ const peek = (v) => {
223
+ const t = toks[pos];
224
+ return t && (v === undefined || (t.k === "p" && t.v === v)) ? t : undefined;
225
+ };
226
+ const expect = (v) => {
227
+ const t = peek(v);
228
+ if (!t)
229
+ throw new Unsupported(src.trim());
230
+ pos++;
231
+ return t;
232
+ };
233
+ const textFrom = (start) => src.slice(toks[start].at, toks[pos - 1].end).trim();
234
+ const steps = () => {
235
+ const out = [];
236
+ for (;;) {
237
+ if (peek(".")) {
238
+ pos++;
239
+ const t = toks[pos];
240
+ if (t?.k === "id")
241
+ out.push({ attr: t.v });
242
+ else if (t?.k === "num")
243
+ out.push({ index: { t: "lit", v: Number(t.v) } });
244
+ else if (t?.k === "p" && t.v === "*")
245
+ out.push({ splat: true });
246
+ else
247
+ throw new Unsupported(src.trim());
248
+ pos++;
249
+ }
250
+ else if (peek("[")) {
251
+ pos++;
252
+ if (peek("*")) {
253
+ pos++;
254
+ out.push({ splat: true });
255
+ }
256
+ else
257
+ out.push({ index: expr() });
258
+ expect("]");
259
+ }
260
+ else
261
+ return out;
262
+ }
263
+ };
264
+ const primary = () => {
265
+ const start = pos;
266
+ const t = toks[pos];
267
+ if (!t)
268
+ throw new Unsupported(src.trim());
269
+ pos++;
270
+ if (t.k === "num")
271
+ return { t: "lit", v: Number(t.v) };
272
+ if (t.k === "str")
273
+ return { t: "tpl", parts: parseTemplate(t.v, unescapeQuoted), text: src.slice(t.at, t.end) };
274
+ if (t.k === "id") {
275
+ if (t.v === "true" || t.v === "false")
276
+ return { t: "lit", v: t.v === "true" };
277
+ if (t.v === "null")
278
+ return { t: "lit", v: null };
279
+ if (peek("(")) {
280
+ pos++;
281
+ const args = [];
282
+ while (!peek(")")) {
283
+ args.push(expr());
284
+ if (peek("..."))
285
+ throw new Unsupported(src.trim());
286
+ if (!peek(","))
287
+ break;
288
+ pos++;
289
+ }
290
+ expect(")");
291
+ return { t: "call", name: t.v, args, text: textFrom(start) };
292
+ }
293
+ const s = steps();
294
+ return { t: "ref", root: t.v, steps: s, text: textFrom(start) };
295
+ }
296
+ if (t.v === "-" && toks[pos]?.k === "num") {
297
+ pos++;
298
+ return { t: "lit", v: -Number(toks[pos - 1].v) };
299
+ }
300
+ if (t.v === "(") {
301
+ const inner = expr();
302
+ expect(")");
303
+ return inner;
304
+ }
305
+ if (t.v === "[") {
306
+ if (toks[pos]?.k === "id" && toks[pos].v === "for")
307
+ throw new Unsupported(src.trim());
308
+ const items = [];
309
+ while (!peek("]")) {
310
+ items.push(expr());
311
+ if (!peek(","))
312
+ break;
313
+ pos++;
314
+ }
315
+ expect("]");
316
+ return { t: "tuple", items };
317
+ }
318
+ if (t.v === "{") {
319
+ if (toks[pos]?.k === "id" && toks[pos].v === "for")
320
+ throw new Unsupported(src.trim());
321
+ const entries = [];
322
+ while (!peek("}")) {
323
+ const k = toks[pos];
324
+ let key;
325
+ if (k?.k === "id" && (toks[pos + 1]?.v === "=" || toks[pos + 1]?.v === ":")) {
326
+ key = { t: "lit", v: k.v };
327
+ pos++;
328
+ }
329
+ else
330
+ key = expr();
331
+ if (peek("=") || peek(":"))
332
+ pos++;
333
+ else
334
+ throw new Unsupported(src.trim());
335
+ entries.push([key, expr()]);
336
+ if (peek(","))
337
+ pos++;
338
+ }
339
+ expect("}");
340
+ return { t: "object", entries };
341
+ }
342
+ throw new Unsupported(src.trim());
343
+ };
344
+ const postfix = () => {
345
+ const start = pos;
346
+ const p = primary();
347
+ if (p.t === "ref")
348
+ return p;
349
+ const s = steps();
350
+ return s.length === 0 ? p : { t: "post", of: p, steps: s, text: textFrom(start) };
351
+ };
352
+ // `==` and `!=` (#5094) bind looser than a traversal and tighter than `? :`.
353
+ // Arithmetic and `&&`/`||` are not read, so an operand followed by one is unsupported.
354
+ const equality = () => {
355
+ let l = postfix();
356
+ while (peek("==") || peek("!=")) {
357
+ const negate = toks[pos].v === "!=";
358
+ pos++;
359
+ l = { t: "eq", negate, l, r: postfix() };
360
+ }
361
+ return l;
362
+ };
363
+ const expr = () => {
364
+ const c = equality();
365
+ const next = toks[pos];
366
+ if (next?.k === "p" && next.v === "?") {
367
+ pos++;
368
+ const a = expr();
369
+ expect(":");
370
+ const b = expr();
371
+ return { t: "cond", c, a, b };
372
+ }
373
+ if (next?.k === "p" && ![")", "]", "}", ",", ":", "...", "="].includes(next.v))
374
+ throw new Unsupported(src.trim());
375
+ return c;
376
+ };
377
+ const e = expr();
378
+ if (pos < toks.length)
379
+ throw new Unsupported(src.trim());
380
+ return e;
381
+ }
382
+ const parsed = new Map();
383
+ /** A hcl2json string as an expression: a template, or one bare `${...}` whose value is the expression's own. */
384
+ function parseValueString(s) {
385
+ const hit = parsed.get(s);
386
+ if (hit)
387
+ return hit;
388
+ let out;
389
+ try {
390
+ const parts = parseTemplate(s, (t) => t);
391
+ out = parts.length === 1 && typeof parts[0] !== "string" ? parts[0] : { t: "tpl", parts, text: s };
392
+ }
393
+ catch (err) {
394
+ out = err instanceof Unsupported ? err : new Unsupported(s);
395
+ }
396
+ if (parsed.size > 20000)
397
+ parsed.clear();
398
+ parsed.set(s, out);
399
+ return out;
400
+ }
401
+ const SEGMENT_RE = /^module\.([A-Za-z_][A-Za-z0-9_-]*)(\[(?:[0-9]+|"(?:[^"\\]|\\.)*")\])?(?:\.|$)/;
402
+ /** The key text of an instance key, `[0]` or `["a"]`, as a number or a string. */
403
+ export function instanceKeyValue(key) {
404
+ const inner = key.slice(1, -1);
405
+ if (/^[0-9]+$/.test(inner))
406
+ return Number(inner);
407
+ try {
408
+ const v = JSON.parse(inner);
409
+ return typeof v === "string" ? v : undefined;
410
+ }
411
+ catch {
412
+ return undefined;
413
+ }
414
+ }
415
+ function bodyOf(entity) {
416
+ const body = entity && isResourceDeclarable(entity) ? entity.props.body : undefined;
417
+ return (typeof body === "object" && body !== null ? body : {});
418
+ }
419
+ const expanded = (body) => ("count" in body ? "count" : "for_each" in body ? "for_each" : undefined);
420
+ /**
421
+ * Evaluates expressions over one root's parsed entities. Build it once per
422
+ * root, after the descent into local modules.
423
+ */
424
+ export class RootEvaluator {
425
+ constructor(entities, root, tfvars = new Map()) {
426
+ this.entities = entities;
427
+ this.root = root;
428
+ this.tfvars = tfvars;
429
+ this.vars = new Map();
430
+ this.locals = new Map();
431
+ this.memo = new Map();
432
+ this.places = new Map();
433
+ this.visiting = new Set();
434
+ this.depth = 0;
435
+ for (const [key, e] of entities) {
436
+ if (!(key === root || key.startsWith(`${root}/`)) || !isResourceDeclarable(e))
437
+ continue;
438
+ const entity = e;
439
+ const scope = scopeOfKey(key);
440
+ if (entity.entityType === VARIABLE_TYPE && entity.props.address.startsWith("var.")) {
441
+ (this.vars.get(scope) ?? this.vars.set(scope, new Map()).get(scope)).set(entity.props.address.slice(4), entity);
442
+ }
443
+ else if (entity.entityType === LOCALS_TYPE) {
444
+ const into = this.locals.get(scope) ?? this.locals.set(scope, new Map()).get(scope);
445
+ for (const [name, value] of Object.entries(bodyOf(entity)))
446
+ into.set(name, value);
447
+ }
448
+ }
449
+ }
450
+ /** The root module's place. */
451
+ rootPlace() {
452
+ return this.placeAt(undefined, this.root, "", undefined);
453
+ }
454
+ placeAt(parent, scope, path, iteration) {
455
+ const hit = this.places.get(path === "" ? `\u0000${scope}` : path);
456
+ if (hit && hit.scope === scope)
457
+ return hit;
458
+ const place = { scope, path, ...(parent ? { parent } : {}), ...(iteration ? { iteration } : {}) };
459
+ this.places.set(path === "" ? `\u0000${scope}` : path, place);
460
+ return place;
461
+ }
462
+ /**
463
+ * The place an instance's scope names (`module.a["x"].module.b`, as
464
+ * `withInstanceNodes` carries it), or undefined when a call on the way is
465
+ * not a module call of this root.
466
+ */
467
+ placeOfInstanceScope(instanceScope) {
468
+ let place = this.rootPlace();
469
+ let rest = instanceScope;
470
+ while (rest !== "") {
471
+ const m = SEGMENT_RE.exec(rest);
472
+ if (!m)
473
+ return undefined;
474
+ rest = rest.slice(m[0].length);
475
+ const next = this.childPlace(place, m[1], m[2] === undefined ? undefined : instanceKeyValue(m[2]));
476
+ if (!next || isUnknown(next))
477
+ return undefined;
478
+ place = next;
479
+ }
480
+ return place;
481
+ }
482
+ /**
483
+ * The place of a block-level read of an entity-key scope: every expanded
484
+ * call on the way has an unknown iteration, since the block stands for all
485
+ * of its instances.
486
+ */
487
+ placeOfScope(scope) {
488
+ let place = this.rootPlace();
489
+ if (scope === this.root)
490
+ return place;
491
+ if (!scope.startsWith(`${this.root}/`))
492
+ return undefined;
493
+ for (const segment of scope.slice(this.root.length + 1).split("/")) {
494
+ if (!segment.startsWith("module."))
495
+ return undefined;
496
+ const name = segment.slice("module.".length);
497
+ const callKey = `${place.scope}/module.${name}`;
498
+ const call = this.entities.get(callKey);
499
+ if (!call || call.entityType !== MODULE_TYPE)
500
+ return undefined;
501
+ const how = expanded(bodyOf(call));
502
+ const pathSeg = `module.${name}`;
503
+ const path = place.path ? `${place.path}.${pathSeg}` : pathSeg;
504
+ const iteration = how === "for_each"
505
+ ? { each: new Unknown(prefixed(place, "each.key")) }
506
+ : how === "count" ? { count: new Unknown(prefixed(place, "count.index")) } : undefined;
507
+ place = this.placeAt(place, `${callKey}`, `${path}${how ? "[*]" : ""}`, iteration);
508
+ }
509
+ return place;
510
+ }
511
+ /** A module call's instance place, or an unknown when its key is not known; undefined when there is no such call. */
512
+ childPlace(place, name, key) {
513
+ const callKey = `${place.scope}/module.${name}`;
514
+ const call = this.entities.get(callKey);
515
+ if (!call || call.entityType !== MODULE_TYPE)
516
+ return undefined;
517
+ const body = bodyOf(call);
518
+ const how = expanded(body);
519
+ const seg = `module.${name}`;
520
+ if (!how) {
521
+ if (key !== undefined)
522
+ return new Unknown(prefixed(place, `${seg}[${JSON.stringify(key)}]`));
523
+ return this.placeAt(place, callKey, place.path ? `${place.path}.${seg}` : seg, undefined);
524
+ }
525
+ if (key === undefined)
526
+ return new Unknown(prefixed(place, seg));
527
+ const iteration = this.iterationOf(body, { place }, key);
528
+ const keyText = typeof key === "number" ? `[${key}]` : `[${JSON.stringify(key)}]`;
529
+ return this.placeAt(place, callKey, `${place.path ? `${place.path}.` : ""}${seg}${keyText}`, iteration);
530
+ }
531
+ /** The iteration of one instance of an expanded block, by its key. */
532
+ iterationOf(body, env, key) {
533
+ if ("count" in body)
534
+ return { count: typeof key === "number" ? key : new Unknown(prefixed(env.place, "count.index")) };
535
+ const all = this.value(body.for_each, { place: env.place });
536
+ if (isUnknown(all))
537
+ return { each: all };
538
+ if (Array.isArray(all))
539
+ return { each: { key, value: key } };
540
+ if (typeof all === "object" && all !== null && typeof key === "string" && key in all) {
541
+ return { each: { key, value: all[key] } };
542
+ }
543
+ return { each: new Unknown(prefixed(env.place, "each.key")) };
544
+ }
545
+ /** The block-level iteration of a block: unknown when it is expanded, none when it is not. */
546
+ blockIteration(body, place) {
547
+ const how = expanded(body);
548
+ if (how === "for_each")
549
+ return { each: new Unknown(prefixed(place, "each.key")) };
550
+ if (how === "count")
551
+ return { count: new Unknown(prefixed(place, "count.index")) };
552
+ return undefined;
553
+ }
554
+ /**
555
+ * A value from a parsed body (a literal, a hcl2json `"${...}"` string, or a
556
+ * list or map of those) evaluated in a place. Unknown parts stay
557
+ * {@link Unknown}; a map keeps its known entries beside them.
558
+ */
559
+ value(raw, env) {
560
+ if (this.depth > 64)
561
+ return new Unknown("(expression too deep)");
562
+ this.depth++;
563
+ try {
564
+ if (typeof raw === "string") {
565
+ if (!raw.includes("${") && !raw.includes("%{"))
566
+ return raw;
567
+ const expr = parseValueString(raw);
568
+ if (expr instanceof Unsupported)
569
+ return new Unknown(prefixed(env.place, expr.text));
570
+ return this.expr(expr, env);
571
+ }
572
+ if (Array.isArray(raw))
573
+ return raw.map((v) => this.value(v, env));
574
+ if (typeof raw === "object" && raw !== null) {
575
+ const out = {};
576
+ for (const [k, v] of Object.entries(raw)) {
577
+ let key = k;
578
+ if (k.includes("${"))
579
+ key = this.value(k, env);
580
+ if (typeof key !== "string")
581
+ return isUnknown(key) ? key : new Unknown(prefixed(env.place, k));
582
+ out[key] = this.value(v, env);
583
+ }
584
+ return out;
585
+ }
586
+ return raw;
587
+ }
588
+ finally {
589
+ this.depth--;
590
+ }
591
+ }
592
+ expr(e, env) {
593
+ switch (e.t) {
594
+ case "lit":
595
+ return e.v;
596
+ case "tpl": {
597
+ let out = "";
598
+ for (const p of e.parts) {
599
+ if (typeof p === "string") {
600
+ out += p;
601
+ continue;
602
+ }
603
+ const v = this.expr(p, env);
604
+ if (isUnknown(v))
605
+ return v;
606
+ if (typeof v === "string")
607
+ out += v;
608
+ else if (typeof v === "number" || typeof v === "boolean")
609
+ out += String(v);
610
+ else
611
+ return new Unknown(prefixed(env.place, e.text));
612
+ }
613
+ return out;
614
+ }
615
+ case "tuple":
616
+ return e.items.map((i) => this.expr(i, env));
617
+ case "object": {
618
+ const out = {};
619
+ for (const [k, v] of e.entries) {
620
+ const key = this.expr(k, env);
621
+ if (isUnknown(key))
622
+ return key;
623
+ if (typeof key !== "string" && typeof key !== "number")
624
+ return new Unknown(prefixed(env.place, "(object key)"));
625
+ out[String(key)] = this.expr(v, env);
626
+ }
627
+ return out;
628
+ }
629
+ case "cond": {
630
+ const c = this.expr(e.c, env);
631
+ if (isUnknown(c))
632
+ return c;
633
+ if (typeof c !== "boolean")
634
+ return new Unknown(prefixed(env.place, "(condition)"));
635
+ return this.expr(c ? e.a : e.b, env);
636
+ }
637
+ case "eq": {
638
+ const l = this.expr(e.l, env);
639
+ const r = this.expr(e.r, env);
640
+ const u = firstUnknown(l) ?? firstUnknown(r);
641
+ if (u)
642
+ return u;
643
+ return sameValue(l, r) !== e.negate;
644
+ }
645
+ case "call":
646
+ return this.call(e, env);
647
+ case "post":
648
+ return this.steps(this.expr(e.of, env), e.steps, env, e.text);
649
+ case "ref":
650
+ return this.ref(e, env);
651
+ }
652
+ }
653
+ call(e, env) {
654
+ const args = () => e.args.map((a) => this.expr(a, env));
655
+ if (e.name === "lookup" && (e.args.length === 2 || e.args.length === 3)) {
656
+ const [map, key, dflt] = args();
657
+ if (isUnknown(map))
658
+ return map;
659
+ if (isUnknown(key))
660
+ return key;
661
+ if (typeof map !== "object" || map === null || Array.isArray(map) || typeof key !== "string")
662
+ return new Unknown(prefixed(env.place, e.text));
663
+ if (key in map)
664
+ return map[key];
665
+ return e.args.length === 3 ? dflt : new Unknown(prefixed(env.place, e.text));
666
+ }
667
+ if (e.name === "toset" && e.args.length === 1) {
668
+ const [list] = args();
669
+ const u = firstUnknown(list);
670
+ if (u)
671
+ return u;
672
+ if (!Array.isArray(list))
673
+ return new Unknown(prefixed(env.place, e.text));
674
+ const set = list.every((v) => typeof v === "string") ? [...new Set(list)].sort() : [...list];
675
+ SETS.add(set);
676
+ return set;
677
+ }
678
+ if (e.name === "length" && e.args.length === 1) {
679
+ const [v] = args();
680
+ if (isUnknown(v))
681
+ return v;
682
+ if (Array.isArray(v))
683
+ return v.length;
684
+ if (typeof v === "object" && v !== null)
685
+ return Object.keys(v).length;
686
+ if (typeof v === "string")
687
+ return [...v].length;
688
+ return new Unknown(prefixed(env.place, e.text));
689
+ }
690
+ return new Unknown(prefixed(env.place, `${e.name}()`));
691
+ }
692
+ /** Apply traversal steps to a value. `text` names the whole traversal when a step does not apply. */
693
+ steps(v, steps, env, text) {
694
+ let cur = v;
695
+ for (const s of steps) {
696
+ if (isUnknown(cur))
697
+ return cur;
698
+ if ("splat" in s)
699
+ return new Unknown(prefixed(env.place, text));
700
+ let key;
701
+ if ("attr" in s)
702
+ key = s.attr;
703
+ else {
704
+ key = this.expr(s.index, env);
705
+ if (isUnknown(key))
706
+ return key;
707
+ }
708
+ if (Array.isArray(cur) && typeof key === "number" && key >= 0 && key < cur.length)
709
+ cur = cur[key];
710
+ else if (typeof cur === "object" && cur !== null && !Array.isArray(cur) && (typeof key === "string" || typeof key === "number") && String(key) in cur) {
711
+ cur = cur[String(key)];
712
+ }
713
+ else
714
+ return new Unknown(prefixed(env.place, text));
715
+ }
716
+ return cur;
717
+ }
718
+ ref(e, env) {
719
+ const { place } = env;
720
+ const unknown = () => new Unknown(prefixed(place, e.text));
721
+ const first = e.steps[0];
722
+ const firstAttr = first && "attr" in first ? first.attr : undefined;
723
+ switch (e.root) {
724
+ case "var":
725
+ return firstAttr === undefined ? unknown() : this.steps(this.variable(place, firstAttr), e.steps.slice(1), env, e.text);
726
+ case "local":
727
+ return firstAttr === undefined ? unknown() : this.steps(this.local(place, firstAttr), e.steps.slice(1), env, e.text);
728
+ case "each": {
729
+ const each = env.iteration?.each;
730
+ if (!each || (firstAttr !== "key" && firstAttr !== "value"))
731
+ return unknown();
732
+ if (isUnknown(each))
733
+ return new Unknown(prefixed(place, `each.${firstAttr}`));
734
+ return this.steps(firstAttr === "key" ? each.key : each.value, e.steps.slice(1), env, e.text);
735
+ }
736
+ case "count": {
737
+ const count = env.iteration?.count;
738
+ if (count === undefined || firstAttr !== "index" || e.steps.length !== 1)
739
+ return unknown();
740
+ return isUnknown(count) ? new Unknown(prefixed(place, "count.index")) : count;
741
+ }
742
+ case "module":
743
+ return firstAttr === undefined ? unknown() : this.moduleOutput(e, env, firstAttr);
744
+ case "data":
745
+ case "path":
746
+ case "terraform":
747
+ case "self":
748
+ return unknown();
749
+ default:
750
+ return firstAttr === undefined ? unknown() : this.resourceArgument(e, env, firstAttr);
751
+ }
752
+ }
753
+ /** `module.<call>[key]?.<output>...`. */
754
+ moduleOutput(e, env, name) {
755
+ let i = 1;
756
+ let key;
757
+ const idx = e.steps[1];
758
+ if (idx && "index" in idx) {
759
+ const k = this.expr(idx.index, env);
760
+ if (isUnknown(k))
761
+ return k;
762
+ if (typeof k !== "number" && typeof k !== "string")
763
+ return new Unknown(prefixed(env.place, e.text));
764
+ key = k;
765
+ i = 2;
766
+ }
767
+ const child = this.childPlace(env.place, name, key);
768
+ if (child === undefined)
769
+ return new Unknown(prefixed(env.place, e.text));
770
+ if (isUnknown(child))
771
+ return child;
772
+ const out = e.steps[i];
773
+ if (!out || !("attr" in out))
774
+ return new Unknown(prefixed(env.place, e.text));
775
+ const output = this.entities.get(`${child.scope}/output.${out.attr}`);
776
+ if (!output || output.entityType !== OUTPUT_TYPE)
777
+ return new Unknown(prefixed(env.place, e.text));
778
+ const body = bodyOf(output);
779
+ if (body.sensitive === true)
780
+ return new Unknown(prefixed(child, `output.${out.attr}`));
781
+ const memoKey = `out\u0000${child.path}\u0000${child.scope}\u0000${out.attr}`;
782
+ const v = this.guarded(memoKey, () => this.value(body.value, { place: child }), () => new Unknown(prefixed(child, `output.${out.attr}`)));
783
+ return this.steps(v, e.steps.slice(i + 1), env, e.text);
784
+ }
785
+ /** `<type>.<name>[key]?.<arg>...` in the same module: the argument as the block sets it. */
786
+ resourceArgument(e, env, name) {
787
+ const address = `${e.root}.${name}`;
788
+ const entity = this.entities.get(`${env.place.scope}/${address}`);
789
+ const unknown = () => new Unknown(prefixed(env.place, e.text));
790
+ if (!entity || entity.entityType !== RESOURCE_TYPE)
791
+ return unknown();
792
+ const body = bodyOf(entity);
793
+ let i = 1;
794
+ let iteration;
795
+ const how = expanded(body);
796
+ if (how) {
797
+ const idx = e.steps[1];
798
+ if (!idx || !("index" in idx))
799
+ return unknown();
800
+ const k = this.expr(idx.index, env);
801
+ if (isUnknown(k))
802
+ return k;
803
+ if (typeof k !== "number" && typeof k !== "string")
804
+ return unknown();
805
+ iteration = this.iterationOf(body, { place: env.place }, k);
806
+ i = 2;
807
+ }
808
+ const arg = e.steps[i];
809
+ if (!arg || !("attr" in arg) || !(arg.attr in body) || ["count", "for_each", "depends_on", "provider", "lifecycle"].includes(arg.attr))
810
+ return unknown();
811
+ const memoKey = `res\u0000${env.place.path}\u0000${env.place.scope}\u0000${address}\u0000${JSON.stringify(iteration ?? null, (_, v) => (isUnknown(v) ? `?${v.ref}` : v))}\u0000${arg.attr}`;
812
+ const v = this.guarded(memoKey, () => this.value(body[arg.attr], { place: env.place, ...(iteration ? { iteration } : {}) }), unknown);
813
+ return this.steps(v, e.steps.slice(i + 1), env, e.text);
814
+ }
815
+ /** A variable's value in a place. */
816
+ variable(place, name) {
817
+ const decl = this.vars.get(place.scope)?.get(name);
818
+ const unknown = () => new Unknown(prefixed(place, `var.${name}`));
819
+ if (!decl)
820
+ return unknown();
821
+ const body = bodyOf(decl);
822
+ if (body.sensitive === true)
823
+ return unknown();
824
+ return this.guarded(`var\u0000${place.path}\u0000${place.scope}\u0000${name}`, () => {
825
+ if (place.parent === undefined) {
826
+ const v = this.tfvars.has(name) ? this.tfvars.get(name) : body.default;
827
+ return v === undefined || holdsExpression(v) ? unknown() : v;
828
+ }
829
+ const call = this.entities.get(place.scope);
830
+ const callBody = bodyOf(call);
831
+ if (name in callBody)
832
+ return this.value(callBody[name], { place: place.parent, ...(place.iteration ? { iteration: place.iteration } : {}) });
833
+ return body.default === undefined || holdsExpression(body.default) ? unknown() : body.default;
834
+ }, unknown);
835
+ }
836
+ /** A local value in a place. */
837
+ local(place, name) {
838
+ const scoped = this.locals.get(place.scope);
839
+ if (!scoped?.has(name))
840
+ return new Unknown(prefixed(place, `local.${name}`));
841
+ return this.guarded(`local\u0000${place.path}\u0000${place.scope}\u0000${name}`, () => this.value(scoped.get(name), { place }), () => new Unknown(prefixed(place, `local.${name}`)));
842
+ }
843
+ /** Memoized, and unknown on a cycle. */
844
+ guarded(key, compute, onCycle) {
845
+ if (this.memo.has(key))
846
+ return this.memo.get(key);
847
+ if (this.visiting.has(key))
848
+ return onCycle();
849
+ this.visiting.add(key);
850
+ try {
851
+ const v = compute();
852
+ this.memo.set(key, v);
853
+ return v;
854
+ }
855
+ finally {
856
+ this.visiting.delete(key);
857
+ }
858
+ }
859
+ }
860
+ /**
861
+ * Terraform's `==` over two known values: the same type and the same value,
862
+ * with no conversion, so `"1" == 1` is false. Lists compare element by
863
+ * element and maps key by key.
864
+ */
865
+ function sameValue(a, b) {
866
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object")
867
+ return a === b;
868
+ if (Array.isArray(a) !== Array.isArray(b))
869
+ return false;
870
+ if (Array.isArray(a)) {
871
+ const bl = b;
872
+ return a.length === bl.length && a.every((x, i) => sameValue(x, bl[i]));
873
+ }
874
+ const ak = Object.keys(a);
875
+ const bo = b;
876
+ return ak.length === Object.keys(bo).length && ak.every((k) => k in bo && sameValue(a[k], bo[k]));
877
+ }
878
+ /** A reference named as Terraform prints it from the root: the module path in front. */
879
+ function prefixed(place, ref) {
880
+ return place.path ? `${place.path}.${ref}` : ref;
881
+ }
882
+ /** Whether a value still holds an expression. */
883
+ function holdsExpression(value) {
884
+ if (typeof value === "string")
885
+ return value.includes("${");
886
+ if (Array.isArray(value))
887
+ return value.some(holdsExpression);
888
+ if (typeof value === "object" && value !== null)
889
+ return Object.entries(value).some(([k, v]) => k.includes("${") || holdsExpression(v));
890
+ return false;
891
+ }
892
+ const isBlock = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
893
+ /** True when a value holds an interpolation, `${...}`, anywhere in it. */
894
+ export function interpolated(value, depth = 0) {
895
+ if (depth > 12)
896
+ return false;
897
+ if (typeof value === "string")
898
+ return value.includes("${");
899
+ if (Array.isArray(value))
900
+ return value.some((v) => interpolated(v, depth + 1));
901
+ if (isBlock(value))
902
+ return Object.values(value).some((v) => interpolated(v, depth + 1));
903
+ return false;
904
+ }
905
+ /**
906
+ * Evaluate the arguments of a block body that hold an expression, walking
907
+ * nested blocks and maps the way the catalog's literal view does.
908
+ */
909
+ export function evaluateArguments(body, evaluate) {
910
+ const stopped = {};
911
+ const walk = (obj, path, depth) => {
912
+ let out;
913
+ for (const [key, value] of Object.entries(obj)) {
914
+ if (depth > 12)
915
+ break;
916
+ const at = path ? `${path}.${key}` : key;
917
+ if (isBlock(value)) {
918
+ const inner = walk(value, at, depth + 1);
919
+ if (inner)
920
+ (out ?? (out = {}))[key] = inner;
921
+ }
922
+ else if (Array.isArray(value) && value.length > 0 && value.every(isBlock)) {
923
+ const inner = value.map((b, i) => walk(b, `${at}[${i}]`, depth + 1));
924
+ if (inner.some((x) => x !== undefined))
925
+ (out ?? (out = {}))[key] = inner.map((x) => x ?? {});
926
+ }
927
+ else if (interpolated(value)) {
928
+ const v = evaluate(value);
929
+ const u = firstUnknown(v);
930
+ if (u)
931
+ stopped[at] = u.ref;
932
+ else
933
+ (out ?? (out = {}))[key] = v;
934
+ }
935
+ }
936
+ return out;
937
+ };
938
+ const resolved = walk(body, "", 0);
939
+ return { ...(resolved ? { arguments: resolved } : {}), ...(Object.keys(stopped).length > 0 ? { stopped } : {}) };
940
+ }