@suss/contract-terraform 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ filterCalls: () => filterCalls,
34
+ filterTerms: () => filterTerms,
35
+ filterValuesFor: () => filterValuesFor,
36
+ parseFilterQuery: () => parseFilterQuery,
33
37
  terraformFileToSummaries: () => terraformFileToSummaries,
34
38
  terraformToSummaries: () => terraformToSummaries
35
39
  });
@@ -39,39 +43,394 @@ var import_node_path = __toESM(require("path"), 1);
39
43
  var import_hcl2_parser = __toESM(require("hcl2-parser"), 1);
40
44
  var import_semver = __toESM(require("semver"), 1);
41
45
  var import_behavioral_ir = require("@suss/behavioral-ir");
42
- function terraformToSummaries(source, sourceFile, options) {
43
- let parsed;
44
- try {
45
- const [read] = import_hcl2_parser.default.parseToObject(source);
46
- parsed = read;
47
- } catch {
46
+
47
+ // src/filterQuery.ts
48
+ var OPERATORS = ["!=", ">=", "<=", "=", ">", "<", ":"];
49
+ var KEYWORDS = /* @__PURE__ */ new Set(["AND", "OR", "NOT"]);
50
+ function filterValuesFor(query, key) {
51
+ return filterTerms(query).filter((term) => term.key === key && term.operator === "=").map((term) => term.value);
52
+ }
53
+ function filterTerms(query) {
54
+ if (query.type === "term") {
55
+ return [query];
56
+ }
57
+ if (query.type === "call") {
48
58
  return [];
49
59
  }
50
- const document = asRecord(parsed);
51
- if (document === null) {
60
+ if (query.type === "negation") {
61
+ return filterTerms(query.operand);
62
+ }
63
+ return query.operands.flatMap(filterTerms);
64
+ }
65
+ function filterCalls(query) {
66
+ if (query.type === "call") {
67
+ return [query];
68
+ }
69
+ if (query.type === "term") {
52
70
  return [];
53
71
  }
54
- const constraints = providerConstraints(document);
55
- const summaries = [];
56
- for (const [resourceType, label, body] of resourcesIn(document)) {
57
- for (const pack of options.packs) {
58
- const pattern = patternFor(pack, resourceType, constraints);
59
- if (pattern === void 0) {
60
- continue;
72
+ if (query.type === "negation") {
73
+ return filterCalls(query.operand);
74
+ }
75
+ return query.operands.flatMap(filterCalls);
76
+ }
77
+ function parseFilterQuery(source) {
78
+ const tokens = tokenize(source);
79
+ if (!tokens.ok) {
80
+ return { ok: false, reason: tokens.reason };
81
+ }
82
+ const reader = new TokenReader(tokens.tokens);
83
+ const query = reader.readExpression();
84
+ if (query === null) {
85
+ return { ok: false, reason: reader.reason };
86
+ }
87
+ if (!reader.atEnd()) {
88
+ return {
89
+ ok: false,
90
+ reason: `nothing joins the term at "${reader.rest()}"`
91
+ };
92
+ }
93
+ return { ok: true, query };
94
+ }
95
+ function tokenize(source) {
96
+ const tokens = [];
97
+ let at = 0;
98
+ while (at < source.length) {
99
+ const char = source[at];
100
+ if (/\s/.test(char) || char === ",") {
101
+ at += 1;
102
+ continue;
103
+ }
104
+ if (char === "(" || char === ")") {
105
+ tokens.push({ type: char === "(" ? "open" : "close", text: char });
106
+ at += 1;
107
+ continue;
108
+ }
109
+ if (char === '"' || char === "'") {
110
+ const quoted = readQuoted(source, at, char);
111
+ if (quoted === null) {
112
+ return { ok: false, reason: `a quote is never closed at ${at}` };
113
+ }
114
+ const previous = tokens[tokens.length - 1];
115
+ if (previous !== void 0 && isPartialKey(previous)) {
116
+ previous.text += quoted.value;
117
+ } else {
118
+ tokens.push({ type: "string", text: quoted.value });
61
119
  }
62
- summaries.push(
63
- ...summariesFor({ pattern, label, body, sourceFile, resourceType })
64
- );
120
+ at = quoted.next;
121
+ continue;
122
+ }
123
+ const operator = OPERATORS.find(
124
+ (candidate) => source.startsWith(candidate, at)
125
+ );
126
+ if (operator !== void 0) {
127
+ tokens.push({ type: "operator", text: operator });
128
+ at += operator.length;
129
+ continue;
65
130
  }
131
+ const word = readWord(source, at);
132
+ if (word === null) {
133
+ return { ok: false, reason: `nothing readable at "${char}"` };
134
+ }
135
+ tokens.push({ type: "word", text: word.value });
136
+ at = word.next;
66
137
  }
67
- return summaries;
138
+ return { ok: true, tokens };
139
+ }
140
+ function readQuoted(source, start, quote) {
141
+ let value = "";
142
+ let at = start + 1;
143
+ while (at < source.length) {
144
+ const char = source[at];
145
+ if (char === "\\" && at + 1 < source.length) {
146
+ value += source[at + 1];
147
+ at += 2;
148
+ continue;
149
+ }
150
+ if (char === quote) {
151
+ return { value, next: at + 1 };
152
+ }
153
+ value += char;
154
+ at += 1;
155
+ }
156
+ return null;
157
+ }
158
+ function isPartialKey(token) {
159
+ return token.type === "word" && token.text.endsWith(".");
160
+ }
161
+ function readWord(source, start) {
162
+ const match = /^[^\s(),="'!<>:]+/.exec(source.slice(start));
163
+ if (match === null) {
164
+ return null;
165
+ }
166
+ return { value: match[0], next: start + match[0].length };
167
+ }
168
+ var TokenReader = class {
169
+ constructor(tokens) {
170
+ this.tokens = tokens;
171
+ }
172
+ tokens;
173
+ at = 0;
174
+ /** What stopped the last read, for the caller to report. */
175
+ reason = "the filter states no comparison";
176
+ atEnd() {
177
+ return this.at >= this.tokens.length;
178
+ }
179
+ rest() {
180
+ return this.tokens.slice(this.at).map((token) => token.text).join(" ");
181
+ }
182
+ readExpression() {
183
+ return this.readJunction(
184
+ "or",
185
+ "OR",
186
+ () => this.readJunction("and", "AND", () => this.readUnary())
187
+ );
188
+ }
189
+ readJunction(operator, keyword, readOperand) {
190
+ const first = readOperand();
191
+ if (first === null) {
192
+ return null;
193
+ }
194
+ const operands = [first];
195
+ while (!this.atEnd()) {
196
+ const joined = this.keywordAhead(keyword);
197
+ if (!joined && !(operator === "and" && this.termAhead())) {
198
+ break;
199
+ }
200
+ if (joined) {
201
+ this.at += 1;
202
+ }
203
+ const next = readOperand();
204
+ if (next === null) {
205
+ return null;
206
+ }
207
+ operands.push(next);
208
+ }
209
+ return operands.length === 1 ? operands[0] : { type: "junction", operator, operands };
210
+ }
211
+ readUnary() {
212
+ if (this.keywordAhead("NOT")) {
213
+ this.at += 1;
214
+ const operand = this.readUnary();
215
+ return operand === null ? null : { type: "negation", operand };
216
+ }
217
+ return this.readPrimary();
218
+ }
219
+ readPrimary() {
220
+ const token = this.tokens[this.at];
221
+ if (token === void 0) {
222
+ this.reason = "the filter ends where a comparison should be";
223
+ return null;
224
+ }
225
+ if (token.type === "open") {
226
+ this.at += 1;
227
+ const inner = this.readExpression();
228
+ if (inner === null) {
229
+ return null;
230
+ }
231
+ if (this.tokens[this.at]?.type !== "close") {
232
+ this.reason = "a parenthesis is never closed";
233
+ return null;
234
+ }
235
+ this.at += 1;
236
+ return inner;
237
+ }
238
+ if (token.type === "word" && this.tokens[this.at + 1]?.type === "open") {
239
+ return this.readCall();
240
+ }
241
+ return this.readTerm();
242
+ }
243
+ /**
244
+ * A call where a comparison would be. Cloud Monitoring writes an SLO
245
+ * burn-rate condition that way, and the call says what the condition
246
+ * is about instead of any comparison.
247
+ */
248
+ readCall() {
249
+ const name = this.tokens[this.at];
250
+ this.at += 2;
251
+ const args = [];
252
+ while (!this.atEnd() && this.tokens[this.at]?.type !== "close") {
253
+ const argument = this.tokens[this.at];
254
+ if (argument.type === "word" || argument.type === "string") {
255
+ args.push(argument.text);
256
+ }
257
+ this.at += 1;
258
+ }
259
+ if (this.atEnd()) {
260
+ this.reason = `the call to "${name.text}" is never closed`;
261
+ return null;
262
+ }
263
+ this.at += 1;
264
+ return { type: "call", name: name.text, arguments: args };
265
+ }
266
+ readTerm() {
267
+ const key = this.tokens[this.at];
268
+ const operator = this.tokens[this.at + 1];
269
+ const value = this.tokens[this.at + 2];
270
+ if (key === void 0 || key.type !== "word") {
271
+ this.reason = `"${key?.text ?? ""}" is not a key`;
272
+ return null;
273
+ }
274
+ if (operator === void 0 || operator.type !== "operator") {
275
+ this.reason = `"${key.text}" is compared to nothing`;
276
+ return null;
277
+ }
278
+ if (value === void 0 || value.type !== "word" && value.type !== "string") {
279
+ this.reason = `"${key.text}" is compared to no value`;
280
+ return null;
281
+ }
282
+ this.at += 3;
283
+ return {
284
+ type: "term",
285
+ key: key.text,
286
+ operator: operator.text,
287
+ value: value.text
288
+ };
289
+ }
290
+ /** Whether the next token is this keyword rather than a key. */
291
+ keywordAhead(keyword) {
292
+ const token = this.tokens[this.at];
293
+ return token !== void 0 && token.type === "word" && token.text === keyword;
294
+ }
295
+ /** Whether a new comparison starts here, with no keyword joining it. */
296
+ termAhead() {
297
+ const token = this.tokens[this.at];
298
+ if (token === void 0) {
299
+ return false;
300
+ }
301
+ if (token.type === "open") {
302
+ return true;
303
+ }
304
+ return token.type === "word" && !KEYWORDS.has(token.text);
305
+ }
306
+ };
307
+
308
+ // src/references.ts
309
+ var SUB_TOKEN = /\$\{([^}]*)\}/g;
310
+ var RESOURCE_ATTRIBUTE = /^([A-Za-z][\w-]*)\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w-]*)$/;
311
+ var LOCAL_VALUE = /^local\.([A-Za-z_][\w-]*)$/;
312
+ var LOCALS = "local";
313
+ var CHAIN_LIMIT = 4;
314
+ function referenceScope(resources, locals = []) {
315
+ const scope = /* @__PURE__ */ new Map();
316
+ for (const [resourceType, label, body] of resources) {
317
+ const address = `${resourceType}.${label}`;
318
+ if (!scope.has(address)) {
319
+ scope.set(address, body);
320
+ }
321
+ }
322
+ const stated = {};
323
+ for (const block of locals) {
324
+ for (const [name, value] of Object.entries(block)) {
325
+ if (!(name in stated)) {
326
+ stated[name] = value;
327
+ }
328
+ }
329
+ }
330
+ scope.set(LOCALS, stated);
331
+ return scope;
332
+ }
333
+ function resolveReferences(value, scope) {
334
+ return expand(value, scope, []) ?? value;
335
+ }
336
+ function expand(value, scope, resolving) {
337
+ let cycled = false;
338
+ const expanded = value.replace(SUB_TOKEN, (written, inner) => {
339
+ const reference = inner.trim();
340
+ if (resolving.includes(reference)) {
341
+ cycled = true;
342
+ return written;
343
+ }
344
+ const stated = statedValue(reference, scope);
345
+ if (stated === null || resolving.length >= CHAIN_LIMIT) {
346
+ return written;
347
+ }
348
+ const nested = expand(stated, scope, [...resolving, reference]);
349
+ if (nested === null) {
350
+ cycled = true;
351
+ return written;
352
+ }
353
+ return nested;
354
+ });
355
+ return cycled ? null : expanded;
356
+ }
357
+ function statedValue(reference, scope) {
358
+ const local = LOCAL_VALUE.exec(reference);
359
+ if (local !== null) {
360
+ const stated2 = scope.get(LOCALS)?.[local[1]];
361
+ return typeof stated2 === "string" ? stated2 : null;
362
+ }
363
+ const parsed = RESOURCE_ATTRIBUTE.exec(reference);
364
+ if (parsed === null) {
365
+ return null;
366
+ }
367
+ const [, resourceType, label, attribute] = parsed;
368
+ const stated = scope.get(`${resourceType}.${label}`)?.[attribute];
369
+ return typeof stated === "string" ? stated : null;
370
+ }
371
+
372
+ // src/index.ts
373
+ function terraformToSummaries(source, sourceFile, options) {
374
+ return summariesForFiles([{ source, sourceFile }], options);
68
375
  }
69
376
  function terraformFileToSummaries(target, options) {
70
377
  const files = import_node_fs.default.statSync(target).isDirectory() ? import_node_fs.default.readdirSync(target).filter((name) => name.endsWith(".tf")).map((name) => import_node_path.default.join(target, name)) : [target];
71
- return files.flatMap(
72
- (file) => terraformToSummaries(import_node_fs.default.readFileSync(file, "utf8"), file, options)
378
+ return summariesForFiles(
379
+ files.map((file) => ({
380
+ source: import_node_fs.default.readFileSync(file, "utf8"),
381
+ sourceFile: file
382
+ })),
383
+ options
73
384
  );
74
385
  }
386
+ function summariesForFiles(files, options) {
387
+ const parsed = files.map((file) => parseSource(file)).filter((file) => file !== null);
388
+ const scope = referenceScope(
389
+ parsed.flatMap((file) => file.resources),
390
+ parsed.flatMap((file) => file.locals)
391
+ );
392
+ const summaries = [];
393
+ for (const file of parsed) {
394
+ for (const [resourceType, label, body] of file.resources) {
395
+ for (const pack of options.packs) {
396
+ const pattern = patternFor(pack, resourceType, file.constraints);
397
+ if (pattern === void 0) {
398
+ continue;
399
+ }
400
+ summaries.push(
401
+ ...summariesFor({
402
+ pattern,
403
+ label,
404
+ body,
405
+ sourceFile: file.sourceFile,
406
+ resourceType,
407
+ scope
408
+ })
409
+ );
410
+ }
411
+ }
412
+ }
413
+ return summaries;
414
+ }
415
+ function parseSource(file) {
416
+ let read;
417
+ try {
418
+ const [parsed] = import_hcl2_parser.default.parseToObject(file.source);
419
+ read = parsed;
420
+ } catch {
421
+ return null;
422
+ }
423
+ const document = asRecord(read);
424
+ if (document === null) {
425
+ return null;
426
+ }
427
+ return {
428
+ sourceFile: file.sourceFile,
429
+ constraints: providerConstraints(document),
430
+ resources: resourcesIn(document),
431
+ locals: localsIn(document)
432
+ };
433
+ }
75
434
  function providerConstraints(document) {
76
435
  const constraints = /* @__PURE__ */ new Map();
77
436
  for (const block of arrayOf(document.terraform)) {
@@ -110,22 +469,26 @@ function patternFor(pack, resourceType, constraints) {
110
469
  }
111
470
  });
112
471
  }
472
+ var READERS = {
473
+ storage: (site, boundary) => {
474
+ const types = fieldTypes(site.body, boundary);
475
+ return keyedShapes(site.body, boundary).map(
476
+ (shape) => storageSummary({ ...site, boundary, shape, types })
477
+ );
478
+ },
479
+ "message-bus": (site, boundary) => [busSummary({ ...site, boundary })],
480
+ metric: (site, boundary) => [metricSummary({ ...site, boundary })],
481
+ "metric-reading": (site, boundary) => readingSummaries({ ...site, boundary })
482
+ };
113
483
  function summariesFor(opts) {
114
- const { pattern } = opts;
115
- if (pattern.boundary.kind === "message-bus") {
116
- return [busSummary({ ...opts, boundary: pattern.boundary })];
117
- }
118
- const boundary = pattern.boundary;
119
- const types = fieldTypes(opts.body, boundary);
120
- return keyedShapes(opts.body, boundary).map(
121
- (shape) => storageSummary({ ...opts, boundary, shape, types })
122
- );
484
+ const { pattern, ...site } = opts;
485
+ const read = READERS[pattern.boundary.kind];
486
+ return read(site, pattern.boundary);
123
487
  }
124
488
  function storageSummary(opts) {
125
489
  const { boundary, label, shape, types } = opts;
126
490
  const address = `${opts.resourceType}.${label}`;
127
- const declaredName = boundary.nameAttribute === void 0 ? null : stringOf(opts.body[boundary.nameAttribute]);
128
- const physicalTable = declaredName === null ? null : (0, import_behavioral_ir.namePatternFromSub)(declaredName);
491
+ const physicalTable = boundary.nameAttribute === void 0 ? null : namePattern(opts.body[boundary.nameAttribute], opts.scope);
129
492
  return {
130
493
  kind: "library",
131
494
  location: {
@@ -169,8 +532,7 @@ function storageSummary(opts) {
169
532
  }
170
533
  function busSummary(opts) {
171
534
  const { boundary, label } = opts;
172
- const declaredName = boundary.nameAttribute === void 0 ? null : stringOf(opts.body[boundary.nameAttribute]);
173
- const physicalName = declaredName === null ? null : (0, import_behavioral_ir.namePatternFromSub)(declaredName);
535
+ const physicalName = boundary.nameAttribute === void 0 ? null : namePattern(opts.body[boundary.nameAttribute], opts.scope);
174
536
  return {
175
537
  kind: "library",
176
538
  location: {
@@ -200,6 +562,132 @@ function busSummary(opts) {
200
562
  }
201
563
  };
202
564
  }
565
+ var NAME_HOLE = "{name}";
566
+ function metricSummary(opts) {
567
+ const { boundary } = opts;
568
+ const declaredName = namePattern(
569
+ opts.body[boundary.nameAttribute],
570
+ opts.scope
571
+ );
572
+ const metricType = declaredName === null ? null : boundary.metricTypeTemplate.replace(NAME_HOLE, declaredName);
573
+ return {
574
+ kind: "library",
575
+ location: {
576
+ file: opts.sourceFile,
577
+ range: { start: 1, end: 1 },
578
+ exportName: null
579
+ },
580
+ identity: {
581
+ name: `${opts.resourceType}.${opts.label}`,
582
+ exportPath: null,
583
+ boundaryBinding: (0, import_behavioral_ir.metricBinding)({
584
+ recognition: "terraform",
585
+ metricSystem: boundary.metricSystem,
586
+ metricType
587
+ })
588
+ },
589
+ inputs: [],
590
+ transitions: [],
591
+ gaps: [],
592
+ confidence: { source: "declared", level: "high" },
593
+ metadata: { metricContract: metricContract(opts.body, boundary) }
594
+ };
595
+ }
596
+ function metricContract(body, boundary) {
597
+ const values = meaningOf(body, boundary.values);
598
+ const accumulates = meaningOf(body, boundary.accumulates);
599
+ return {
600
+ ...values !== void 0 ? { values } : {},
601
+ ...accumulates !== void 0 ? { accumulates } : {}
602
+ };
603
+ }
604
+ function readingSummaries(opts) {
605
+ const { boundary } = opts;
606
+ const summaries = [];
607
+ for (const reading of blocksAt(opts.body, boundary.readingBlocks)) {
608
+ const query = stringOf(valueAt(reading, boundary.queryAttribute));
609
+ for (const metricType of metricTypesIn(
610
+ query,
611
+ boundary.queryIdentityKey,
612
+ opts.scope
613
+ )) {
614
+ summaries.push({
615
+ kind: "consumer",
616
+ location: {
617
+ file: opts.sourceFile,
618
+ range: { start: 1, end: 1 },
619
+ exportName: null
620
+ },
621
+ identity: {
622
+ name: `${opts.resourceType}.${opts.label}#${summaries.length}`,
623
+ exportPath: null,
624
+ boundaryBinding: (0, import_behavioral_ir.metricBinding)({
625
+ recognition: "terraform",
626
+ metricSystem: boundary.metricSystem,
627
+ metricType
628
+ })
629
+ },
630
+ inputs: [],
631
+ transitions: [],
632
+ gaps: [],
633
+ confidence: { source: "declared", level: "high" },
634
+ metadata: { metricReading: metricReading(reading, boundary) }
635
+ });
636
+ }
637
+ }
638
+ return summaries;
639
+ }
640
+ function metricTypesIn(query, identityKey, scope) {
641
+ if (query === null) {
642
+ return [null];
643
+ }
644
+ const parsed = parseFilterQuery(query);
645
+ if (!parsed.ok) {
646
+ return [null];
647
+ }
648
+ const found = filterValuesFor(parsed.query, identityKey).map((value) => namePattern(value, scope)).filter((value) => value !== null);
649
+ return found.length === 0 ? [null] : found;
650
+ }
651
+ function metricReading(reading, boundary) {
652
+ const compares = boundary.comparesTo;
653
+ const comparesTo = compares !== void 0 && valueAt(reading, compares.attribute) !== void 0 ? compares.whenSet : void 0;
654
+ const reduces = boundary.reducesTo;
655
+ const reducesTo = meaningOf(reading, reduces);
656
+ return {
657
+ ...comparesTo !== void 0 ? { comparesTo } : {},
658
+ ...reducesTo !== void 0 ? { reducesTo } : {},
659
+ ...reduces === void 0 ? {} : { reduction: { setting: reduces.attribute, leaves: reduces.means } }
660
+ };
661
+ }
662
+ function meaningOf(body, spec) {
663
+ if (spec === void 0) {
664
+ return void 0;
665
+ }
666
+ const stated = stringOf(valueAt(body, spec.attribute));
667
+ return stated === null ? void 0 : spec.means[stated];
668
+ }
669
+ function valueAt(body, path2) {
670
+ const steps = path2.split(".");
671
+ const last = steps.pop();
672
+ let current = body;
673
+ for (const step of steps) {
674
+ const nested = arrayOf(current[step])[0];
675
+ current = asRecord(nested);
676
+ if (current === null) {
677
+ return void 0;
678
+ }
679
+ }
680
+ return current[last];
681
+ }
682
+ function blocksAt(body, blocks) {
683
+ let found = [body];
684
+ for (const block of blocks) {
685
+ found = found.flatMap(
686
+ (record) => arrayOf(record[block]).map(asRecord).filter((nested) => nested !== null)
687
+ );
688
+ }
689
+ return found;
690
+ }
203
691
  function keyedShapes(body, boundary) {
204
692
  if (boundary.identifies === void 0) {
205
693
  return [{ accessPath: null, keyFields: [], serves: null }];
@@ -264,6 +752,16 @@ function fieldTypes(body, boundary) {
264
752
  }
265
753
  return types;
266
754
  }
755
+ function localsIn(document) {
756
+ const found = [];
757
+ for (const block of arrayOf(document.locals)) {
758
+ const stated = asRecord(block);
759
+ if (stated !== null) {
760
+ found.push(stated);
761
+ }
762
+ }
763
+ return found;
764
+ }
267
765
  function resourcesIn(document) {
268
766
  const found = [];
269
767
  for (const resource of arrayOf(document.resource)) {
@@ -290,6 +788,11 @@ function resourcesIn(document) {
290
788
  }
291
789
  return found;
292
790
  }
791
+ function namePattern(value, scope) {
792
+ return (0, import_behavioral_ir.namePatternFromSub)(
793
+ typeof value === "string" ? resolveReferences(value, scope) : value
794
+ );
795
+ }
293
796
  function arrayOf(value) {
294
797
  if (value === void 0 || value === null) {
295
798
  return [];
@@ -304,6 +807,10 @@ function stringOf(value) {
304
807
  }
305
808
  // Annotate the CommonJS export names for ESM import in node:
306
809
  0 && (module.exports = {
810
+ filterCalls,
811
+ filterTerms,
812
+ filterValuesFor,
813
+ parseFilterQuery,
307
814
  terraformFileToSummaries,
308
815
  terraformToSummaries
309
816
  });