@telorun/templating 0.23.0 → 0.24.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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/builtins.d.ts +8 -0
  3. package/dist/builtins.d.ts.map +1 -1
  4. package/dist/builtins.js +13 -0
  5. package/dist/cel/analyze.d.ts +4 -0
  6. package/dist/cel/analyze.d.ts.map +1 -1
  7. package/dist/cel/analyze.js +9 -0
  8. package/dist/cel/catalog.d.ts.map +1 -1
  9. package/dist/cel/catalog.js +12 -4
  10. package/dist/cel/compile.d.ts +4 -26
  11. package/dist/cel/compile.d.ts.map +1 -1
  12. package/dist/cel/compile.js +3 -88
  13. package/dist/cel/interpolation-holes.d.ts +43 -0
  14. package/dist/cel/interpolation-holes.d.ts.map +1 -0
  15. package/dist/cel/interpolation-holes.js +121 -0
  16. package/dist/cel/walk.d.ts +7 -28
  17. package/dist/cel/walk.d.ts.map +1 -1
  18. package/dist/cel/walk.js +7 -39
  19. package/dist/engine.d.ts +14 -0
  20. package/dist/engine.d.ts.map +1 -1
  21. package/dist/engines/cel.d.ts +7 -0
  22. package/dist/engines/cel.d.ts.map +1 -1
  23. package/dist/engines/cel.js +29 -12
  24. package/dist/engines/hole-analysis.d.ts +23 -0
  25. package/dist/engines/hole-analysis.d.ts.map +1 -0
  26. package/dist/engines/hole-analysis.js +66 -0
  27. package/dist/engines/interpolate.d.ts +13 -0
  28. package/dist/engines/interpolate.d.ts.map +1 -0
  29. package/dist/engines/interpolate.js +123 -0
  30. package/dist/engines/sql.d.ts +3 -3
  31. package/dist/engines/sql.d.ts.map +1 -1
  32. package/dist/engines/sql.js +24 -58
  33. package/dist/index.d.ts +6 -4
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +4 -2
  36. package/dist/sentinel.d.ts +4 -5
  37. package/dist/sentinel.d.ts.map +1 -1
  38. package/dist/sentinel.js +6 -14
  39. package/package.json +2 -2
  40. package/src/builtins.ts +14 -0
  41. package/src/cel/analyze.ts +12 -0
  42. package/src/cel/catalog.ts +14 -4
  43. package/src/cel/compile.ts +4 -92
  44. package/src/cel/interpolation-holes.ts +138 -0
  45. package/src/cel/walk.ts +8 -54
  46. package/src/engine.ts +16 -0
  47. package/src/engines/cel.ts +36 -14
  48. package/src/engines/hole-analysis.ts +96 -0
  49. package/src/engines/interpolate.ts +139 -0
  50. package/src/engines/sql.ts +26 -67
  51. package/src/index.ts +12 -7
  52. package/src/sentinel.ts +6 -14
@@ -1,6 +1,7 @@
1
1
  import { formatLocale } from "d3-format";
2
2
  import { RE2JS } from "re2js";
3
3
  import { v1, v3, v4, v5, v6, v7, validate as uuidValidate, version as uuidVersion } from "uuid";
4
+ import { PLAIN_ENCODINGS } from "@telorun/sdk";
4
5
 
