@telorun/templating 0.22.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 +21 -40
  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 +23 -56
  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
@@ -0,0 +1,139 @@
1
+ import { Environment, EvaluationError, type ASTNode } from "@marcbachmann/cel-js";
2
+ import { RuntimeError, type CompiledValue } from "@telorun/sdk";
3
+ import { nullableValueChain } from "../cel/analyze.js";
4
+ import { literalFragments, type InterpolationHole } from "../cel/interpolation-holes.js";
5
+ import type { AnalyzeEnv, AnalyzeResult, EngineDiagnostic, TemplatingEngine } from "../engine.js";
6
+ import { analyzeHoles, compileHoles, holeRegions, requireHoles } from "./hole-analysis.js";
7
+
8
+ const INTERPOLATE_ENGINE = "interpolate";
9
+
10
+ /**
11
+ * The `!interpolate` engine: literal text with `${{ expr }}` holes, always a
12
+ * string. Its meaning is exactly the CEL expression that joins the text with
13
+ * `string(<hole>)` for each hole — every hole converts through CEL's own
14
+ * `string()` overloads (RFC 3339 for a timestamp, `5400s` for a duration, UTF-8
15
+ * for bytes), never the host language's conversion, so any CEL engine renders
16
+ * the same text. A hole whose type has no `string()` overload is refused
17
+ * statically, and a `dyn` hole that turns out null, a list or a map is refused
18
+ * at runtime with the hole it came from.
19
+ */
20
+ export const interpolateEngine: TemplatingEngine = {
21
+ name: INTERPOLATE_ENGINE,
22
+ language: "cel",
23
+
24
+ compile(source, env) {
25
+ const holes = requireHoles(INTERPOLATE_ENGINE, source);
26
+ const fragments = literalFragments(source, holes);
27
+ const { compiled, refs, calls, volatile } = compileHoles(holes, env);
28
+ const convert = stringConversion(env.celEnv);
29
+ return {
30
+ __compiled: true,
31
+ source,
32
+ refs,
33
+ calls,
34
+ ...(volatile ? { volatile: true as const } : {}),
35
+ call: (ctx: Record<string, unknown>): string => {
36
+ let out = fragments[0]!;
37
+ for (let i = 0; i < holes.length; i++) {
38
+ out += convert(compiled[i]!.call(ctx), holes[i]!, source) + fragments[i + 1]!;
39
+ }
40
+ return out;
41
+ },
42
+ } satisfies CompiledValue;
43
+ },
44
+
45
+ analyze(source, env) {
46
+ return analyzeHoles(source, env, (hole, result, ast) => holeVerdict(hole, result, ast, env));
47
+ },
48
+
49
+ producedType() {
50
+ return { type: "string" };
51
+ },
52
+
53
+ expressionRegions(source) {
54
+ return holeRegions(source);
55
+ },
56
+ };
57
+
58
+ /** A clean hole's own checks, over the tree its analysis already built:
59
+ * whether it may be null, and whether CEL can turn its type into text at all. */
60
+ function holeVerdict(
61
+ hole: InterpolationHole,
62
+ result: AnalyzeResult,
63
+ ast: ASTNode | undefined,
64
+ env: AnalyzeEnv,
65
+ ): readonly EngineDiagnostic[] {
66
+ if (ast && env.contextSchema) {
67
+ const chain = nullableValueChain(ast, env.contextSchema as Record<string, any>);
68
+ if (chain !== null) {
69
+ return [
70
+ {
71
+ code: "CEL_NULLABLE_ACCESS",
72
+ message:
73
+ `'${chain}' may be null, and a null has no text — guard it in the hole ` +
74
+ `(e.g. '\${{ ${chain} != null ? ${chain} : "" }}').`,
75
+ },
76
+ ];
77
+ }
78
+ }
79
+ if (result.type === undefined || convertibleTypes(env.celEnv).has(result.type)) return [];
80
+ return [
81
+ {
82
+ code: "INTERPOLATION_HOLE_NOT_CONVERTIBLE",
83
+ message:
84
+ `the hole '\${{ ${hole.expr} }}' is ${result.type}, which CEL's string() cannot convert to text. ` +
85
+ `Convert it inside the hole (e.g. join a list, or read the field you meant), or write the whole value as !cel.`,
86
+ },
87
+ ];
88
+ }
89
+
90
+ const CONVERTIBLE = new WeakMap<Environment, ReadonlySet<string>>();
91
+
92
+ /** The types a `string()` overload of `env` accepts, `dyn` among them — read
93
+ * off the registered overloads, so the check is the one evaluation applies. */
94
+ function convertibleTypes(env: Environment): ReadonlySet<string> {
95
+ const cached = CONVERTIBLE.get(env);
96
+ if (cached) return cached;
97
+ const types = new Set<string>(["dyn"]);
98
+ for (const fn of env.getDefinitions().functions) {
99
+ if (fn.name === "string" && fn.receiverType === null && fn.params?.length === 1) {
100
+ types.add(fn.params[0]!.type);
101
+ }
102
+ }
103
+ CONVERTIBLE.set(env, types);
104
+ return types;
105
+ }
106
+
107
+ type Conversion = (value: unknown, hole: InterpolationHole, source: string) => string;
108
+
109
+ const CONVERSIONS = new WeakMap<Environment, Conversion>();
110
+
111
+ /** CEL's `string(v)` in `env`, with every overload the environment registers. */
112
+ function stringConversion(env: Environment): Conversion {
113
+ const cached = CONVERSIONS.get(env);
114
+ if (cached) return cached;
115
+ const program = env.parse("string(value)") as (ctx: { value: unknown }) => unknown;
116
+ const conversion: Conversion = (value, hole, source) => {
117
+ if (typeof value === "string") return value;
118
+ try {
119
+ return program({ value }) as string;
120
+ } catch (error) {
121
+ if (!(error instanceof EvaluationError)) throw error;
122
+ throw new RuntimeError(
123
+ "ERR_INTERPOLATION_HOLE_NOT_CONVERTIBLE",
124
+ `the hole '\${{ ${hole.expr} }}' at offset ${hole.start} of !interpolate ${JSON.stringify(source)} ` +
125
+ `evaluated to ${runtimeTypeOf(value)}, which CEL's string() cannot convert to text. ` +
126
+ `Declare outputType on the resource producing it so the check sees its type, or guard it inside the hole.`,
127
+ );
128
+ }
129
+ };
130
+ CONVERSIONS.set(env, conversion);
131
+ return conversion;
132
+ }
133
+
134
+ function runtimeTypeOf(value: unknown): string {
135
+ if (value === null || value === undefined) return "null";
136
+ if (Array.isArray(value)) return "a list";
137
+ if (value instanceof Map || Object.getPrototypeOf(value) === Object.prototype) return "a map";
138
+ return `a value of type ${(value as object).constructor?.name ?? typeof value}`;
139
+ }
@@ -1,19 +1,14 @@
1
1
  import { isParameterizedSql, type CompiledValue, type ParameterizedSql } from "@telorun/sdk";
