@telorun/templating 0.107.0 → 0.109.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 (60) hide show
  1. package/dist/builtins.d.ts +2 -2
  2. package/dist/builtins.d.ts.map +1 -1
  3. package/dist/cel/analyze.d.ts +6 -6
  4. package/dist/cel/analyze.d.ts.map +1 -1
  5. package/dist/cel/analyze.js +138 -183
  6. package/dist/cel/compile.d.ts +47 -17
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +135 -83
  9. package/dist/cel/diagnose.d.ts +52 -57
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +69 -291
  12. package/dist/cel/environment.d.ts +33 -37
  13. package/dist/cel/environment.d.ts.map +1 -1
  14. package/dist/cel/environment.js +54 -86
  15. package/dist/cel/module-call.d.ts +68 -79
  16. package/dist/cel/module-call.d.ts.map +1 -1
  17. package/dist/cel/module-call.js +118 -194
  18. package/dist/cel/value-brands.d.ts +14 -12
  19. package/dist/cel/value-brands.d.ts.map +1 -1
  20. package/dist/cel/value-brands.js +26 -24
  21. package/dist/cel/verdict-codes.d.ts +13 -2
  22. package/dist/cel/verdict-codes.d.ts.map +1 -1
  23. package/dist/cel/verdict-codes.js +20 -1
  24. package/dist/engine.d.ts +4 -4
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engines/cel.d.ts +2 -2
  27. package/dist/engines/cel.d.ts.map +1 -1
  28. package/dist/engines/cel.js +53 -81
  29. package/dist/engines/hole-analysis.d.ts +3 -3
  30. package/dist/engines/hole-analysis.d.ts.map +1 -1
  31. package/dist/engines/interpolate.js +11 -8
  32. package/dist/index.d.ts +4 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +8 -5
  35. package/package.json +4 -4
  36. package/src/builtins.ts +2 -2
  37. package/src/cel/analyze.ts +152 -193
  38. package/src/cel/compile.ts +160 -77
  39. package/src/cel/diagnose.ts +115 -370
  40. package/src/cel/environment.ts +64 -87
  41. package/src/cel/module-call.ts +129 -292
  42. package/src/cel/value-brands.ts +26 -25
  43. package/src/cel/verdict-codes.ts +20 -1
  44. package/src/engine.ts +4 -4
  45. package/src/engines/cel.ts +52 -84
  46. package/src/engines/hole-analysis.ts +3 -3
  47. package/src/engines/interpolate.ts +16 -13
  48. package/src/index.ts +8 -11
  49. package/dist/cel/catalog.d.ts +0 -70
  50. package/dist/cel/catalog.d.ts.map +0 -1
  51. package/dist/cel/catalog.js +0 -1320
  52. package/dist/cel/json-prefix-scan.d.ts +0 -17
  53. package/dist/cel/json-prefix-scan.d.ts.map +0 -1
  54. package/dist/cel/json-prefix-scan.js +0 -160
  55. package/dist/cel/value-identity.d.ts +0 -18
  56. package/dist/cel/value-identity.d.ts.map +0 -1
  57. package/dist/cel/value-identity.js +0 -25
  58. package/src/cel/catalog.ts +0 -1455
  59. package/src/cel/json-prefix-scan.ts +0 -152
  60. package/src/cel/value-identity.ts +0 -34