5
6
  /** Host-injected functions that need platform APIs the templating package must
6
7
  * not import directly (Node `crypto` / `Buffer`), keeping it browser-safe. The
@@ -1100,15 +1101,24 @@ export const CEL_FUNCTIONS: readonly CelFunctionDoc[] = [
1100
1101
  // so an expiry could be computed and not stored. Semantics follow cel-go
1101
1102
  // exactly — RFC 3339 and epoch SECONDS — so `int(timestamp)` and
1102
1103
  // `timestamp(int)` round-trip in one unit.
1104
+ //
1105
+ // `string(duration)` is cel-spec's too, and cel-js omits it: seconds with a
1106
+ // trimmed fraction, the `Telo.Duration` plain encoding, so a duration renders
1107
+ // one way whether it is interpolated or serialized.
1103
1108
  {
1104
1109
  name: "string",
1105
- signature: "string(timestamp): string",
1106
- register: ["string(google.protobuf.Timestamp): string"],
1110
+ signature: "string(timestamp | duration): string",
1111
+ register: [
1112
+ "string(google.protobuf.Timestamp): string",
1113
+ "string(google.protobuf.Duration): string",
1114
+ ],
1107
1115
  category: "conversion",
1108
- summary: "Format an instant as RFC 3339 (ISO-8601, UTC).",
1116
+ summary:
1117
+ "Format an instant as RFC 3339 (ISO-8601, UTC), or a duration as seconds with a trimmed fraction (`5400s`, `1.5s`).",
1109
1118
  deterministic: true,
1110
1119
  hostBacked: false,
1111
- build: () => (t: Date) => t.toISOString(),
1120
+ build: () => (value: unknown) =>
1121
+ value instanceof Date ? value.toISOString() : PLAIN_ENCODINGS["cel-duration"]!.encode(value),
1112
1122
  },
1113
1123
  {
1114
1124
  name: "int",
@@ -1,12 +1,9 @@
1
- import { isCompiledValue, type CompiledValue } from "@telorun/sdk";
1
+ import type { CompiledValue } from "@telorun/sdk";
2
2
  import type { ASTNode, Environment } from "@marcbachmann/cel-js";
3
3
  import { extractAccessChains } from "./analyze.js";
4
4
  import { CEL_FUNCTIONS } from "./catalog.js";
5
5
  import { resolveModuleCalls } from "./module-call.js";
6
6
 
7
- export const TEMPLATE_REGEX = /\$\{\{\s*([^}]+?)\s*\}\}/g;
8
- export const EXACT_TEMPLATE_REGEX = /^\s*\$\{\{\s*([^}]+?)\s*\}\}\s*$/;
9
-
10
7
  /** Root variable identifiers an expression reads, from its parsed AST — the
11
8
  * first element of every member-access chain (`self.table` → `self`). Returns
12
9
  * undefined when the parse result carries no AST so consumers can tell "no
@@ -41,9 +38,9 @@ function callsNonDeterministic(root: ASTNode): boolean {
41
38
  return visit(root);
42
39
  }
43
40
 
44
- /** Compile a single CEL expression (no `${{ }}` wrapping) into a CompiledValue.
45
- * Throws on syntax errors. Used by the `!cel` engine where the entire tagged
46
- * scalar is treated as one expression.
41
+ /** Compile a single CEL expression into a CompiledValue. Throws on syntax
42
+ * errors. The `!cel` engine compiles its whole scalar with it, and the tags
43
+ * with holes compile each hole.
47
44
  *
48
45
  * `moduleNames` are the declaring module's own names; a call whose receiver is
49
46
  * one of them resolves to a late-bound module call HERE, on the parsed tree, so
@@ -67,88 +64,3 @@ export function compileExpression(
67
64
  call: (ctx: Record<string, unknown>) => fn(ctx),
68
65
  };
69
66
  }
70
-
71
- /** Compile a string that may contain `${{ }}`-delimited CEL segments. If the
72
- * string is exactly one expression, returns a single CompiledValue. If it
73
- * contains interpolations, returns a CompiledValue that joins literal parts
74
- * with stringified expression results. If no expressions are present, returns
75
- * the input string unchanged. Throws on CEL syntax errors. */
76
- export function compileString(
77
- s: string,
78
- env: Environment,
79
- moduleNames?: ReadonlySet<string>,
80
- ): unknown {
81
- if (!s.includes("${{")) return s;
82
-
83
- const exact = s.match(EXACT_TEMPLATE_REGEX);
84
- if (exact) {
85
- return compileExpression(exact[1].trim(), env, moduleNames);
86
- }
87
-
88
- const parts: Array<string | CompiledValue> = [];
89
- let last = 0;
90
- for (const m of s.matchAll(TEMPLATE_REGEX)) {
91
- if (m.index! > last) parts.push(s.slice(last, m.index));
92
- parts.push(compileExpression(m[1].trim(), env, moduleNames));
93
- last = m.index! + m[0].length;
94
- }
95
- if (last < s.length) parts.push(s.slice(last));
96
-
97
- const refs = new Set<string>();
98
- const calls = new Set<string>();
99
- let volatile = false;
100
- for (const p of parts) {
101
- if (typeof p === "string") continue;
102
- if (p.refs) for (const r of p.refs) refs.add(r);
103
- if (p.calls) for (const c of p.calls) calls.add(c);
104
- if (p.volatile) volatile = true;
105
- }
106
-
107
- return {
108
- __compiled: true,
109
- source: s,
110
- parts,
111
- refs: [...refs],
112
- calls: [...calls],
113
- ...(volatile ? { volatile: true as const } : {}),
114
- call: (ctx: Record<string, unknown>) =>
115
- parts.map((p) => (typeof p === "string" ? p : String(p.call(ctx) ?? ""))).join(""),
116
- } satisfies CompiledValue;
117
- }
118
-
119
- /** Split an interpolated value into literal fragments and the evaluated values
120
- * of its embedded expressions, instead of joining them into one string. Lets a
121
- * consumer emit its own placeholders between fragments and bind the values
122
- * separately (e.g. parameterized SQL). The invariant
123
- * `fragments.length === values.length + 1` always holds.
124
- *
125
- * - plain string (no `${{ }}`) → `{ fragments: [s], values: [] }`
126
- * - bare single expression `${{ x }}` → `{ fragments: ["", ""], values: [x] }`
127
- * - interpolated `"a ${{ x }} b"` → `{ fragments: ["a ", " b"], values: [x] }`
128
- */
129
- export function toParameterized(
130
- value: unknown,
131
- ctx: Record<string, unknown>,
132
- ): { fragments: string[]; values: unknown[] } {
133
- if (typeof value === "string") return { fragments: [value], values: [] };
134
- if (!isCompiledValue(value)) {
135
- throw new Error("toParameterized expects a string or CompiledValue");
136
- }
137
- if (!value.parts) {
138
- return { fragments: ["", ""], values: [value.call(ctx)] };
139
- }
140
- const fragments: string[] = [];
141
- const values: unknown[] = [];
142
- let current = "";
143
- for (const p of value.parts) {
144
- if (typeof p === "string") {
145
- current += p;
146
- } else {
147
- fragments.push(current);
148
- current = "";
149
- values.push(p.call(ctx));
150
- }
151
- }
152
- fragments.push(current);
153
- return { fragments, values };
154
- }
@@ -0,0 +1,138 @@
1
+ /** One `${{ expr }}` hole in a scalar. Offsets index the scalar's source. */
2
+ export interface InterpolationHole {
3
+ /** Offset of the opening `${{`. */
4
+ readonly start: number;
5
+ /** Offset just past the closing `}}`. */
6
+ readonly end: number;
7
+ /** The expression, trimmed of the whitespace inside the delimiters. */
8
+ readonly expr: string;
9
+ /** Offset of {@link expr} within the source. */
10
+ readonly exprStart: number;
11
+ }
12
+
13
+ export type HoleReading =
14
+ | { readonly ok: true; readonly holes: readonly InterpolationHole[] }
15
+ | { readonly ok: false; readonly offset: number; readonly message: string };
16
+
17
+ /** How a scalar's text relates to holes: none at all, exactly one hole with only
18
+ * whitespace around it, holes among text, or a `${{` that opens no readable
19
+ * hole. */
20
+ export type InterpolationShape = "none" | "lone-hole" | "interpolated" | "malformed";
21
+
22
+ const OPEN = "${{";
23
+
24
+ /**
25
+ * Every `${{ expr }}` hole in `source` — the one hole grammar every tag with
26
+ * holes (`!interpolate`, `!sql`) and the untagged-interpolation migration read.
27
+ *
28
+ * A hole opens at `${{` and closes at the first `}}` that is outside a CEL
29
+ * string literal and outside any `{` the expression itself opened, so a map
30
+ * literal or a string holding braces is read whole. String literals follow CEL's
31
+ * lexical grammar: `'`, `"`, their triple-quoted forms, and the `r`/`b` prefixes,
32
+ * where a raw string takes no escapes. Outside a hole nothing is special but
33
+ * `${{`; a literal `${{` is written as a hole yielding it (`${{ '${{' }}`).
34
+ *
35
+ * A hole that never closes is a reading failure at its opening offset, never a
36
+ * guess at where it meant to end.
37
+ */
38
+ export function readInterpolationHoles(source: string): HoleReading {
39
+ const holes: InterpolationHole[] = [];
40
+ let from = 0;
41
+ for (;;) {
42
+ const start = source.indexOf(OPEN, from);
43
+ if (start === -1) return { ok: true, holes };
44
+ const close = closingOffset(source, start + OPEN.length);
45
+ if (close === undefined) {
46
+ return {
47
+ ok: false,
48
+ offset: start,
49
+ message: `the hole opened at offset ${start} never closes — a hole ends at the first '}}' outside a string literal and outside any braces it opened`,
50
+ };
51
+ }
52
+ const body = source.slice(start + OPEN.length, close);
53
+ const lead = body.length - body.trimStart().length;
54
+ holes.push({
55
+ start,
56
+ end: close + 2,
57
+ expr: body.trim(),
58
+ exprStart: start + OPEN.length + lead,
59
+ });
60
+ from = close + 2;
61
+ }
62
+ }
63
+
64
+ /** The shape of `source` under {@link readInterpolationHoles}. */
65
+ export function interpolationShape(source: string): InterpolationShape {
66
+ if (!source.includes(OPEN)) return "none";
67
+ const reading = readInterpolationHoles(source);
68
+ if (!reading.ok) return "malformed";
69
+ const [only, ...rest] = reading.holes;
70
+ if (!only) return "none";
71
+ const lone =
72
+ rest.length === 0 &&
73
+ source.slice(0, only.start).trim() === "" &&
74
+ source.slice(only.end).trim() === "";
75
+ return lone ? "lone-hole" : "interpolated";
76
+ }
77
+
78
+ /** The literal text between holes: always `holes.length + 1` fragments. */
79
+ export function literalFragments(source: string, holes: readonly InterpolationHole[]): string[] {
80
+ const out: string[] = [];
81
+ let last = 0;
82
+ for (const hole of holes) {
83
+ out.push(source.slice(last, hole.start));
84
+ last = hole.end;
85
+ }
86
+ out.push(source.slice(last));
87
+ return out;
88
+ }
89
+
90
+ /** Offset of the `}}` closing a hole whose body starts at `from`. */
91
+ function closingOffset(source: string, from: number): number | undefined {
92
+ let depth = 0;
93
+ let i = from;
94
+ while (i < source.length) {
95
+ const c = source[i]!;
96
+ if (c === "'" || c === '"') {
97
+ const after = skipString(source, i);
98
+ if (after === undefined) return undefined;
99
+ i = after;
100
+ continue;
101
+ }
102
+ if (c === "{") depth++;
103
+ else if (c === "}") {
104
+ if (depth === 0) return source[i + 1] === "}" ? i : undefined;
105
+ depth--;
106
+ }
107
+ i++;
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ /** Offset just past the string literal whose opening quote is at `quoteAt`. */
113
+ function skipString(source: string, quoteAt: number): number | undefined {
114
+ const quote = source[quoteAt]!;
115
+ const raw = /[rR]/.test(literalPrefix(source, quoteAt));
116
+ const triple = source.startsWith(quote.repeat(3), quoteAt);
117
+ const delimiter = triple ? quote.repeat(3) : quote;
118
+ let i = quoteAt + delimiter.length;
119
+ while (i < source.length) {
120
+ if (!raw && source[i] === "\\") {
121
+ i += 2;
122
+ continue;
123
+ }
124
+ if (!triple && source[i] === "\n") return undefined;
125
+ if (source.startsWith(delimiter, i)) return i + delimiter.length;
126
+ i++;
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ /** The `r`/`b` prefix letters written immediately before a quote, when they are
132
+ * a prefix rather than the tail of an identifier. */
133
+ function literalPrefix(source: string, quoteAt: number): string {
134
+ let i = quoteAt;
135
+ while (i > 0 && quoteAt - i < 2 && /[rRbB]/.test(source[i - 1]!)) i--;
136
+ if (i > 0 && /[A-Za-z0-9_]/.test(source[i - 1]!)) return "";
137
+ return source.slice(i, quoteAt);
138
+ }
package/src/cel/walk.ts CHANGED
@@ -1,64 +1,18 @@
1
1
  import { isTaggedSentinel } from "../sentinel.js";
2
- import { TEMPLATE_REGEX } from "./compile.js";
3
2
 
4
- /** How an emitted expression sits in the scalar it came from. A repair can be
5
- * applied by replacing the scalar only when the expression covers all of it;
6
- * otherwise the literal text around it would be lost.
7
- *
8
- * `wrapper` is the delimiter text to restore around a corrected expression —
9
- * empty for a tagged sentinel (whose scalar *is* the expression), `${{` / `}}`
10
- * for the legacy interpolation form. Carrying it as data rather than letting
11
- * each consumer re-derive it is what keeps `${{ … }}` a first-class fix site
12
- * instead of an exclusion: the two surfaces differ only by these delimiters. */
13
- export interface CelSurface {
14
- readonly whole: boolean;
15
- readonly wrapper?: { readonly prefix: string; readonly suffix: string };
16
- }
17
-
18
- const OPEN = "${{";
19
-
20
- /** Walks `value` and emits each templated source segment with its dotted
21
- * path (e.g. `routes[0].handler.body`) and the engine that owns it.
22
- *
23
- * - Untagged strings: every `${{ ... }}` segment is emitted with
24
- * `engineName = "cel"` (the implicit engine for the legacy interpolation
25
- * syntax).
26
- * - Tagged sentinels: emitted once with the sentinel's declared engine.
27
- * This includes engines that may produce no diagnostics (`literal`) —
28
- * routing through the registry stays generic so adding a third engine
29
- * that wants real analysis doesn't require touching the walker.
30
- * - Compiled values are skipped so a precompiled tree won't be re-walked. */
3
+ /** Walks `value` and emits each tagged scalar with its dotted path (e.g.
4
+ * `routes[0].handler.body`) and the engine that owns it — including engines
5
+ * that produce no diagnostics (`literal`), so routing through the registry
6
+ * stays generic and a new engine needs no change here. A plain string is
7
+ * never a value's expression, and compiled values are skipped so a
8
+ * precompiled tree is not re-walked. */
31
9
  export function walkCelExpressions(
32
10
  value: unknown,
33
11
  path: string,
34
- cb: (source: string, path: string, engineName: string, surface: CelSurface) => void,
12
+ cb: (source: string, path: string, engineName: string) => void,
35
13
  ): void {
36
14
  if (isTaggedSentinel(value)) {
37
- cb(value.source, path, value.engine, { whole: true });
38
- return;
39
- }
40
- if (typeof value === "string") {
41
- if (!value.includes(OPEN)) return;
42
- const matches = [...value.matchAll(TEMPLATE_REGEX)];
43
- for (const m of matches) {
44
- const expr = m[1]!.trim();
45
- // A string that is nothing but one interpolation is as whole as a
46
- // tagged scalar — the delimiters are the only difference, and they are
47
- // handed back as the wrapper.
48
- const only = matches.length === 1 && m.index === 0 && m[0]!.length === value.length;
49
- const lead = /^\s*/.exec(m[0]!.slice(OPEN.length))![0]!.length;
50
- cb(expr, path, "cel", {
51
- whole: only,
52
- ...(only
53
- ? {
54
- wrapper: {
55
- prefix: value.slice(0, OPEN.length + lead),
56
- suffix: value.slice(OPEN.length + lead + expr.length),
57
- },
58
- }
59
- : {}),
60
- });
61
- }
15
+ cb(value.source, path, value.engine);
62
16
  return;
63
17
  }
64
18
  if (Array.isArray(value)) {
package/src/engine.ts CHANGED
@@ -190,6 +190,13 @@ export interface EngineFileClaim {
190
190
  readonly directory?: boolean;
191
191
  }
192
192
 
193
+ /** One CEL expression inside a tagged scalar, by offset into the scalar's
194
+ * source. */
195
+ export interface ExpressionRegion {
196
+ readonly start: number;
197
+ readonly end: number;
198
+ }
199
+
193
200
  /** Per-property templating engine. Matches a YAML tag (`!<name>`); the kernel
194
201
  * and analyzer dispatch through the registry rather than knowing about
195
202
  * specific engines. */
@@ -250,4 +257,13 @@ export interface TemplatingEngine {
250
257
  * byte slot both fail statically, through the ordinary schema check and with
251
258
  * no diagnostic code of their own. */
252
259
  producedType?(): Record<string, unknown>;
260
+
261
+ /** Where the CEL expressions sit inside the tagged scalar — the whole source
262
+ * for `!cel`, each hole's expression for a tag with holes.
263
+ *
264
+ * What an editor colours, completes, hovers and renames against, so it finds
265
+ * the expressions of any tag without recognising the tag. Absent on an
266
+ * engine whose scalar holds no CEL. A source the engine cannot read yields
267
+ * no regions; `analyze` is what reports why. */
268
+ expressionRegions?(source: string): readonly ExpressionRegion[];
253
269
  }
@@ -36,6 +36,15 @@ import type {
36
36
  * explained it, and left `${{ }}` interpolations chain-validated but never
37
37
  * type-checked at all. */
38
38
  export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeResult {
39
+ return analyzeCelWithTree(source, env).result;
40
+ }
41
+
42
+ /** {@link analyzeCelExpression}, with the resolved tree it built — for a tag
43
+ * that asks its own questions of one expression without parsing it again. */
44
+ export function analyzeCelWithTree(
45
+ source: string,
46
+ env: AnalyzeEnv,
47
+ ): { result: AnalyzeResult; ast?: ASTNode } {
39
48
  const out: EngineDiagnostic[] = [];
40
49
 
41
50
  let parsed: ReturnType<typeof env.celEnv.parse>;
@@ -43,10 +52,13 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
43
52
  parsed = env.celEnv.parse(source);
44
53
  } catch (e) {
45
54
  return {
46
- diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: e instanceof Error ? e.message : String(e) }],
47
- calls: [],
55
+ result: {
56
+ diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: e instanceof Error ? e.message : String(e) }],
57
+ calls: [],
58
+ },
48
59
  };
49
60
  }
61
+ const ast: ASTNode = parsed.ast;
50
62
 
51
63
  // Resolution, before anything reads the tree — the audit, the type check and
52
64
  // every chain walk below all see the resolved shape, so none of them has to
@@ -94,15 +106,18 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
94
106
  // crash here silently retires static typing for that expression. Report it
95
107
  // instead: degrading is acceptable, degrading invisibly is not.
96
108
  return {
97
- diagnostics: [
98
- {
99
- code: "CEL_TYPE_ERROR",
100
- message: `the CEL type-checker failed on this expression: ${
101
- e instanceof Error ? e.message : String(e)
102
- }`,
103
- },
104
- ],
105
- calls: audit.calls,
109
+ result: {
110
+ diagnostics: [
111
+ {
112
+ code: "CEL_TYPE_ERROR",
113
+ message: `the CEL type-checker failed on this expression: ${
114
+ e instanceof Error ? e.message : String(e)
115
+ }`,
116
+ },
117
+ ],
118
+ calls: audit.calls,
119
+ },
120
+ ast,
106
121
  };
107
122
  }
108
123
 
@@ -193,9 +208,12 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
193
208
  }
194
209
 
195
210
  return {
196
- diagnostics: out,
197
- calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
198
- ...(type === undefined ? {} : { type }),
211
+ result: {
212
+ diagnostics: out,
213
+ calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
214
+ ...(type === undefined ? {} : { type }),
215
+ },
216
+ ast,
199
217
  };
200
218
  }
