@telorun/templating 0.20.1 → 0.21.1

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 (40) hide show
  1. package/dist/cel/analyze.d.ts +26 -0
  2. package/dist/cel/analyze.d.ts.map +1 -1
  3. package/dist/cel/analyze.js +114 -8
  4. package/dist/cel/catalog.d.ts.map +1 -1
  5. package/dist/cel/catalog.js +10 -0
  6. package/dist/cel/compile.d.ts +9 -3
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +52 -11
  9. package/dist/cel/diagnose.d.ts +10 -1
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +42 -6
  12. package/dist/cel/environment.d.ts.map +1 -1
  13. package/dist/cel/environment.js +2 -0
  14. package/dist/cel/module-call.d.ts +108 -0
  15. package/dist/cel/module-call.d.ts.map +1 -0
  16. package/dist/cel/module-call.js +245 -0
  17. package/dist/cel/value-identity.d.ts +18 -0
  18. package/dist/cel/value-identity.d.ts.map +1 -0
  19. package/dist/cel/value-identity.js +25 -0
  20. package/dist/engine.d.ts +66 -0
  21. package/dist/engine.d.ts.map +1 -1
  22. package/dist/engines/cel.d.ts.map +1 -1
  23. package/dist/engines/cel.js +87 -6
  24. package/dist/engines/sql.d.ts.map +1 -1
  25. package/dist/engines/sql.js +5 -1
  26. package/dist/index.d.ts +3 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -1
  29. package/package.json +3 -3
  30. package/src/cel/analyze.ts +131 -9
  31. package/src/cel/catalog.ts +10 -0
  32. package/src/cel/compile.ts +59 -12
  33. package/src/cel/diagnose.ts +56 -6
  34. package/src/cel/environment.ts +3 -0
  35. package/src/cel/module-call.ts +369 -0
  36. package/src/cel/value-identity.ts +34 -0
  37. package/src/engine.ts +72 -0
  38. package/src/engines/cel.ts +104 -6
  39. package/src/engines/sql.ts +5 -1
  40. package/src/index.ts +20 -1
@@ -1,5 +1,6 @@
1
1
  import type { ASTNode, Environment } from "@marcbachmann/cel-js";
2
2
  import { CEL_FUNCTIONS, type CelFunctionDoc } from "./catalog.js";
3
+ import { moduleCallOf } from "./module-call.js";
3
4
  import type { CallSite, DiagnosticFix, EngineDiagnostic } from "../engine.js";
4
5
 
5
6
  /** Classifies every function call in a CEL expression against the environment's
@@ -37,6 +38,15 @@ export interface FunctionIndex {
37
38
  const DETERMINISM: ReadonlyMap<string, boolean> = new Map(
38
39
  CEL_FUNCTIONS.map((f) => [f.name, f.deterministic]),
39
40
  );
41
+ const HOST_BACKED: ReadonlyMap<string, boolean> = new Map(
42
+ CEL_FUNCTIONS.map((f) => [f.name, f.hostBacked === true]),
43
+ );
44
+
45
+ /** The flags a module function carries, as the host that resolves it derives
46
+ * them — or undefined where the name reaches no function. */
47
+ export type ModuleCallFlags = (
48
+ qualified: string,
49
+ ) => { readonly deterministic: boolean; readonly hostBacked: boolean } | undefined;
40
50
 
41
51
  const INDEX_CACHE = new WeakMap<Environment, FunctionIndex>();
42
52
 
@@ -84,13 +94,40 @@ function isNode(v: unknown): v is ASTNode {
84
94
  }
85
95
 
86
96
  /** Every non-macro call in the expression, in source order. */