2
- import { analyzeCelExpression } from "./cel.js";
3
- import { compileString, toParameterized, TEMPLATE_REGEX } from "../cel/compile.js";
4
- import type {
5
- CallSite,
6
- DiagnosticFix,
7
- EngineDiagnostic,
8
- TemplatingEngine,
9
- } from "../engine.js";
2
+ import { literalFragments } from "../cel/interpolation-holes.js";
3
+ import type { TemplatingEngine } from "../engine.js";
4
+ import { analyzeHoles, compileHoles, holeRegions, requireHoles } from "./hole-analysis.js";
10
5
 
11
6
  export { isParameterizedSql, type ParameterizedSql };
12
7
 
13
8
  /** The `!sql` engine. Treats the tagged scalar as a SQL string with `${{ }}`
14
- * interpolations whose values are *bound*, not spliced. Unlike `!cel` (one bare
15
- * expression) it keeps the literal text and each interpolation separate: at
16
- * runtime `call()` returns a {@link ParameterizedSql} the consumer turns into a
9
+ * holes whose values are *bound*, not spliced. Unlike `!cel` (one bare
10
+ * expression) it keeps the literal text and each hole separate: at runtime
11
+ * `call()` returns a {@link ParameterizedSql} the consumer turns into a
17
12
  * parameterized query. Generic expansion passes that object through untouched
18
13
  * (it is the `call()` result), so it survives the step-level input expansion. */