201
219
 
@@ -248,4 +266,8 @@ export const celEngine: TemplatingEngine = {
248
266
  analyze(source, env) {
249
267
  return analyzeCelExpression(source, env);
250
268
  },
269
+
270
+ expressionRegions(source) {
271
+ return [{ start: 0, end: source.length }];
272
+ },
251
273
  };
@@ -0,0 +1,96 @@
1
+ import type { ASTNode } from "@marcbachmann/cel-js";
2
+ import type { CompiledValue } from "@telorun/sdk";
3
+ import { compileExpression } from "../cel/compile.js";
4
+ import {
5
+ readInterpolationHoles,
6
+ type InterpolationHole,
7
+ } from "../cel/interpolation-holes.js";
8
+ import type {
9
+ AnalyzeEnv,
10
+ AnalyzeResult,
11
+ CallSite,
12
+ CompileEnv,
13
+ DiagnosticFix,
14
+ EngineDiagnostic,
15
+ ExpressionRegion,
16
+ } from "../engine.js";
17
+ import { analyzeCelWithTree } from "./cel.js";
18
+
19
+ /** The holes of a scalar a hole-bearing tag compiles, or a thrown error naming
20
+ * where the reading failed — a tag's scalar that cannot be read is not a value. */
21
+ export function requireHoles(tag: string, source: string): readonly InterpolationHole[] {
22
+ const reading = readInterpolationHoles(source);
23
+ if (!reading.ok) throw new Error(`!${tag}: ${reading.message}`);
24
+ return reading.holes;
25
+ }
26
+
27
+ /** Every hole compiled as its own CEL expression, with the roots, module calls
28
+ * and volatility of all of them carried together. */
29
+ export function compileHoles(
30
+ holes: readonly InterpolationHole[],
31
+ env: CompileEnv,
32
+ ): {
33
+ readonly compiled: readonly CompiledValue[];
34
+ readonly refs: readonly string[];
35
+ readonly calls: readonly string[];
36
+ readonly volatile: boolean;
37
+ } {
38
+ const compiled = holes.map((h) => compileExpression(h.expr, env.celEnv, env.moduleNames));
39
+ const refs = new Set<string>();
40
+ const calls = new Set<string>();
41
+ let volatile = false;
42
+ for (const c of compiled) {
43
+ for (const r of c.refs ?? []) refs.add(r);
44
+ for (const q of c.calls ?? []) calls.add(q);
45
+ if (c.volatile) volatile = true;
46
+ }
47
+ return { compiled, refs: [...refs], calls: [...calls], volatile };
48
+ }
49
+
50
+ /** Analyze each hole with the shared CEL analysis, so diagnostics read exactly
51
+ * as they do under `!cel`; a fix computed against one hole's expression is
52
+ * re-anchored onto the whole scalar, and call offsets onto the scalar too.
53
+ * `perHole` adds a tag's own verdict on a hole that analyzed clean. */
54
+ export function analyzeHoles(
55
+ source: string,
56
+ env: AnalyzeEnv,
57
+ perHole?: (
58
+ hole: InterpolationHole,
59
+ result: AnalyzeResult,
60
+ ast: ASTNode | undefined,
61
+ ) => readonly EngineDiagnostic[],
62
+ ): AnalyzeResult {
63
+ const reading = readInterpolationHoles(source);
64
+ if (!reading.ok) {
65
+ return { diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: reading.message }], calls: [] };
66
+ }
67
+ const diagnostics: EngineDiagnostic[] = [];
68
+ const calls: CallSite[] = [];
69
+ for (const hole of reading.holes) {
70
+ const { result, ast } = analyzeCelWithTree(hole.expr, env);
71
+ for (const d of result.diagnostics) {
72
+ diagnostics.push(d.fix ? { ...d, fix: reanchor(source, hole, d.fix) } : d);
73
+ }
74
+ for (const c of result.calls) {
75
+ calls.push({ ...c, start: hole.exprStart + c.start, end: hole.exprStart + c.end });
76
+ }
77
+ if (perHole && result.diagnostics.length === 0) diagnostics.push(...perHole(hole, result, ast));
78
+ }
79
+ return { diagnostics, calls };
80
+ }
81
+
82
+ /** The CEL expressions of a hole-bearing scalar, by offset. */
83
+ export function holeRegions(source: string): readonly ExpressionRegion[] {
84
+ const reading = readInterpolationHoles(source);
85
+ if (!reading.ok) return [];
86
+ return reading.holes.map((h) => ({ start: h.exprStart, end: h.exprStart + h.expr.length }));
87
+ }
88
+
89
+ function reanchor(source: string, hole: InterpolationHole, fix: DiagnosticFix): DiagnosticFix {
90
+ return {
91
+ replacement:
92
+ source.slice(0, hole.exprStart) +
93
+ fix.replacement +
94
+ source.slice(hole.exprStart + hole.expr.length),
95
+ };
96
+ }