87
- function collectCalls(root: ASTNode, index: FunctionIndex): RawCall[] {
97
+ function collectCalls(
98
+ root: ASTNode,
99
+ index: FunctionIndex,
100
+ moduleCallFlags: ModuleCallFlags | undefined,
101
+ ): RawCall[] {
88
102
  const out: RawCall[] = [];
89
103
  visit(root);
90
104
  return out.sort((a, b) => a.start - b.start);
91
105
 
92
106
  function visit(node: ASTNode): void {
93
107
  const args = node.args as unknown;
108
+ // A RESOLVED module call is reported under its QUALIFIED name and is never
109
+ // looked up in the catalog: the two namespaces are disjoint by construction
110
+ // (a bare name is always the catalog), so classifying it here would report
111
+ // `there is no function 'format'` for a call that names a module's own, and
112
+ // attaching the catalog's determinism to it would be a flag about a
113
+ // different function entirely. What a module call's flags are is the
114
+ // resolving host's answer, carried when it gives one.
115
+ const moduleCall = moduleCallOf(node);
116
+ if (moduleCall) {
117
+ const flags = moduleCallFlags?.(moduleCall.qualified);
118
+ out.push({
119
+ name: moduleCall.qualified,
120
+ form: "receiver",
121
+ moduleCall: true,
122
+ arity: moduleCall.args.length,
123
+ start: node.start,
124
+ end: node.end,
125
+ ...(flags ? { deterministic: flags.deterministic, hostBacked: flags.hostBacked } : {}),
126
+ args: moduleCall.args,
127
+ });
128
+ for (const arg of moduleCall.args) visit(arg);
129
+ return;
130
+ }
94
131
  if (node.op === "call" || node.op === "rcall") {
95
132
  const tuple = args as unknown[];
96
133
  const name = tuple[0];
@@ -104,7 +141,9 @@ function collectCalls(root: ASTNode, index: FunctionIndex): RawCall[] {
104
141
  arity: callArgs.length,
105
142
  start: node.start,
106
143
  end: node.end,
107
- ...(index.byName.has(name) ? { deterministic: DETERMINISM.get(name) } : {}),
144
+ ...(index.byName.has(name)
145
+ ? { deterministic: DETERMINISM.get(name), hostBacked: HOST_BACKED.get(name) }
146
+ : {}),
108
147
  ...(isNode(receiver) ? { receiver } : {}),
109
148
  args: callArgs,
110
149
  });
@@ -176,8 +215,8 @@ const listOf = (names: readonly string[]): string => [...new Set(names)].sort().
176
215
 
177
216
  /** Names registered in exactly the form and arity the author wrote — the only
178
217
  * ones that could replace this call with no further edits. Ranked by shared
179
- * prefix, which is what reaches `nowIso` from `now`; edit distance never
180
- * would (3 characters against a 3-character name). Returns [] when nothing
218
+ * prefix, which is what reaches `nowIso` from `no`; edit distance never
219
+ * would (4 characters against a 2-character name). Returns [] when nothing
181
220
  * shares a prefix, so the caller lists what is legal here instead of
182
221
  * guessing. */
183
222
  function candidates(call: RawCall, index: FunctionIndex): string[] {
@@ -249,13 +288,24 @@ export interface CallAudit {
249
288
  * failed type-check, because a type-check reports its first error and stops:
250
289
  * an expression with two bad calls would otherwise fix one, re-run, and
251
290
  * discover the next. */
252
- export function auditCalls(source: string, ast: ASTNode, env: Environment): CallAudit {
291
+ export function auditCalls(
292
+ source: string,
293
+ ast: ASTNode,
294
+ env: Environment,
295
+ /** The flags of the module functions the expression calls, from whoever
296
+ * resolves them. */
297
+ moduleCallFlags?: ModuleCallFlags,
298
+ ): CallAudit {
253
299
  const index = functionIndex(env);
254
300
  const diagnostics: EngineDiagnostic[] = [];
255
301
  const unresolved: string[] = [];
256
- const calls = collectCalls(ast, index);
302
+ const calls = collectCalls(ast, index, moduleCallFlags);
257
303
 
258
304
  for (const call of calls) {
305
+ // Resolution already decided what a module call names. The catalog has
306
+ // nothing to say about it, and saying it anyway would be a refusal of valid
307
+ // CEL.
308
+ if (call.moduleCall) continue;
259
309
  const entries = index.byName.get(call.name);
260
310
  const noun = call.form === "receiver" ? "method" : "function";
261
311
 
@@ -1,9 +1,12 @@
1
1
  import { Environment } from "@marcbachmann/cel-js";
2
2
  import { Stream } from "@telorun/sdk";
3
3
  import { CEL_FUNCTIONS, type CelHandlers } from "./catalog.js";
4
+ import { assertCelValueIdentity, SDK_CEL_VALUE_CLASSES } from "./value-identity.js";
4
5
 
5
6
  export type { CelHandlers } from "./catalog.js";
6
7
 
8
+ assertCelValueIdentity(SDK_CEL_VALUE_CLASSES);
9
+
7
10
  const stub = (name: string) => () => {
8
11
  throw new Error(
9
12
  `${name}() is not available in this environment. ` +
@@ -0,0 +1,369 @@
1
+ /**
2
+ * **A call whose receiver is one of the declaring module's names.**
3
+ *
4
+ * `Billing.format(x)`, `Self.y(1)`, `<ModuleName>.y(1)` — CEL's own
5
+ * qualified-function rule, the one `cel.bind` and cel-go's `math.greatest`
6
+ * already follow. Resolution happens on the PARSED TREE, right after
7
+ * `env.parse` and before any check: the author's text, spans and the expression
8
+ * a trace shows stay exactly as written, which rewriting the source would move.
9
+ *
10
+ * A module's names are known from its own file before any import resolves — its
11
+ * `imports:` keys, `Self`, its `metadata.name` and `Telo` — so the set is an
12
+ * INPUT here rather than something this module derives. A call on a bare
13
+ * identifier outside the set stays an ordinary method call, which is what keeps
14
+ * the catalog's `format` and `Billing.format` from ever colliding, with one
15
+ * catalog environment compiling both.
16
+ *
17
+ * Two engine internals carry it, neither exposed by cel-js's typings — hence
18
+ * the exact version pin and `tests/module-call.test.ts`, which fails the moment
19
+ * an upgrade moves either:
20
+ *
21
+ * - `ASTNode.setMeta('macro', …)` redirects a node's check and evaluation. A
22
+ * comprehension macro (`map`, `filter`, …) sets `alternate` instead, and
23
+ * `alternate` WINS over `macro`, so a call the parser expanded as a macro
24
+ * needs it cleared or the rewrite is silently ignored. The parser expands
25
+ * those names BEFORE this rewrite and refuses any call whose arguments do not
26
+ * fit the macro, so no function may take a macro's name
27
+ * (`FUNCTION_NAME_RESERVED`); clearing keeps a call that did parse reported
28
+ * as the module call it names.
29
+ * - `async` must be set explicitly: cel-js derives it for an `rcall` from
30
+ * `receiverWithArgs`, which only the rcall's own checker fills in — and ours
31
+ * replaces it.
32
+ *
33
+ * The dispatch table is read from the activation under a key no CEL source can
34
+ * spell, so nothing an author can write reaches the mechanism past the export
35
+ * gate or the dependency edge. Binding the table is the kernel's, per scope;
36
+ * until something binds one, evaluating a module call throws naming the
37
+ * function.
38
+ */
39
+ import type { ASTNode } from "@marcbachmann/cel-js";
40
+
41
+ /**
42
+ * Activation key the per-scope dispatch table is read from.
43
+ *
44
+ * `@` and `:` are outside CEL's identifier grammar and there is no other way to
45
+ * reach the activation, so no expression can name this — a spellable dispatcher
46
+ * would let an author call past the export gate and past the dependency edge
47
+ * that orders the callee before its caller.
48
+ */
49
+ export const MODULE_CALL_DISPATCH_KEY = "@telo:module-functions";
50
+
51
+ /** Per-scope binding table: qualified name → the callable's `call`. */
52
+ export type ModuleCallDispatch = ReadonlyMap<string, (args: readonly unknown[]) => unknown>;
53
+
54
+ /**
55
+ * The CEL type a qualified call yields, as a type name (`"string"`,
56
+ * `"list<int>"`), or undefined for "not known here".
57
+ *
58
+ * A hook rather than a table because the answer belongs to the analysis, not to
59
+ * the expression: a signature is declared on a resource in the module the call
60
+ * resolves through. With no resolver — every compile, and every analysis until
61
+ * signatures are typed — a module call is `dyn`, which types its arguments and
62
+ * claims nothing about its result.
63
+ */
64
+ export type ModuleCallTypeResolver = (qualified: string) => string | undefined;
65
+
66
+ /** cel-js internals this module drives. Structural, because the package's
67
+ * typings expose neither `meta` nor `setMeta`. */
68
+ interface MetaNode {
69
+ readonly meta?: Record<string, unknown>;
70
+ setMeta(key: string, value: unknown): MetaNode;
71
+ }
72
+
73
+ /** cel-js's `ASTNode` is a union over its operators, so it has no statically
74
+ * known members to extend — the internals are read through this cast, in one
75
+ * place. */
76
+ const metaOf = (node: ASTNode): MetaNode => node as unknown as MetaNode;
77
+
78
+ /** The macro record a resolved node carries. `teloModuleCall` is the brand every
79
+ * reader tests — cel-js puts its own macros under the same key. */
80
+ interface ModuleCallMacro {
81
+ readonly teloModuleCall: true;
82
+ readonly qualified: string;
83
+ readonly args: readonly ASTNode[];
84
+ /** Each argument's checked type name, recorded by the last type check. */
85
+ argumentTypes?: readonly string[];
86
+ typeCheck(chk: TypeCheckerLike, macro: ModuleCallMacro, ctx: unknown): unknown;
87
+ evaluate(ev: EvaluatorLike, macro: ModuleCallMacro, ctx: ActivationLike): unknown;
88
+ }
89
+
90
+ interface TypeCheckerLike {
91
+ readonly dynType: unknown;
92
+ check(node: ASTNode, ctx: unknown): unknown;
93
+ getType(name: string): unknown;
94
+ }
95
+
96
+ interface EvaluatorLike {
97
+ eval(node: ASTNode, ctx: unknown): unknown;
98
+ }
99
+
100
+ interface ActivationLike {
101
+ getValue(key: string): unknown;
102
+ }
103
+
104
+ /** What a resolved module call says about itself: the qualified name as
105
+ * written, the argument nodes, and — once the tree has been type-checked — the
106
+ * type the checker gave each argument. The single reader — no other surface
107
+ * pattern-matches the macro's shape. */
108
+ export interface ModuleCall {
109
+ readonly qualified: string;
110
+ readonly args: readonly ASTNode[];
111
+ readonly argumentTypes?: readonly string[];
112
+ }
113
+
114
+ export function moduleCallOf(node: ASTNode): ModuleCall | undefined {
115
+ const macro = metaOf(node).meta?.macro as ModuleCallMacro | undefined;
116
+ return macro?.teloModuleCall === true
117
+ ? {
118
+ qualified: macro.qualified,
119
+ args: macro.args,
120
+ ...(macro.argumentTypes ? { argumentTypes: macro.argumentTypes } : {}),
121
+ }
122
+ : undefined;
123
+ }
124
+
125
+ /** Message for a call nothing has bound. Not a fallback value: a call that
126
+ * cannot reach its function has no result, and inventing one would make a
127
+ * missing export read as a null. */
128
+ export function unboundModuleCallMessage(qualified: string): string {
129
+ const dot = qualified.indexOf(".");
130
+ const receiver = qualified.slice(0, dot);
131
+ const fn = qualified.slice(dot + 1);
132
+ return (
133
+ `unbound function '${qualified}' — nothing is bound under that name in this scope. ` +
134
+ `'${receiver}' must be an imports: alias (or Self, or this module's own name) whose ` +
135
+ `module declares a callable named '${fn}' and exports it.`
136
+ );
137
+ }
138
+
139
+ const NO_NAMES: ReadonlySet<string> = new Set();
140
+
141
+ /**
142
+ * Rewrite every module call in `ast` in place and report them in source order.
143
+ *
144
+ * Returns the qualified names as written (`["Billing.format", "Self.y"]`), which
145
+ * is what a compiled value carries so no consumer has to re-parse to learn what
146
+ * an expression calls. Idempotent: a node already resolved is rewritten once and
147
+ * reported again, so two passes over one tree agree about what it calls.
148
+ */
149
+ export function resolveModuleCalls(
150
+ ast: ASTNode | undefined,
151
+ moduleNames: ReadonlySet<string> = NO_NAMES,
152
+ typeOf?: ModuleCallTypeResolver,
153
+ ): string[] {
154
+ const calls: string[] = [];
155
+ if (ast && moduleNames.size > 0) visit(ast, moduleNames, typeOf, calls);
156
+ return calls;
157
+ }
158
+
159
+ function visit(
160
+ node: ASTNode,
161
+ moduleNames: ReadonlySet<string>,
162
+ typeOf: ModuleCallTypeResolver | undefined,
163
+ calls: string[],
164
+ ): void {
165
+ // Already resolved: rewritten once, reported every time, so the return value
166
+ // is what the TREE calls rather than what this pass happened to change.
167
+ const resolved = moduleCallOf(node);
168
+ if (resolved) {
169
+ calls.push(resolved.qualified);
170
+ for (const arg of resolved.args) visit(arg, moduleNames, typeOf, calls);
171
+ return;
172
+ }
173
+
174
+ const receiver = moduleCallReceiver(node, moduleNames);
175
+ if (receiver) {
176
+ const [method, , args] = node.args as [string, ASTNode, ASTNode[]];
177
+ const qualified = `${receiver}.${method}`;
178
+ calls.push(qualified);
179
+ rewrite(node, qualified, args, typeOf);
180
+ // The receiver names a MODULE, not a value, so it is not descended into:
181
+ // that is what keeps it out of every access chain, out of `refs`, and out
182
+ // of the undeclared-root check.
183
+ for (const arg of args) visit(arg, moduleNames, typeOf, calls);
184
+ return;
185
+ }
186
+ descend(node, (child) => visit(child, moduleNames, typeOf, calls));
187
+ }
188
+
189
+ /** The module name a node's receiver is, or undefined when the node is not a
190
+ * module call. `a.b.c(x)` is not one — its receiver is a member access, not a
191
+ * bare identifier. */
192
+ function moduleCallReceiver(
193
+ node: ASTNode,
194
+ moduleNames: ReadonlySet<string>,
195
+ ): string | undefined {
196
+ if (node.op !== "rcall" || !Array.isArray(node.args)) return undefined;
197
+ const [method, receiver, args] = node.args as [unknown, unknown, unknown];
198
+ if (typeof method !== "string" || !Array.isArray(args)) return undefined;
199
+ if (!isNode(receiver) || receiver.op !== "id") return undefined;
200
+ const name = receiver.args as string;
201
+ return moduleNames.has(name) ? name : undefined;
202
+ }
203
+
204
+ function rewrite(
205
+ node: ASTNode,
206
+ qualified: string,
207
+ args: readonly ASTNode[],
208
+ typeOf: ModuleCallTypeResolver | undefined,
209
+ ): void {
210
+ const macro: ModuleCallMacro = {
211
+ teloModuleCall: true,
212
+ qualified,
213
+ args,
214
+ typeCheck(chk, m, ctx) {
215
+ // The arguments are checked in the CURRENT context, so a mistake inside
216
+ // one is reported where it is written — and each argument's type is kept,
217
+ // so whoever knows the callee's signature can compare against it.
218
+ m.argumentTypes = m.args.map((arg) => typeNameOf(chk.check(arg, ctx)));
219
+ // cel-js derives an rcall's asyncness from `receiverWithArgs`, which only
220
+ // the rcall checker this macro replaces fills in — so it is stated: the
221
+ // dispatch is synchronous, so the node is async exactly when one of its
222
+ // arguments is. Asked only now, once each argument is checked: an
223
+ // argument's answer is cached on first reading, and read before its own
224
+ // check it is the conservative `true` for every operator and call.
225
+ metaOf(node).setMeta(
226
+ "async",
227
+ m.args.some((arg) => (arg as { maybeAsync?: boolean }).maybeAsync === true),
228
+ );
229
+ const declared = typeOf?.(m.qualified);
230
+ return declared === undefined ? chk.dynType : chk.getType(declared);
231
+ },
232
+ evaluate(ev, m, ctx) {
233
+ const table = ctx.getValue(MODULE_CALL_DISPATCH_KEY) as ModuleCallDispatch | undefined;
234
+ const fn = table?.get(m.qualified);
235
+ if (!fn) throw new Error(unboundModuleCallMessage(m.qualified));
236
+ const values = m.args.map((arg) => ev.eval(arg, ctx));
237
+ // A callable's `call` is synchronous; an ARGUMENT need not be, and every
238
+ // other dispatch in cel-js settles its operands first. Handing a pending
239
+ // Promise to the function instead would pass it a value of the wrong type
240
+ // with nothing reported.
241
+ return values.some((value) => value instanceof Promise)
242
+ ? Promise.all(values).then((settled) => fn(settled))
243
+ : fn(values);
244
+ },
245
+ };
246
+ metaOf(node)
247
+ // A comprehension macro expands into an `alternate`, which cel-js consults
248
+ // BEFORE `macro`. Left in place, `Billing.map(i, i)` would evaluate as a
249
+ // comprehension over an identifier rather than as the module call it names.
250
+ .setMeta("alternate", undefined)
251
+ .setMeta("macro", macro);
252
+ }
253
+
254
+ /** Every resolved module call in `ast` with its node, outermost first. */
255
+ export function moduleCallNodes(ast: ASTNode | undefined): Array<{ node: ASTNode; call: ModuleCall }> {
256
+ const out: Array<{ node: ASTNode; call: ModuleCall }> = [];
257
+ if (ast) walk(ast);
258
+ return out;
259
+
260
+ function walk(node: ASTNode): void {
261
+ const call = moduleCallOf(node);
262
+ if (call) {
263
+ out.push({ node, call });
264
+ for (const arg of call.args) walk(arg);
265
+ return;
266
+ }
267
+ descend(node, walk);
268
+ }
269
+ }
270
+
271
+ /** The name of a checker type object (`int`, `list<string>`), or `dyn` for one
272
+ * that carries none. */
273
+ function typeNameOf(type: unknown): string {
274
+ const name = (type as { name?: unknown } | null | undefined)?.name;
275
+ return typeof name === "string" ? name : "dyn";
276
+ }
277
+
278
+ /**
279
+ * Bare identifiers used as a call receiver that resolved to NO module name.
280
+ *
281
+ * `Foo.bar()` with no `Foo` import is an unknown identifier like any other, but
282
+ * the repair is not the usual one — it needs an `imports:` alias, not a
283
+ * different spelling — so the caller that reports the root says so.
284
+ */
285
+ export function unresolvedCallReceivers(
286
+ ast: ASTNode | undefined,
287
+ moduleNames: ReadonlySet<string> = NO_NAMES,
288
+ ): Set<string> {
289
+ const out = new Set<string>();
290
+ if (ast) walk(ast);
291
+ return out;
292
+
293
+ function walk(node: ASTNode): void {
294
+ if (moduleCallOf(node)) {
295
+ for (const arg of (node.args as [string, ASTNode, ASTNode[]])[2]) walk(arg);
296
+ return;
297
+ }
298
+ if (node.op === "rcall" && Array.isArray(node.args)) {
299
+ const receiver = (node.args as [unknown, unknown, unknown])[1];
300
+ if (isNode(receiver) && receiver.op === "id" && !moduleNames.has(receiver.args as string)) {
301
+ out.add(receiver.args as string);
302
+ }
303
+ }
304
+ descend(node, walk);
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Names bound INSIDE the expression — a comprehension variable, a `cel.bind`
310
+ * name — that collide with one of the module's names.
311
+ *
312
+ * Such a binding is unreachable through a call: `Billing.f(x)` inside it
313
+ * resolves to the module, never to the bound value. Reported as a reserved name
314
+ * rather than silently shadowed, which is the rule every other name in CEL
315
+ * scope already follows.
316
+ */
317
+ export function moduleNameBindings(
318
+ ast: ASTNode | undefined,
319
+ moduleNames: ReadonlySet<string> = NO_NAMES,
320
+ ): string[] {
321
+ const out: string[] = [];
322
+ if (ast && moduleNames.size > 0) walk(ast);
323
+ return [...new Set(out)];
324
+
325
+ function walk(node: ASTNode): void {
326
+ const bound = boundNameOf(node);
327
+ if (bound !== undefined && moduleNames.has(bound)) out.push(bound);
328
+ descend(node, walk);
329
+ }
330
+ }
331
+
332
+ /** The name a binding form introduces: `cel.bind(<name>, …)`'s first argument,
333
+ * or a comprehension macro's iteration variable. */
334
+ function boundNameOf(node: ASTNode): string | undefined {
335
+ if (node.op !== "rcall" || !Array.isArray(node.args)) return undefined;
336
+ if (moduleCallOf(node)) return undefined;
337
+ const [method, receiver, args] = node.args as [unknown, unknown, unknown];
338
+ if (!Array.isArray(args) || args.length === 0) return undefined;
339
+ const first = args[0];
340
+ if (!isNode(first) || first.op !== "id") return undefined;
341
+ if (method === "bind") {
342
+ return isNode(receiver) && receiver.op === "id" && receiver.args === "cel"
343
+ ? (first.args as string)
344
+ : undefined;
345
+ }
346
+ return COMPREHENSION_METHODS.has(method as string) ? (first.args as string) : undefined;
347
+ }
348
+
349
+ /** cel-js's comprehension macros, which bind their first argument as the
350
+ * iteration variable. Mirrors the set `analyze.ts` walks with. */
351
+ const COMPREHENSION_METHODS = new Set(["filter", "map", "exists", "all", "exists_one"]);
352
+
353
+ /** Generic descent over a node's operands — an array, a single node, or an
354
+ * array of arrays (a map literal's entries). */
355
+ function descend(node: ASTNode, fn: (child: ASTNode) => void): void {
356
+ const args = node.args as unknown;
357
+ if (Array.isArray(args)) {
358
+ for (const arg of args) {
359
+ if (isNode(arg)) fn(arg);
360
+ else if (Array.isArray(arg)) for (const item of arg) if (isNode(item)) fn(item);
361
+ }
362
+ return;
363
+ }
364
+ if (isNode(args)) fn(args);
365
+ }
366
+
367
+ function isNode(v: unknown): v is ASTNode {
368
+ return v !== null && typeof v === "object" && "op" in (v as Record<string, unknown>);
369
+ }
@@ -0,0 +1,34 @@
1
+ import { Environment } from "@marcbachmann/cel-js";
2
+ import { Duration, UnsignedInt } from "@telorun/sdk";
3
+
4
+ /** The classes the CEL value domain is typed by. */
5
+ export interface CelValueClasses {
6
+ readonly Duration: abstract new (...args: never[]) => unknown;
7
+ readonly UnsignedInt: abstract new (...args: never[]) => unknown;
8
+ }
9
+
10
+ /**
11
+ * Refuse to run with a CEL engine whose values are not the SDK's.
12
+ *
13
+ * cel-js dispatches by constructor, so a second installed copy of it gives the
14
+ * engine a `Duration` / `UnsignedInt` no controller can construct: every value a
15
+ * controller builds from `@telorun/sdk` would fail `+`, `type()` and every
16
+ * overload, at the first expression that meets one. Checked once, where the
17
+ * engine is loaded, so the cause is named before anything evaluates.
18
+ */
19
+ export function assertCelValueIdentity(classes: CelValueClasses): void {
20
+ const probe = new Environment();
21
+ const duration = probe.evaluate("duration('1s')");
22
+ const uint = probe.evaluate("1u");
23
+ if (duration instanceof classes.Duration && uint instanceof classes.UnsignedInt) return;
24
+ throw new Error(
25
+ "@telorun/templating's CEL engine is a different copy of @marcbachmann/cel-js than the one " +
26
+ "@telorun/sdk exports Duration and UnsignedInt from, so a duration or uint a controller " +
27
+ "builds would be rejected by every CEL expression. Two copies of @marcbachmann/cel-js are " +
28
+ "installed: every Telo package pins the same exact version, so deduplicate the install " +
29
+ "(`pnpm dedupe` / `npm dedupe`) until one remains.",
30
+ );
31
+ }
32
+
33
+ /** The SDK's classes — the identity every Telo package and controller shares. */
34
+ export const SDK_CEL_VALUE_CLASSES: CelValueClasses = { Duration, UnsignedInt };
package/src/engine.ts CHANGED
@@ -1,11 +1,25 @@
1
1
  import type { Environment } from "@marcbachmann/cel-js";
2
2
  import type { CompiledValue } from "@telorun/sdk";
3
+ import type { ModuleCallFlags } from "./cel/diagnose.js";
4
+ import type { ModuleCallTypeResolver } from "./cel/module-call.js";
3
5
 
4
6
  /** Compile-time environment passed to `engine.compile`. Engines that need to
5
7
  * parse against a CEL environment (the `cel` engine) read it from `celEnv`;
6
8
  * engines that resolve fully at compile time (`literal`) ignore it. */
7
9
  export interface CompileEnv {
8
10
  readonly celEnv: Environment;
11
+ /**
12
+ * The names a call's receiver may be for the call to resolve as a MODULE
13
+ * call — the declaring module's `imports:` keys, `Self`, its `metadata.name`
14
+ * and `Telo`.
15
+ *
16
+ * An INPUT, not something an engine derives: they are known from the module's
17
+ * own file before any import resolves, and a partial compiles with the names
18
+ * of the module that includes it. Absent means "no module names here", which
19
+ * leaves every call an ordinary catalog call — the reading every caller had
20
+ * before module functions existed.
21
+ */
22
+ readonly moduleNames?: ReadonlySet<string>;
9
23
  }
10
24
 
11
25
  /** Analyze-time environment passed to `engine.analyze`. The walker resolves
@@ -33,6 +47,38 @@ export interface AnalyzeEnv {
33
47
  * did before it existed.
34
48
  */
35
49
  readonly rootsDeclared?: boolean;
50
+
51
+ /** The declaring module's names — see {@link CompileEnv.moduleNames}. An
52
+ * analysis that does not supply them reads a module call as an ordinary
53
+ * method call, so the compile and analyze halves must be given the same set
54
+ * or they disagree about what the expression says. */
55
+ readonly moduleNames?: ReadonlySet<string>;
56
+
57
+ /** The type a module call yields, when the caller can resolve one. Absent
58
+ * leaves every module call `dyn` — its arguments are still checked where
59
+ * they are written, and nothing is claimed about its result. */
60
+ readonly moduleCallType?: ModuleCallTypeResolver;
61
+
62
+ /** The JSON Schema a module call's RESULT carries, when the caller can resolve
63
+ * one — what member access on the result (`Billing.total(xs).amont`) is
64
+ * checked against. Absent leaves such access unchecked. */
65
+ readonly moduleCallResult?: (qualified: string) => Record<string, unknown> | undefined;
66
+
67
+ /** The derived flags of the module function a qualified call reaches, carried
68
+ * onto its {@link CallSite} — boolean wherever the call resolves, so a
69
+ * consumer reading `deterministic === false` sees every impure one. */
70
+ readonly moduleCallFlags?: ModuleCallFlags;
71
+
72
+ /**
73
+ * Whether a bare identifier could denote a MODULE at all.
74
+ *
75
+ * The host's naming rule, which this package does not own: an unknown call
76
+ * receiver is repaired by an `imports:` alias only where the name could be
77
+ * one, and telling the author of `dbb.query(1)` to add an import is advice
78
+ * for a different mistake. Absent leaves the unknown-identifier message
79
+ * unqualified, which is what it says with no host rule to consult.
80
+ */
81
+ readonly couldNameModule?: (name: string) => boolean;
36
82
  }
37
83
 
38
84
  /** A mechanically applicable repair for a diagnostic. `replacement` is the
@@ -68,11 +114,26 @@ export interface EngineDiagnostic {
68
114
  * call), and policy that depends on manifest context does not belong in a
69
115
  * templating engine. */
70
116
  export interface CallSite {
117
+ /** The name called. For a module call this is the QUALIFIED name as written
118
+ * (`Billing.format`), which is what keeps a module function and a catalog
119
+ * function of the same bare name apart in every consumer that keys on it. */
71
120
  readonly name: string;
72
121
  /** How it was written — `f(x)` vs `x.f()`. */
73
122
  readonly form: "global" | "receiver";
123
+ /** Set when the receiver is one of the declaring module's names, so the call
124
+ * resolved to a module function rather than to the catalog. Its determinism
125
+ * and host-backedness are not this engine's to know — they follow from the
126
+ * callable the name resolves to — so they are carried only as the host's
127
+ * {@link AnalyzeEnv.moduleCallFlags} reports them. */
128
+ readonly moduleCall?: true;
74
129
  /** Argument count as written; excludes the receiver. */
75
130
  readonly arity: number;
131
+ /** For a module call, each argument as the analysis saw it: the type the
132
+ * checker gave it (absent when the expression did not type-check) and, when
133
+ * the argument is a plain member chain (`variables.price`), that chain — so a
134
+ * caller holding the callee's signature can compare a declared shape rather
135
+ * than a CEL type alone. */
136
+ readonly arguments?: readonly CallArgument[];
76
137
  /** Offsets of the whole call within the analyzed source. */
77
138
  readonly start: number;
78
139
  readonly end: number;
@@ -80,6 +141,17 @@ export interface CallSite {
80
141
  * name resolves to nothing, or to a function carrying no determinism
81
142
  * metadata — absent is not "deterministic". */
82
143
  readonly deterministic?: boolean;
144
+ /** Whether the resolved function is supplied by the host rather than written
145
+ * in CEL — a catalog function the kernel implements natively, or a module
146
+ * function reaching native code — so nothing without that host can run it.
147
+ * `undefined` under the same rule as {@link CallSite.deterministic}. */
148
+ readonly hostBacked?: boolean;
149
+ }
150
+
151
+ /** One argument of a module call. */
152
+ export interface CallArgument {
153
+ readonly type?: string;
154
+ readonly chain?: readonly string[];
83
155
  }
84
156
 
85
157
  /** What one `analyze` call establishes about one source. Everything derivable