19
14
  export const sqlEngine: TemplatingEngine = {
@@ -21,69 +16,33 @@ export const sqlEngine: TemplatingEngine = {
21
16
  language: "sql",
22
17
 
23
18
  compile(source, env) {
24
- const inner = compileString(source, env.celEnv, env.moduleNames);
19
+ const holes = requireHoles("sql", source);
20
+ const fragments = literalFragments(source, holes);
21
+ const { compiled, refs, calls, volatile } = compileHoles(holes, env);
25
22
  return {
26
23
  __compiled: true,
27
24
  source,
28
- // The qualified module calls of every interpolation, for the reason
29
- // `refs` are carried: a consumer asking what an expression CALLS cannot
30
- // re-derive it from the text without the declaring module's names.
31
- calls: typeof inner === "string" ? [] : ((inner as CompiledValue).calls ?? []),
32
- // The AST-derived root identifiers of every interpolation, carried through
33
- // rather than dropped. `compileString` has already computed them one line
34
- // above, and a consumer that asks a compiled value what it READS —
35
- // a template body deciding which nodes survive its `init()` — otherwise
36
- // falls back to scanning the source text, which cannot tell an identifier
37
- // from a word inside a SQL string literal.
38
- refs: typeof inner === "string" ? [] : (inner as CompiledValue).refs,
39
- call: (ctx: Record<string, unknown>): ParameterizedSql => {
40
- const { fragments, values } = toParameterized(inner, ctx);
41
- return { __teloParameterized: true, fragments, values };
42
- },
25
+ // Carried for the reason `!cel` carries them: a consumer asking what an
26
+ // expression READS or CALLS cannot re-derive it from SQL text, which
27
+ // cannot tell an identifier from a word inside a string literal.
28
+ refs,
29
+ calls,
30
+ ...(volatile ? { volatile: true as const } : {}),
31
+ call: (ctx: Record<string, unknown>): ParameterizedSql => ({
32
+ __teloParameterized: true,
33
+ fragments: fragments.slice(),
34
+ values: compiled.map((c) => c.call(ctx)),
35
+ }),
43
36
  } satisfies CompiledValue;
44
37
  },
45
38
 
46
39
  analyze(source, env) {
47
- // Each `${{ }}` interpolation is its own CEL expression; reuse the shared
48
- // per-expression analyzer so diagnostics match the `!cel` engine exactly.
49
- // Each interpolation's offset is kept so a fix computed against the bare
50
- // expression is re-anchored to the whole SQL scalar — the only thing that
51
- // ever made `!sql` fix-less was dropping it here.
52
- const diagnostics: EngineDiagnostic[] = [];
53
- const calls: CallSite[] = [];
54
- for (const { expr, start } of expressionsOf(source)) {
55
- const result = analyzeCelExpression(expr, env);
56
- for (const d of result.diagnostics) {
57
- diagnostics.push(d.fix ? { ...d, fix: reanchor(source, expr, start, d.fix) } : d);
58
- }
59
- for (const c of result.calls) {
60
- calls.push({ ...c, start: start + c.start, end: start + c.end });
61
- }
62
- }
63
- // No `type`: a SQL template is a string built from many expressions, so
40
+ // No `type`: a SQL template is a query built from many expressions, so
64
41
  // there is no single checked type to report.
65
- return { diagnostics, calls };
42
+ return analyzeHoles(source, env);
66
43
  },
67
- };
68
-
69
- /** Re-anchor a fix computed against one interpolation onto the full source. */
70
- function reanchor(source: string, expr: string, start: number, fix: DiagnosticFix): DiagnosticFix {
71
- return {
72
- replacement: source.slice(0, start) + fix.replacement + source.slice(start + expr.length),
73
- };
74
- }
75
-
76
- /** Each `${{ expr }}` body in a `!sql` template, with the body's offset in the
77
- * source. The offset is derived from the opening delimiter and the leading
78
- * whitespace the capture group already trims, never by searching for the
79
- * body text — which a body appearing twice would defeat. */
80
- function expressionsOf(source: string): { expr: string; start: number }[] {
81
- const out: { expr: string; start: number }[] = [];
82
- for (const m of source.matchAll(TEMPLATE_REGEX)) {
83
- const lead = /^\s*/.exec(m[0]!.slice(OPEN.length))![0]!.length;
84
- out.push({ expr: m[1]!, start: m.index! + OPEN.length + lead });
85
- }
86
- return out;
87
- }
88
44
 
89
- const OPEN = "${{";
45
+ expressionRegions(source) {
46
+ return holeRegions(source);
47
+ },
48
+ };
package/src/index.ts CHANGED
@@ -11,13 +11,15 @@ export {
11
11
  type CelFunctionDoc,
12
12
  type CelFunctionCategory,
13
13
  } from "./cel/catalog.js";