@@ -1,295 +1,73 @@
1
- import { CEL_FUNCTIONS } from "./catalog.js";
2
- import { moduleCallOf } from "./module-call.js";
3
- /** Determinism is Telo catalog metadata; cel-js builtins carry none. Absent
4
- * means "no signal", never "deterministic" — consumers of
5
- * `CallSite.deterministic` must not read undefined as a guarantee. */
6
- const DETERMINISM = new Map(CEL_FUNCTIONS.map((f) => [f.name, f.deterministic]));
7
- const HOST_BACKED = new Map(CEL_FUNCTIONS.map((f) => [f.name, f.hostBacked === true]));
8
- const INDEX_CACHE = new WeakMap();
9
- /** Registry view of an environment, memoized: environments are rebuilt per
10
- * analysis path, but each is immutable once built. */
11
- export function functionIndex(env) {
12
- const cached = INDEX_CACHE.get(env);
13
- if (cached)
14
- return cached;
15
- const byName = new Map();
16
- for (const fn of env.getDefinitions().functions) {
17
- const form = fn.receiverType === null ? "global" : "receiver";
18
- const entry = { signature: fn.signature, form, arity: fn.params?.length ?? 0 };
19
- const entries = byName.get(fn.name);
20
- if (entries)
21
- entries.push(entry);
22
- else
23
- byName.set(fn.name, [entry]);
24
- }
25
- const index = { byName };
26
- INDEX_CACHE.set(env, index);
27
- return index;
28
- }
29
- /** Macros the parser expands rather than dispatching through the registry, so
30
- * they never appear in `getDefinitions()` and would otherwise classify as
31
- * unknown names.
1
+ import { moduleCallArgumentChains } from "./analyze.js";
2
+ /**
3
+ * Every call the expression makes, with what the checker resolved about it.
32
4
  *
33
- * Deliberately short: most macros ARE registered, and the caller only reports
34
- * this audit when the type-checker already rejected the expression, so a macro
35
- * missing from here degrades to "no extra explanation" rather than to a false
36
- * error on valid CEL. That is what keeps a cel-js upgrade from turning a new
37
- * macro into a manifest this analyzer refuses. */
38
- const MACROS = new Set(["optMap", "optFlatMap", "bind"]);
39
- function isNode(v) {
40
- return typeof v === "object" && v !== null && "op" in v;
41
- }
42
- /** Every non-macro call in the expression, in source order. */
43
- function collectCalls(root, index, moduleCallFlags) {
44
- const out = [];
45
- visit(root);
46
- return out.sort((a, b) => a.start - b.start);
47
- function visit(node) {
48
- const args = node.args;
49
- // A RESOLVED module call is reported under its QUALIFIED name and is never
50
- // looked up in the catalog: the two namespaces are disjoint by construction
51
- // (a bare name is always the catalog), so classifying it here would report
52
- // `there is no function 'format'` for a call that names a module's own, and
53
- // attaching the catalog's determinism to it would be a flag about a
54
- // different function entirely. What a module call's flags are is the
55
- // resolving host's answer, carried when it gives one.
56
- const moduleCall = moduleCallOf(node);
57
- if (moduleCall) {
58
- const flags = moduleCallFlags?.(moduleCall.qualified);
59
- out.push({
60
- name: moduleCall.qualified,
61
- form: "receiver",
62
- moduleCall: true,
63
- arity: moduleCall.args.length,
64
- start: node.start,
65
- end: node.end,
66
- ...(flags ? { deterministic: flags.deterministic, hostBacked: flags.hostBacked } : {}),
67
- args: moduleCall.args,
68
- });
69
- for (const arg of moduleCall.args)
70
- visit(arg);
71
- return;
72
- }
73
- if (node.op === "call" || node.op === "rcall") {
74
- const tuple = args;
75
- const name = tuple[0];
76
- if (typeof name === "string" && !MACROS.has(name)) {
77
- const receiver = node.op === "rcall" ? tuple[1] : undefined;
78
- const rawArgs = node.op === "rcall" ? tuple[2] : tuple[1];
79
- const callArgs = (Array.isArray(rawArgs) ? rawArgs : []).filter(isNode);
80
- out.push({
81
- name,
82
- form: node.op === "rcall" ? "receiver" : "global",
83
- arity: callArgs.length,
84
- start: node.start,
85
- end: node.end,
86
- ...(index.byName.has(name)
87
- ? { deterministic: DETERMINISM.get(name), hostBacked: HOST_BACKED.get(name) }
88
- : {}),
89
- ...(isNode(receiver) ? { receiver } : {}),
90
- args: callArgs,
91
- });
92
- }
93
- }
94
- for (const arg of Array.isArray(args) ? args : [args]) {
95
- if (isNode(arg))
96
- visit(arg);
97
- else if (Array.isArray(arg))
98
- for (const item of arg)
99
- if (isNode(item))
100
- visit(item);
101
- }
102
- }
103
- }
104
- /** Node shapes that can carry a `.` on their right without reparsing
105
- * differently. Everything else — an operator expression, a literal that would
106
- * sit against the dot — is parenthesized when moved into receiver position. */
107
- const SELF_DELIMITING = new Set(["id", ".", ".?", "call", "rcall", "[]", "[?]"]);
108
- /** Source text of a node. When it is about to become a receiver it may need
109
- * parentheses: an identifier, member chain, index or call is self-delimiting,
110
- * but an operator expression or a bare literal against a `.` is not. */
111
- function nodeText(source, node, asReceiver = false) {
112
- const text = source.slice(node.start, node.end);
113
- if (!asReceiver)
114
- return text;
115
- return SELF_DELIMITING.has(node.op) ? text : `(${text})`;
116
- }
117
- /** The same call written in the other form, or undefined when the shape does
118
- * not allow it (a global call with no arguments has no receiver to move). */
119
- function transpose(source, call) {
120
- if (call.form === "global") {
121
- const [first, ...rest] = call.args;
122
- if (!first)
123
- return undefined;
124
- const argText = rest.map((a) => nodeText(source, a));
125
- return `${nodeText(source, first, true)}.${call.name}(${argText.join(", ")})`;
126
- }
127
- if (!call.receiver)
128
- return undefined;
129
- const argText = [nodeText(source, call.receiver), ...call.args.map((a) => nodeText(source, a))];
130
- return `${call.name}(${argText.join(", ")})`;
131
- }
132
- /** Splice a rewritten call back into the full source. The fix always carries
133
- * the whole corrected source, so a consumer applies it by replacing the
134
- * scalar. */
135
- function spliceFix(source, call, rewritten) {
136
- return { replacement: source.slice(0, call.start) + rewritten + source.slice(call.end) };
137
- }
138
- /** Replace only the called name, leaving arguments untouched. The offset is
139
- * derived rather than searched: a receiver whose own text contains the name
140
- * (`slice.slice(1)`) would defeat a first-occurrence replace. */
141
- function renameFix(source, call, to) {
142
- const searchFrom = call.receiver ? call.receiver.end : call.start;
143
- const at = source.indexOf(call.name, searchFrom);
144
- if (at === -1 || at >= call.end)
145
- return undefined;
146
- return { replacement: source.slice(0, at) + to + source.slice(at + call.name.length) };
147
- }
148
- /** Arity the call would need in the other form: moving a receiver in adds an
149
- * argument, moving it out removes one. */
150
- function transposedArity(call) {
151
- return call.form === "global" ? call.arity - 1 : call.arity + 1;
152
- }
153
- function accepts(entries, form, arity) {
154
- return entries.some((e) => e.form === form && e.arity === arity);
155
- }
156
- const listOf = (names) => [...new Set(names)].sort().join(", ");
157
- /** Names registered in exactly the form and arity the author wrote — the only
158
- * ones that could replace this call with no further edits. Ranked by shared
159
- * prefix, which is what reaches `nowIso` from `no`; edit distance never
160
- * would (4 characters against a 2-character name). Returns [] when nothing
161
- * shares a prefix, so the caller lists what is legal here instead of
162
- * guessing. */
163
- function candidates(call, index) {
164
- const written = call.name.toLowerCase();
165
- return callableHere(call, index)
166
- .filter((name) => {
167
- const lower = name.toLowerCase();
168
- return lower.startsWith(written) || written.startsWith(lower);
169
- })
170
- .sort((a, b) => a.length - b.length || a.localeCompare(b));
171
- }
172
- /** Every name callable in exactly the position written — same form, same
173
- * argument count. Arity is what makes the list usable: a receiver's type is
174
- * `dyn` at analysis time so every method is nominally reachable, and printing
175
- * all forty says nothing. */
176
- function callableHere(call, index) {
177
- const names = [];
178
- for (const [name, entries] of index.byName) {
179
- if (name !== call.name && accepts(entries, call.form, call.arity))
180
- names.push(name);
181
- }
182
- return names;
183
- }
184
- function signaturesOf(name, index) {
185
- return (index.byName.get(name) ?? []).map((e) => e.signature);
186
- }
187
- /** Spread-friendly optional `fix`, so an undecidable rewrite simply omits the
188
- * field rather than carrying `undefined` into the diagnostic. */
189
- const withFix = (fix) => (fix ? { fix } : {});
190
- /** The literal value of an argument, or `undefined` when it is an expression
191
- * whose value is not statically known. A negated numeric literal is one node
192
- * out (`-1` parses as unary minus over a value), and reading it is what lets a
193
- * bound like "0–10" catch the below-range case as well as the above. */
194
- function literalOf(node) {
195
- if (node.op === "value")
196
- return node.args;
197
- if (node.op === "-_") {
198
- const inner = node.args;
199
- if (isNode(inner) && inner.op === "value") {
200
- const v = inner.args;
201
- if (typeof v === "number")
202
- return -v;
203
- if (typeof v === "bigint")
204
- return -v;
205
- }
206
- }
207
- return undefined;
208
- }
209
- const ARG_CHECKS = new Map(CEL_FUNCTIONS.flatMap((f) => (f.checkArgs ? [[f.name, f.checkArgs]] : [])));
210
- /** Classify every call in `ast`. Runs unconditionally rather than only after a
211
- * failed type-check, because a type-check reports its first error and stops:
212
- * an expression with two bad calls would otherwise fix one, re-run, and
213
- * discover the next. */
214
- export function auditCalls(source, ast, env,
215
- /** The flags of the module functions the expression calls, from whoever
216
- * resolves them. */
217
- moduleCallFlags) {
218
- const index = functionIndex(env);
219
- const diagnostics = [];
220
- const unresolved = [];
221
- const calls = collectCalls(ast, index, moduleCallFlags);
222
- for (const call of calls) {
223
- // Resolution already decided what a module call names. The catalog has
224
- // nothing to say about it, and saying it anyway would be a refusal of valid
225
- // CEL.
226
- if (call.moduleCall)
227
- continue;
228
- const entries = index.byName.get(call.name);
229
- const noun = call.form === "receiver" ? "method" : "function";
230
- if (!entries) {
231
- const near = candidates(call, index);
232
- const hint = near.length > 0
233
- ? `Closest taking ${call.arity} argument${call.arity === 1 ? "" : "s"}: ${near
234
- .slice(0, 5)
235
- .map((n) => `\`${n}\``)
236
- .join(", ")}.`
237
- : `Every ${noun} taking ${call.arity} argument${call.arity === 1 ? "" : "s"}: ${listOf(callableHere(call, index))}.`;
238
- diagnostics.push({
239
- code: "CEL_UNKNOWN_FUNCTION",
240
- message: `there is no ${noun} \`${call.name}\`. ${hint} Full list: \`telo cel functions\`.`,
241
- // A single candidate is an unambiguous rename; several are a menu, and
242
- // applying an arbitrary one would be a guess wearing a fix's clothes.
243
- ...(near.length === 1 ? withFix(renameFix(source, call, near[0])) : {}),
244
- });
245
- continue;
246
- }
247
- if (accepts(entries, call.form, call.arity))
248
- continue;
249
- const otherForm = call.form === "global" ? "receiver" : "global";
250
- if (accepts(entries, otherForm, transposedArity(call))) {
251
- const rewritten = transpose(source, call);
252
- const written = source.slice(call.start, call.end);
253
- diagnostics.push({
254
- code: "CEL_WRONG_CALL_FORM",
255
- message: `\`${call.name}\` is ${call.form === "global"
256
- ? "a method, not a global function — call it on the value"
257
- : "a global function, not a method — pass the value to it"}:` +
258
- (rewritten ? `\n write: ${rewritten}\n not: ${written}` : "") +
259
- `\nRegistered: ${listOf(signaturesOf(call.name, index))}.`,
260
- ...withFix(rewritten ? spliceFix(source, call, rewritten) : undefined),
261
- });
262
- continue;
263
- }
264
- unresolved.push(call.name);
265
- }
266
- const argumentIssues = [];
267
- for (const call of calls) {
268
- const check = ARG_CHECKS.get(call.name);
269
- if (!check)
270
- continue;
271
- const message = check(call.args.map(literalOf));
272
- // No span on an EngineDiagnostic, so the written call goes in the message —
273
- // an expression with two calls to the same function is otherwise ambiguous.
274
- if (message) {
275
- argumentIssues.push({
276
- code: "CEL_INVALID_ARGUMENT",
277
- message: `${message} (in \`${source.slice(call.start, call.end)}\`)`,
278
- });
279
- }
5
+ * A module call carries no catalog flag: what a module function's determinism and
6
+ * host-backedness are follows from the callable it resolves to, so they are carried only as
7
+ * the host's `moduleCallFlags` reports them, and stay absent where it gives nothing.
8
+ */
9
+ export function auditCalls(source, root, environment, moduleCallFlags, checked) {
10
+ const result = checked ?? environment.check({ source, root, namespaces: environment.namespaces(), diagnostics: [] });
11
+ const argumentChains = moduleCallArgumentChains(root);
12
+ const byNode = new Map([...argumentChains].map(([node, chains]) => [`${node.range[0]}:${node.range[1]}`, chains]));
13
+ // **One entry per call.** The checker already lists a qualified call — with `namespace`
14
+ // set and `form: "receiver"`, which is how it was written — so appending a second entry
15
+ // per `qualifiedCalls` showed every module call twice, with two contradictory forms, to
16
+ // every consumer that iterates this list.
17
+ const calls = [];
18
+ for (const call of result.calls) {
19
+ const qualified = call.namespace !== undefined;
20
+ const flags = qualified ? moduleCallFlags?.(call.name) : undefined;
21
+ const chains = qualified ? byNode.get(`${call.range[0]}:${call.range[1]}`) : undefined;
22
+ calls.push({
23
+ name: call.name,
24
+ form: call.form,
25
+ arity: call.arity,
26
+ start: call.range[0],
27
+ end: call.range[1],
28
+ ...(qualified ? { moduleCall: true } : {}),
29
+ // A module call's arguments as the analysis saw them: the type the checker gives each
30
+ // one, and the chain where the argument IS one — so a caller holding the callee's
31
+ // signature can compare a declared shape rather than a CEL type alone.
32
+ ...(qualified && call.argumentTypes
33
+ ? {
34
+ arguments: call.argumentTypes.map((type, at) => {
35
+ const chain = chains?.[at] ?? null;
36
+ return {
37
+ ...(type === "dyn" ? {} : { type }),
38
+ ...(chain ? { chain } : {}),
39
+ };
40
+ }),
41
+ }
42
+ : {}),
43
+ // A module call carries no catalog flag: its determinism and host-backedness follow
44
+ // from the callable the name resolves to, which only the host that resolves it knows.
45
+ ...(qualified
46
+ ? flags
47
+ ? { deterministic: flags.deterministic, hostBacked: flags.hostBacked }
48
+ : {}
49
+ : {
50
+ ...(call.deterministic === undefined ? {} : { deterministic: call.deterministic }),
51
+ ...(call.hostBacked === undefined ? {} : { hostBacked: call.hostBacked }),
52
+ }),
53
+ });
280
54
  }
281
- return {
282
- diagnostics,
283
- calls: calls.map(({ receiver: _receiver, args: _args, ...site }) => site),
284
- unresolved,
285
- argumentIssues,
286
- };
55
+ calls.sort((left, right) => left.start - right.start || left.end - right.end);
56
+ return { diagnostics: [], calls, unresolved: [], argumentIssues: [] };
287
57
  }
288
- /** Registered signatures for names a type-check failure mentions, so the
289
- * residual says what the function actually accepts rather than only echoing
290
- * what the author wrote. */
291
- export function explainUnresolved(names, env) {
292
- const index = functionIndex(env);
293
- const signatures = [...new Set(names)].flatMap((n) => signaturesOf(n, index));
294
- return signatures.length > 0 ? ` Registered: ${listOf(signatures)}.` : "";
58
+ /**
59
+ * Registered signatures for names a type-check failure mentions, so a residual message says
60
+ * what the function actually accepts rather than only echoing what the author wrote.
61
+ */
62
+ export function explainUnresolved(names, environment) {
63
+ const wanted = new Set(names);
64
+ const signatures = environment
65
+ .definitions()
66
+ .functions.filter((entry) => wanted.has(entry.name))
67
+ .map((entry) => entry.signature);
68
+ if (signatures.length === 0)
69
+ return "";
70
+ const listed = [...new Set(signatures)].map((signature) => `\`${signature}\``);
71
+ const last = listed.pop();
72
+ return ` Registered: ${listed.length > 0 ? `${listed.join(", ")} and ${last}` : last}.`;
295
73
  }
@@ -1,39 +1,35 @@
1
- import { Environment } from "@marcbachmann/cel-js";
2
- import { type CelHandlers } from "./catalog.js";
3
- export type { CelHandlers } from "./catalog.js";
4
- /** Build a CEL `Environment` with Telo's stdlib. Every function comes from the
5
- * single-source catalog (`CEL_FUNCTIONS`), so registration and the documented
6
- * surface (`telo cel functions`) can never drift. Always registers the same
7
- * signatures (so `env.check()` succeeds for type-inference); the host-injected
8
- * handlers govern what `hostBacked` functions do at runtime. Analyzer-only
9
- * callers can omit handlers (the stubs throw if such a function is evaluated);
10
- * runtime callers (kernel) supply real ones.
1
+ /**
2
+ * The two environments, now built on `@telorun/cel`.
11
3
  *
12
- * Also registers the `Stream` object type, backed by the `Stream` class from
13
- * `@telorun/sdk`. CEL's type-checker rejects values whose constructor isn't
14
- * Object/Map/Array/Set/registered; producers that need to expose an
15
- * `AsyncIterable` through a stream-typed property must wrap the iterable in
16
- * `new Stream(...)` so its constructor is the registered class. The type has
17
- * no fields, so terminal access (passing the value through CEL) succeeds but
18
- * member access raises a CEL error at runtime — matching the analyzer's
19
- * static check on `x-telo-stream`-marked properties. */
20
- /** Expand a documented signature that may contain `type?`-marked optional
21
- * parameters into one cel-js registration signature per arity. For example,
22
- * `"nowIso(string?): string"` produces `["nowIso(): string",
23
- * "nowIso(string): string"]`. Required parameters must precede optional ones.
24
- * Returns `[signature]` unchanged when no `?` is present or the signature
25
- * cannot be parsed. */
26
- export declare function deriveSignatures(signature: string): string[];
27
- /** The environment before any Telo function is registered — i.e. exactly
28
- * cel-js's own built-ins. Documentation needs to tell the two apart, and
29
- * subtracting by signature TEXT does not work: cel-js normalizes a declared
30
- * `list` to `list<dyn>`, so the catalog's documented spelling and the
31
- * registered one differ for a third of the entries. Asking for the base set
32
- * directly needs no matching at all. */
33
- export declare function celBuiltinFunctions(): ReturnType<Environment["getDefinitions"]>["functions"];
34
- /** The bare CEL language under Telo's options: cel-js's built-ins and nothing
35
- * else — no catalog, no `Stream`. The dialect is built on it, and the
36
- * language conformance vectors (`templating/cel-conformance/`) run against it. */
37
- export declare function buildCelLanguageEnvironment(): Environment;
38
- export declare function buildCelEnvironment(handlers?: Partial<CelHandlers>): Environment;
4
+ * **The dialect is no longer declared here.** Telo's 67 functions and their 86 signatures
5
+ * ship inside the engine as data plus implementations, registered through the very
6
+ * `registerFunction` a host uses, so this package no longer carries a catalog table of its
7
+ * own: `registerFunctionCatalog` is what the dialect IS, and `functionCatalog()` is the one
8
+ * listing surface `telo cel functions` reads. What is left here is the pair of environments
9
+ * and the host handlers — the only part that was ever this package's.
10
+ *
11
+ * A second engine reproduces the two separately, so they stay named separately:
12
+ * `buildCelLanguageEnvironment()` is CEL under Telo's options and nothing else, and
13
+ * `buildCelEnvironment(handlers?)` is the dialect built on it.
14
+ */
15
+ import { CelEnvironment, functionCatalog, type CelCatalogHandlers } from "@telorun/cel";
16
+ /** The nine functions the host answers for. The engine's own seam, re-exported so a
17
+ * consumer naming it does not have to name the engine. */
18
+ export type CelHandlers = CelCatalogHandlers;
19
+ /**
20
+ * The bare CEL language under Telo's options: the standard library and nothing else — no
21
+ * catalog, no `Stream`. The dialect is built on it, and the language conformance vectors
22
+ * run against it.
23
+ */
24
+ export declare function buildCelLanguageEnvironment(): CelEnvironment;
25
+ /**
26
+ * Every function the LANGUAGE declares, for documentation that must tell the language and
27
+ * the dialect apart. Subtracting by signature text does not work — a declared `list` is
28
+ * normalized — so the base set is asked for directly.
29
+ */
30
+ export declare function celBuiltinFunctions(): ReturnType<CelEnvironment["definitions"]>["functions"];
31
+ /** Telo's dialect: the language, the function catalog, and the live `Stream` type. */
32
+ export declare function buildCelEnvironment(handlers?: Partial<CelHandlers>): CelEnvironment;
33
+ /** The dialect's functions as the one listing surface answers them. */
34
+ export declare function celFunctionCatalog(): ReturnType<typeof functionCatalog>;
39
35
  //# sourceMappingURL=environment.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../src/cel/environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,OAAO,EAAiB,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAG/D,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAuBhD;;;;;;;;;;;;;;;yDAeyD;AACzD;;;;;wBAKwB;AACxB,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,CAyB5D;AAYD;;;;;yCAKyC;AACzC,wBAAgB,mBAAmB,IAAI,UAAU,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAAC,WAAW,CAAC,CAE5F;AAED;;mFAEmF;AACnF,wBAAgB,2BAA2B,IAAI,WAAW,CAEzD;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,GAAE,OAAO,CAAC,WAAW,CAAM,GAAG,WAAW,CAcpF"}
1
+ {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../src/cel/environment.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,cAAc,EACd,eAAe,EAEf,KAAK,kBAAkB,EACxB,MAAM,cAAc,CAAC;AAEtB;2DAC2D;AAC3D,MAAM,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAyC7C;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,cAAc,CAE5D;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,UAAU,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,WAAW,CAAC,CAE5F;AAED,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,QAAQ,GAAE,OAAO,CAAC,WAAW,CAAM,GAAG,cAAc,CAOvF;AAED,uEAAuE;AACvE,wBAAgB,kBAAkB,IAAI,UAAU,CAAC,OAAO,eAAe,CAAC,CAEvE"}
@@ -1,12 +1,30 @@
1
- import { Environment } from "@marcbachmann/cel-js";
2
- import { Stream } from "@telorun/sdk";
3
- import { CEL_FUNCTIONS } from "./catalog.js";
4
- import { assertCelValueIdentity, SDK_CEL_VALUE_CLASSES } from "./value-identity.js";
5
- assertCelValueIdentity(SDK_CEL_VALUE_CLASSES);
1
+ /**
2
+ * The two environments, now built on `@telorun/cel`.
3
+ *
4
+ * **The dialect is no longer declared here.** Telo's 67 functions and their 86 signatures
5
+ * ship inside the engine as data plus implementations, registered through the very
6
+ * `registerFunction` a host uses, so this package no longer carries a catalog table of its
7
+ * own: `registerFunctionCatalog` is what the dialect IS, and `functionCatalog()` is the one
8
+ * listing surface `telo cel functions` reads. What is left here is the pair of environments
9
+ * and the host handlers — the only part that was ever this package's.
10
+ *
11
+ * A second engine reproduces the two separately, so they stay named separately:
12
+ * `buildCelLanguageEnvironment()` is CEL under Telo's options and nothing else, and
13
+ * `buildCelEnvironment(handlers?)` is the dialect built on it.
14
+ */
15
+ import { CelEnvironment, functionCatalog, registerFunctionCatalog, } from "@telorun/cel";
6
16
  const stub = (name) => () => {
7
17
  throw new Error(`${name}() is not available in this environment. ` +
8
18
  `Construct StaticAnalyzer or Loader with celHandlers to enable it.`);
9
19
  };
20
+ /**
21
+ * What a host-backed function does where the host supplied nothing.
22
+ *
23
+ * The engine's own answer for a missing handler is the `unbound_function` error VALUE,
24
+ * naming the function — which is what an analyzer wants, since it never evaluates. These
25
+ * throw instead, keeping the message this package has always produced for a caller that
26
+ * built an analyzer-only environment and then evaluated through it.
27
+ */
10
28
  const STUB_HANDLERS = {
11
29
  sha256: stub("sha256"),
12
30
  md5: stub("md5"),
@@ -18,93 +36,43 @@ const STUB_HANDLERS = {
18
36
  json: stub("json"),
19
37
  joinPath: stub("joinPath"),
20
38
  };
21
- /** Build a CEL `Environment` with Telo's stdlib. Every function comes from the
22
- * single-source catalog (`CEL_FUNCTIONS`), so registration and the documented
23
- * surface (`telo cel functions`) can never drift. Always registers the same
24
- * signatures (so `env.check()` succeeds for type-inference); the host-injected
25
- * handlers govern what `hostBacked` functions do at runtime. Analyzer-only
26
- * callers can omit handlers (the stubs throw if such a function is evaluated);
27
- * runtime callers (kernel) supply real ones.
28
- *
29
- * Also registers the `Stream` object type, backed by the `Stream` class from
30
- * `@telorun/sdk`. CEL's type-checker rejects values whose constructor isn't
31
- * Object/Map/Array/Set/registered; producers that need to expose an
32
- * `AsyncIterable` through a stream-typed property must wrap the iterable in
33
- * `new Stream(...)` so its constructor is the registered class. The type has
34
- * no fields, so terminal access (passing the value through CEL) succeeds but
35
- * member access raises a CEL error at runtime — matching the analyzer's
36
- * static check on `x-telo-stream`-marked properties. */
37
- /** Expand a documented signature that may contain `type?`-marked optional
38
- * parameters into one cel-js registration signature per arity. For example,
39
- * `"nowIso(string?): string"` produces `["nowIso(): string",
40
- * "nowIso(string): string"]`. Required parameters must precede optional ones.
41
- * Returns `[signature]` unchanged when no `?` is present or the signature
42
- * cannot be parsed. */
43
- export function deriveSignatures(signature) {
44
- const m = signature.match(/^(\w+)\((.*?)\):\s*(.+)$/);
45
- if (!m)
46
- return [signature];
47
- const name = m[1];
48
- const paramsStr = m[2].trim();
49
- const returnType = m[3].trim();
50
- if (!paramsStr.includes("?"))
51
- return [signature];
52
- const params = paramsStr.split(",").map((p) => p.trim());
53
- const required = [];
54
- const optional = [];
55
- for (const p of params) {
56
- if (p.endsWith("?")) {
57
- optional.push(p.slice(0, -1));
58
- }
59
- else {
60
- if (optional.length > 0)
61
- return [signature];
62
- required.push(p);
63
- }
64
- }
65
- if (optional.length === 0)
66
- return [signature];
67
- return Array.from({ length: optional.length + 1 }, (_, i) => {
68
- const allParams = [...required, ...optional.slice(0, i)];
69
- return `${name}(${allParams.join(", ")}): ${returnType}`;
70
- });
71
- }
72
- /** cel-go defaults HomogeneousAggregateLiterals OFF: heterogeneous list/map
73
- * literals unify to `dyn` rather than erroring. cel-js flips that default to
74
- * strict; we align with cel-go so manifests (dyn-heavy: request, rows, …)
75
- * don't hit false positives the runtime evaluates fine. */
39
+ /**
40
+ * cel-go defaults HomogeneousAggregateLiterals OFF: heterogeneous list/map literals unify
41
+ * to `dyn` rather than erroring, which is what a manifest needs (`request`, rows, …).
42
+ * `unlistedVariablesAreDyn` is on because a host types only part of what a site may read,
43
+ * and optional types are on because the manifest surface uses them.
44
+ */
76
45
  const ENVIRONMENT_OPTIONS = {
77
46
  unlistedVariablesAreDyn: true,
78
47
  enableOptionalTypes: true,
79
48
  homogeneousAggregateLiterals: false,
80
49
  };
81
- /** The environment before any Telo function is registered — i.e. exactly
82
- * cel-js's own built-ins. Documentation needs to tell the two apart, and
83
- * subtracting by signature TEXT does not work: cel-js normalizes a declared
84
- * `list` to `list<dyn>`, so the catalog's documented spelling and the
85
- * registered one differ for a third of the entries. Asking for the base set
86
- * directly needs no matching at all. */
87
- export function celBuiltinFunctions() {
88
- return buildCelLanguageEnvironment().getDefinitions().functions;
89
- }
90
- /** The bare CEL language under Telo's options: cel-js's built-ins and nothing
91
- * else — no catalog, no `Stream`. The dialect is built on it, and the
92
- * language conformance vectors (`templating/cel-conformance/`) run against it. */
50
+ /**
51
+ * The bare CEL language under Telo's options: the standard library and nothing else — no
52
+ * catalog, no `Stream`. The dialect is built on it, and the language conformance vectors
53
+ * run against it.
54
+ */
93
55
  export function buildCelLanguageEnvironment() {
94
- return new Environment(ENVIRONMENT_OPTIONS);
56
+ return new CelEnvironment(ENVIRONMENT_OPTIONS);
95
57
  }
58
+ /**
59
+ * Every function the LANGUAGE declares, for documentation that must tell the language and
60
+ * the dialect apart. Subtracting by signature text does not work — a declared `list` is
61
+ * normalized — so the base set is asked for directly.
62
+ */
63
+ export function celBuiltinFunctions() {
64
+ return buildCelLanguageEnvironment().definitions().functions;
65
+ }
66
+ /** Telo's dialect: the language, the function catalog, and the live `Stream` type. */
96
67
  export function buildCelEnvironment(handlers = {}) {
97
- const h = { ...STUB_HANDLERS, ...handlers };
98
- let env = buildCelLanguageEnvironment();
99
- for (const fn of CEL_FUNCTIONS) {
100
- const impl = fn.build(h);
101
- // `register` lists one cel-js signature per arity (overloaded functions).
102
- // When absent, `deriveSignatures` expands `type?` optional-param notation
103
- // into one registration per arity — so `nowIso(string?): string` registers
104
- // both `nowIso(): string` and `nowIso(string): string` automatically.
105
- for (const sig of fn.register ?? deriveSignatures(fn.signature)) {
106
- env = env.registerFunction(sig, impl);
107
- }
108
- }
109
- return env.registerType("Stream", Stream);
68
+ const environment = buildCelLanguageEnvironment();
69
+ registerFunctionCatalog(environment, { handlers: { ...STUB_HANDLERS, ...handlers } });
70
+ // A live handle: `dyn` underneath with no conversion and no member, so reading anything
71
+ // off one is refused at check. It needs no constructor — identity by class is what the
72
+ // engine replaced, and at runtime a stream is whatever the producer handed over.
73
+ return environment.registerType({ name: "Stream", base: "dyn" });
74
+ }
75
+ /** The dialect's functions as the one listing surface answers them. */
76
+ export function celFunctionCatalog() {
77
+ return functionCatalog();
110
78
  }