14
+ export { compileExpression } from "./cel/compile.js";
14
15
  export {
15
- compileExpression,
16
- compileString,
17
- toParameterized,
18
- TEMPLATE_REGEX,
19
- EXACT_TEMPLATE_REGEX,
20
- } from "./cel/compile.js";
16
+ interpolationShape,
17
+ literalFragments,
18
+ readInterpolationHoles,
19
+ type HoleReading,
20
+ type InterpolationHole,
21
+ type InterpolationShape,
22
+ } from "./cel/interpolation-holes.js";
21
23
  export {
22
24
  extractAccessChains,
23
25
  findNullableAccessIssues,
@@ -43,7 +45,7 @@ export {
43
45
  type ModuleCallDispatch,
44
46
  type ModuleCallTypeResolver,
45
47
  } from "./cel/module-call.js";
46
- export { walkCelExpressions, type CelSurface } from "./cel/walk.js";
48
+ export { walkCelExpressions } from "./cel/walk.js";
47
49
 
48
50
  export { celEngine } from "./engines/cel.js";
49
51
  export {
@@ -53,6 +55,7 @@ export {
53
55
  normalizeModulePath,
54
56
  type NormalizedIncludePath,
55
57
  } from "./engines/include.js";
58
+ export { interpolateEngine } from "./engines/interpolate.js";
56
59
  export { literalEngine } from "./engines/literal.js";
57
60
  export { modulePathEngine } from "./engines/module-path.js";
58
61
  export { refEngine } from "./engines/ref.js";
@@ -61,6 +64,7 @@ export { sqlEngine, isParameterizedSql, type ParameterizedSql } from "./engines/
61
64
  export { TemplatingEngineRegistry } from "./registry.js";
62
65
  export {
63
66
  builtinEngines,
67
+ celExpressionsOf,
64
68
  createDefaultRegistry,
65
69
  defaultRegistry,
66
70
  producedTypeOf,
@@ -74,6 +78,7 @@ export type {
74
78
  DiagnosticFix,
75
79
  EngineDiagnostic,
76
80
  EngineFileClaim,
81
+ ExpressionRegion,
77
82
  TemplatingEngine,
78
83
  } from "./engine.js";
79
84
 
package/src/sentinel.ts CHANGED
@@ -51,26 +51,18 @@ export const MODULE_PATH_ENGINE = "module-path";
51
51
  /**
52
52
  * The dotted chain a value names, or undefined.
53
53
  *
54
- * Only a PLAIN CHAIN — `steps.encode.result.output` — in either spelling a
55
- * manifest may carry it: a `!cel` sentinel or the `${{ }}` string form. An
56
- * expression that COMPUTES rather than names has no schema to read off a context,
57
- * so a caller that navigates one gets nothing and reports nothing: silence where
58
- * the analyzer knows least is the conservative direction.
54
+ * Only a PLAIN CHAIN written as a `!cel` value — `steps.encode.result.output`.
55
+ * An expression that COMPUTES rather than names has no schema to read off a
56
+ * context, so a caller that navigates one gets nothing and reports nothing:
57
+ * silence where the analyzer knows least is the conservative direction.
59
58
  *
60
59
  * Here rather than in each caller because "is this expression a plain chain" is
61
60
  * one question, and two copies of the answer would eventually disagree about a
62
61
  * shape like `a.b[0]`.
63
62
  */
64
63
  export function plainChainOf(value: unknown): string | undefined {
65
- const source = isTaggedSentinel(value)
66
- ? value.engine === CEL_ENGINE
67
- ? value.source
68
- : undefined
69
- : typeof value === "string"
70
- ? /^\s*\$\{\{(.+)\}\}\s*$/.exec(value)?.[1]
71
- : undefined;
72
- if (typeof source !== "string") return undefined;
73
- const trimmed = source.trim();
64
+ if (!isTaggedSentinel(value) || value.engine !== CEL_ENGINE) return undefined;
65
+ const trimmed = value.source.trim();
74
66
  return /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(trimmed)
75
67
  ? trimmed
76
68
  : undefined;