@telorun/templating 0.4.1 → 0.6.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.
@@ -0,0 +1,540 @@
1
+ import { v1, v3, v4, v5, v6, v7, validate as uuidValidate, version as uuidVersion } from "uuid";
2
+
3
+ /** Host-injected functions that need platform APIs the templating package must
4
+ * not import directly (Node `crypto` / `Buffer`), keeping it browser-safe. The
5
+ * kernel supplies real implementations; the analyzer omits them (the stubs
6
+ * throw, since static analysis never executes these). */
7
+ export interface CelHandlers {
8
+ sha256: (s: string) => string;
9
+ md5: (s: string) => string;
10
+ sha1: (s: string) => string;
11
+ sha512: (s: string) => string;
12
+ hmac: (algorithm: string, key: string, message: string) => string;
13
+ base64Encode: (s: string) => string;
14
+ base64Decode: (s: string) => string;
15
+ json: (value: unknown) => string;
16
+ }
17
+
18
+ export type CelFunctionCategory =
19
+ | "conversion"
20
+ | "time"
21
+ | "uuid"
22
+ | "string"
23
+ | "math"
24
+ | "collection"
25
+ | "json"
26
+ | "encoding"
27
+ | "hashing"
28
+ | "null";
29
+
30
+ /** One entry in the CEL standard library — the single source of truth that both
31
+ * registers the function (`build`) and documents it (everything else). `telo
32
+ * cel functions` and `celFunctionCatalog()` read the metadata; `buildCelEnvironment`
33
+ * calls `build`. */
34
+ export interface CelFunctionDoc {
35
+ /** Bare function name (`nowIso`, `uuidv4`). */
36
+ readonly name: string;
37
+ /** Human-facing signature for docs (`nowIso(tz?): string`). May use `?` for
38
+ * optional args even though cel-js itself has no optional syntax. */
39
+ readonly signature: string;
40
+ /** Actual cel-js signatures to register — one per arity for an overloaded
41
+ * function. Defaults to `[signature]` when omitted (the common single-arity
42
+ * case, where `signature` is itself a valid cel-js signature). */
43
+ readonly register?: readonly string[];
44
+ readonly category: CelFunctionCategory;
45
+ readonly summary: string;
46
+ /** False → re-evaluates per call; in an `x-telo-eval: compile` field it bakes
47
+ * once at load. */
48
+ readonly deterministic: boolean;
49
+ /** Needs a `CelHandlers` implementation (Node `crypto` / `Buffer`); the
50
+ * analyzer's stub throws if such a function is actually evaluated. */
51
+ readonly hostBacked: boolean;
52
+ readonly build: (h: CelHandlers) => (...args: any[]) => unknown;
53
+ }
54
+
55
+ /** Public, build-free view of a catalog entry (for `--json` / docs). */
56
+ export type CelFunctionInfo = Omit<CelFunctionDoc, "build">;
57
+
58
+ const num = (x: unknown): number => Number(x);
59
+
60
+ const minMax = (list: unknown[], isMin: boolean): unknown => {
61
+ if (!Array.isArray(list) || list.length === 0) return null;
62
+ let best = list[0];
63
+ let bestN = num(best);
64
+ for (const x of list) {
65
+ const n = num(x);
66
+ if (isMin ? n < bestN : n > bestN) {
67
+ best = x;
68
+ bestN = n;
69
+ }
70
+ }
71
+ return best;
72
+ };
73
+
74
+ const sortList = (list: unknown[]): unknown[] =>
75
+ [...list].sort((a, b) => {
76
+ if (typeof a === "number" || typeof a === "bigint") {
77
+ const d = num(a) - num(b);
78
+ return d < 0 ? -1 : d > 0 ? 1 : 0;
79
+ }
80
+ return String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
81
+ });
82
+
83
+ /** `Intl.DateTimeFormat` is an ECMA-402 global in Node (full ICU) and browsers,
84
+ * so timezone handling needs no Node-only API and stays browser-safe. */
85
+ const zoneParts = (date: Date, tz: string, opts: Intl.DateTimeFormatOptions): Record<string, string> => {
86
+ const parts: Record<string, string> = {};
87
+ for (const p of new Intl.DateTimeFormat("en-US", { timeZone: tz, ...opts }).formatToParts(date)) {
88
+ parts[p.type] = p.value;
89
+ }
90
+ return parts;
91
+ };
92
+
93
+ /** Current instant as ISO-8601 in `tz`: UTC `…Z` for "UTC", else the zone's
94
+ * offset (e.g. `2026-06-06T18:30:00.000-05:00`). Uses only standard Intl
95
+ * fields and derives the offset arithmetically, so it needs no newer Intl
96
+ * type-lib features and stays portable. */
97
+ const isoInZone = (tz: string): string => {
98
+ const now = new Date();
99
+ if (tz === "UTC" || tz === "Z") return now.toISOString();
100
+ const p = zoneParts(now, tz, {
101
+ hourCycle: "h23",
102
+ year: "numeric",
103
+ month: "2-digit",
104
+ day: "2-digit",
105
+ hour: "2-digit",
106
+ minute: "2-digit",
107
+ second: "2-digit",
108
+ });
109
+ // Sub-second is timezone-independent; read it off the instant directly.
110
+ const ms = String(now.getUTCMilliseconds()).padStart(3, "0");
111
+ // Offset = the zone's wall-clock read as UTC, minus the real instant.
112
+ const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
113
+ const offsetMin = Math.round((asUtc - now.getTime()) / 60000);
114
+ const offset =
115
+ offsetMin === 0
116
+ ? "Z"
117
+ : `${offsetMin > 0 ? "+" : "-"}${String(Math.floor(Math.abs(offsetMin) / 60)).padStart(2, "0")}:${String(Math.abs(offsetMin) % 60).padStart(2, "0")}`;
118
+ return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}.${ms}${offset}`;
119
+ };
120
+
121
+ /** Current calendar date (`YYYY-MM-DD`) in `tz`. */
122
+ const dateInZone = (tz: string): string => {
123
+ const now = new Date();
124
+ if (tz === "UTC" || tz === "Z") return now.toISOString().slice(0, 10);
125
+ const p = zoneParts(now, tz, { year: "numeric", month: "2-digit", day: "2-digit" });
126
+ return `${p.year}-${p.month}-${p.day}`;
127
+ };
128
+
129
+ export const CEL_FUNCTIONS: readonly CelFunctionDoc[] = [
130
+ // Collections
131
+ {
132
+ name: "join",
133
+ signature: "join(list, string): string",
134
+ category: "collection",
135
+ summary: "Join list elements into a string with a separator.",
136
+ deterministic: true,
137
+ hostBacked: false,
138
+ build: () => (list: unknown[], sep: string) => list.map(String).join(sep),
139
+ },
140
+ {
141
+ name: "keys",
142
+ signature: "keys(map): list",
143
+ category: "collection",
144
+ summary: "List a map's keys.",
145
+ deterministic: true,
146
+ hostBacked: false,
147
+ build: () => (map: unknown) =>
148
+ map instanceof Map ? [...map.keys()] : Object.keys(map as Record<string, unknown>),
149
+ },
150
+ {
151
+ name: "values",
152
+ signature: "values(map): list",
153
+ category: "collection",
154
+ summary: "List a map's values.",
155
+ deterministic: true,
156
+ hostBacked: false,
157
+ build: () => (map: unknown) =>
158
+ map instanceof Map ? [...map.values()] : Object.values(map as Record<string, unknown>),
159
+ },
160
+ {
161
+ name: "distinct",
162
+ signature: "distinct(list): list",
163
+ category: "collection",
164
+ summary: "Remove duplicate elements, preserving order.",
165
+ deterministic: true,
166
+ hostBacked: false,
167
+ build: () => (list: unknown[]) => [...new Set(list)],
168
+ },
169
+ {
170
+ name: "reverse",
171
+ signature: "reverse(list): list",
172
+ category: "collection",
173
+ summary: "Reverse a list (copy; never mutates the input).",
174
+ deterministic: true,
175
+ hostBacked: false,
176
+ build: () => (list: unknown[]) => [...list].reverse(),
177
+ },
178
+ {
179
+ name: "flatten",
180
+ signature: "flatten(list): list",
181
+ category: "collection",
182
+ summary: "Flatten one level of nested lists.",
183
+ deterministic: true,
184
+ hostBacked: false,
185
+ build: () => (list: unknown[]) => list.flat(),
186
+ },
187
+ {
188
+ name: "sort",
189
+ signature: "sort(list): list",
190
+ category: "collection",
191
+ summary: "Sort a list numerically (numbers) or lexicographically; copy.",
192
+ deterministic: true,
193
+ hostBacked: false,
194
+ build: () => (list: unknown[]) => sortList(list),
195
+ },
196
+ // Strings
197
+ {
198
+ name: "lower",
199
+ signature: "lower(string): string",
200
+ category: "string",
201
+ summary: "Lowercase a string.",
202
+ deterministic: true,
203
+ hostBacked: false,
204
+ build: () => (s: string) => s.toLowerCase(),
205
+ },
206
+ {
207
+ name: "upper",
208
+ signature: "upper(string): string",
209
+ category: "string",
210
+ summary: "Uppercase a string.",
211
+ deterministic: true,
212
+ hostBacked: false,
213
+ build: () => (s: string) => s.toUpperCase(),
214
+ },
215
+ {
216
+ name: "trim",
217
+ signature: "trim(string): string",
218
+ category: "string",
219
+ summary: "Strip leading/trailing whitespace.",
220
+ deterministic: true,
221
+ hostBacked: false,
222
+ build: () => (s: string) => s.trim(),
223
+ },
224
+ {
225
+ name: "replace",
226
+ signature: "replace(string, string, string): string",
227
+ category: "string",
228
+ summary: "Replace all occurrences of a substring.",
229
+ deterministic: true,
230
+ hostBacked: false,
231
+ build: () => (s: string, a: string, b: string) => s.split(a).join(b),
232
+ },
233
+ {
234
+ name: "split",
235
+ signature: "split(string, string): list",
236
+ category: "string",
237
+ summary: "Split a string on a separator into a list.",
238
+ deterministic: true,
239
+ hostBacked: false,
240
+ build: () => (s: string, sep: string) => s.split(sep),
241
+ },
242
+ // Math
243
+ {
244
+ name: "abs",
245
+ signature: "abs(dyn): double",
246
+ category: "math",
247
+ summary: "Absolute value.",
248
+ deterministic: true,
249
+ hostBacked: false,
250
+ build: () => (x: unknown) => Math.abs(num(x)),
251
+ },
252
+ {
253
+ name: "floor",
254
+ signature: "floor(dyn): double",
255
+ category: "math",
256
+ summary: "Round down to an integer.",
257
+ deterministic: true,
258
+ hostBacked: false,
259
+ build: () => (x: unknown) => Math.floor(num(x)),
260
+ },
261
+ {
262
+ name: "ceil",
263
+ signature: "ceil(dyn): double",
264
+ category: "math",
265
+ summary: "Round up to an integer.",
266
+ deterministic: true,
267
+ hostBacked: false,
268
+ build: () => (x: unknown) => Math.ceil(num(x)),
269
+ },
270
+ {
271
+ name: "round",
272
+ signature: "round(dyn): double",
273
+ category: "math",
274
+ summary: "Round to the nearest integer.",
275
+ deterministic: true,
276
+ hostBacked: false,
277
+ build: () => (x: unknown) => Math.round(num(x)),
278
+ },
279
+ {
280
+ name: "min",
281
+ signature: "min(list): dyn",
282
+ category: "math",
283
+ summary: "Smallest element (by numeric value); null for an empty list.",
284
+ deterministic: true,
285
+ hostBacked: false,
286
+ build: () => (list: unknown[]) => minMax(list, true),
287
+ },
288
+ {
289
+ name: "max",
290
+ signature: "max(list): dyn",
291
+ category: "math",
292
+ summary: "Largest element (by numeric value); null for an empty list.",
293
+ deterministic: true,
294
+ hostBacked: false,
295
+ build: () => (list: unknown[]) => minMax(list, false),
296
+ },
297
+ // JSON
298
+ {
299
+ name: "json",
300
+ signature: "json(dyn): string",
301
+ category: "json",
302
+ summary: "Serialize any value to a JSON string.",
303
+ deterministic: true,
304
+ hostBacked: true,
305
+ build: (h) => (value: unknown) => h.json(value),
306
+ },
307
+ {
308
+ name: "parseJson",
309
+ signature: "parseJson(string): dyn",
310
+ category: "json",
311
+ summary: "Parse a JSON string into a value (numbers come back as doubles).",
312
+ deterministic: true,
313
+ hostBacked: false,
314
+ build: () => (s: string) => JSON.parse(s),
315
+ },
316
+ // Encoding
317
+ {
318
+ name: "base64Encode",
319
+ signature: "base64Encode(string): string",
320
+ category: "encoding",
321
+ summary: "Encode a UTF-8 string as base64.",
322
+ deterministic: true,
323
+ hostBacked: true,
324
+ build: (h) => (s: string) => h.base64Encode(s),
325
+ },
326
+ {
327
+ name: "base64Decode",
328
+ signature: "base64Decode(string): string",
329
+ category: "encoding",
330
+ summary: "Decode a base64 string to UTF-8.",
331
+ deterministic: true,
332
+ hostBacked: true,
333
+ build: (h) => (s: string) => h.base64Decode(s),
334
+ },
335
+ {
336
+ name: "urlEncode",
337
+ signature: "urlEncode(string): string",
338
+ category: "encoding",
339
+ summary: "Percent-encode a URI component.",
340
+ deterministic: true,
341
+ hostBacked: false,
342
+ build: () => (s: string) => encodeURIComponent(s),
343
+ },
344
+ {
345
+ name: "urlDecode",
346
+ signature: "urlDecode(string): string",
347
+ category: "encoding",
348
+ summary: "Decode a percent-encoded URI component.",
349
+ deterministic: true,
350
+ hostBacked: false,
351
+ build: () => (s: string) => decodeURIComponent(s),
352
+ },
353
+ // Hashing
354
+ {
355
+ name: "sha256",
356
+ signature: "sha256(string): string",
357
+ category: "hashing",
358
+ summary: "SHA-256 hash, hex-encoded.",
359
+ deterministic: true,
360
+ hostBacked: true,
361
+ build: (h) => (s: string) => h.sha256(s),
362
+ },
363
+ {
364
+ name: "md5",
365
+ signature: "md5(string): string",
366
+ category: "hashing",
367
+ summary: "MD5 hash, hex-encoded.",
368
+ deterministic: true,
369
+ hostBacked: true,
370
+ build: (h) => (s: string) => h.md5(s),
371
+ },
372
+ {
373
+ name: "sha1",
374
+ signature: "sha1(string): string",
375
+ category: "hashing",
376
+ summary: "SHA-1 hash, hex-encoded.",
377
+ deterministic: true,
378
+ hostBacked: true,
379
+ build: (h) => (s: string) => h.sha1(s),
380
+ },
381
+ {
382
+ name: "sha512",
383
+ signature: "sha512(string): string",
384
+ category: "hashing",
385
+ summary: "SHA-512 hash, hex-encoded.",
386
+ deterministic: true,
387
+ hostBacked: true,
388
+ build: (h) => (s: string) => h.sha512(s),
389
+ },
390
+ {
391
+ name: "hmac",
392
+ signature: "hmac(string, string, string): string",
393
+ category: "hashing",
394
+ summary: "HMAC of message under key for an algorithm (e.g. 'sha256'), hex.",
395
+ deterministic: true,
396
+ hostBacked: true,
397
+ build: (h) => (algo: string, key: string, msg: string) => h.hmac(algo, key, msg),
398
+ },
399
+ // Null handling
400
+ {
401
+ name: "default",
402
+ signature: "default(dyn, dyn): dyn",
403
+ category: "null",
404
+ summary: "Return the value, or the fallback when it is null.",
405
+ deterministic: true,
406
+ hostBacked: false,
407
+ build: () => (v: unknown, fallback: unknown) =>
408
+ v === null || v === undefined ? fallback : v,
409
+ },
410
+ {
411
+ name: "coalesce",
412
+ signature: "coalesce(list): dyn",
413
+ category: "null",
414
+ summary: "First non-null element of a list, or null.",
415
+ deterministic: true,
416
+ hostBacked: false,
417
+ build: () => (list: unknown[]) => {
418
+ const found = list.find((x) => x !== null && x !== undefined);
419
+ return found === undefined ? null : found;
420
+ },
421
+ },
422
+ // Time (non-deterministic). `nowIso`/`today` take an optional IANA timezone
423
+ // (default "UTC"); epoch values are absolute and take none.
424
+ {
425
+ name: "nowIso",
426
+ signature: "nowIso(tz?): string",
427
+ register: ["nowIso(): string", "nowIso(string): string"],
428
+ category: "time",
429
+ summary: "Current time as ISO-8601; UTC by default, or in the given IANA timezone.",
430
+ deterministic: false,
431
+ hostBacked: false,
432
+ build: () => (tz?: string) => isoInZone(tz ?? "UTC"),
433
+ },
434
+ {
435
+ name: "today",
436
+ signature: "today(tz?): string",
437
+ register: ["today(): string", "today(string): string"],
438
+ category: "time",
439
+ summary: "Current calendar date (YYYY-MM-DD); UTC by default, or in the given IANA timezone.",
440
+ deterministic: false,
441
+ hostBacked: false,
442
+ build: () => (tz?: string) => dateInZone(tz ?? "UTC"),
443
+ },
444
+ {
445
+ name: "nowMillis",
446
+ signature: "nowMillis(): int",
447
+ category: "time",
448
+ summary: "Current time as epoch milliseconds (absolute; timezone-independent).",
449
+ deterministic: false,
450
+ hostBacked: false,
451
+ build: () => () => BigInt(Date.now()),
452
+ },
453
+ {
454
+ name: "nowSeconds",
455
+ signature: "nowSeconds(): int",
456
+ category: "time",
457
+ summary: "Current time as epoch seconds (absolute; timezone-independent).",
458
+ deterministic: false,
459
+ hostBacked: false,
460
+ build: () => () => BigInt(Math.floor(Date.now() / 1000)),
461
+ },
462
+ // UUID
463
+ {
464
+ name: "uuidv1",
465
+ signature: "uuidv1(): string",
466
+ category: "uuid",
467
+ summary: "Time-based UUID (v1).",
468
+ deterministic: false,
469
+ hostBacked: false,
470
+ build: () => () => v1(),
471
+ },
472
+ {
473
+ name: "uuidv4",
474
+ signature: "uuidv4(): string",
475
+ category: "uuid",
476
+ summary: "Random UUID (v4).",
477
+ deterministic: false,
478
+ hostBacked: false,
479
+ build: () => () => v4(),
480
+ },
481
+ {
482
+ name: "uuidv6",
483
+ signature: "uuidv6(): string",
484
+ category: "uuid",
485
+ summary: "Time-ordered UUID (v6).",
486
+ deterministic: false,
487
+ hostBacked: false,
488
+ build: () => () => v6(),
489
+ },
490
+ {
491
+ name: "uuidv7",
492
+ signature: "uuidv7(): string",
493
+ category: "uuid",
494
+ summary: "Time-ordered UUID (v7).",
495
+ deterministic: false,
496
+ hostBacked: false,
497
+ build: () => () => v7(),
498
+ },
499
+ {
500
+ name: "uuidv3",
501
+ signature: "uuidv3(string, string): string",
502
+ category: "uuid",
503
+ summary: "Name-based UUID (v3, MD5) under a namespace UUID.",
504
+ deterministic: true,
505
+ hostBacked: false,
506
+ build: () => (name: string, ns: string) => v3(name, ns),
507
+ },
508
+ {
509
+ name: "uuidv5",
510
+ signature: "uuidv5(string, string): string",
511
+ category: "uuid",
512
+ summary: "Name-based UUID (v5, SHA-1) under a namespace UUID.",
513
+ deterministic: true,
514
+ hostBacked: false,
515
+ build: () => (name: string, ns: string) => v5(name, ns),
516
+ },
517
+ {
518
+ name: "uuidValidate",
519
+ signature: "uuidValidate(string): bool",
520
+ category: "uuid",
521
+ summary: "True if the string is a valid UUID.",
522
+ deterministic: true,
523
+ hostBacked: false,
524
+ build: () => (s: string) => uuidValidate(s),
525
+ },
526
+ {
527
+ name: "uuidVersion",
528
+ signature: "uuidVersion(string): int",
529
+ category: "uuid",
530
+ summary: "The version number of a UUID.",
531
+ deterministic: true,
532
+ hostBacked: false,
533
+ build: () => (s: string) => BigInt(uuidVersion(s)),
534
+ },
535
+ ];
536
+
537
+ /** Build-free catalog for the CLI / docs (`telo cel functions`). */
538
+ export function celFunctionCatalog(): CelFunctionInfo[] {
539
+ return CEL_FUNCTIONS.map(({ build: _build, ...info }) => info);
540
+ }
@@ -1,4 +1,4 @@
1
- import type { CompiledValue } from "@telorun/sdk";
1
+ import { isCompiledValue, type CompiledValue } from "@telorun/sdk";
2
2
  import type { Environment } from "@marcbachmann/cel-js";
3
3
 
4
4
  export const TEMPLATE_REGEX = /\$\{\{\s*([^}]+?)\s*\}\}/g;
@@ -41,7 +41,45 @@ export function compileString(s: string, env: Environment): unknown {
41
41
  return {
42
42
  __compiled: true,
43
43
  source: s,
44
+ parts,
44
45
  call: (ctx: Record<string, unknown>) =>
45
46
  parts.map((p) => (typeof p === "string" ? p : String(p.call(ctx) ?? ""))).join(""),
46
47
  } satisfies CompiledValue;
47
48
  }
49
+
50
+ /** Split an interpolated value into literal fragments and the evaluated values
51
+ * of its embedded expressions, instead of joining them into one string. Lets a
52
+ * consumer emit its own placeholders between fragments and bind the values
53
+ * separately (e.g. parameterized SQL). The invariant
54
+ * `fragments.length === values.length + 1` always holds.
55
+ *
56
+ * - plain string (no `${{ }}`) → `{ fragments: [s], values: [] }`
57
+ * - bare single expression `${{ x }}` → `{ fragments: ["", ""], values: [x] }`
58
+ * - interpolated `"a ${{ x }} b"` → `{ fragments: ["a ", " b"], values: [x] }`
59
+ */
60
+ export function toParameterized(
61
+ value: unknown,
62
+ ctx: Record<string, unknown>,
63
+ ): { fragments: string[]; values: unknown[] } {
64
+ if (typeof value === "string") return { fragments: [value], values: [] };
65
+ if (!isCompiledValue(value)) {
66
+ throw new Error("toParameterized expects a string or CompiledValue");
67
+ }
68
+ if (!value.parts) {
69
+ return { fragments: ["", ""], values: [value.call(ctx)] };
70
+ }
71
+ const fragments: string[] = [];
72
+ const values: unknown[] = [];
73
+ let current = "";
74
+ for (const p of value.parts) {
75
+ if (typeof p === "string") {
76
+ current += p;
77
+ } else {
78
+ fragments.push(current);
79
+ current = "";
80
+ values.push(p.call(ctx));
81
+ }
82
+ }
83
+ fragments.push(current);
84
+ return { fragments, values };
85
+ }
@@ -1,10 +1,8 @@
1
1
  import { Environment } from "@marcbachmann/cel-js";
2
2
  import { Stream } from "@telorun/sdk";
3
+ import { CEL_FUNCTIONS, type CelHandlers } from "./catalog.js";
3
4
 
4
- export interface CelHandlers {
5
- sha256: (s: string) => string;
6
- json: (value: unknown) => string;
7
- }
5
+ export type { CelHandlers } from "./catalog.js";
8
6
 
9
7
  const stub = (name: string) => () => {
10
8
  throw new Error(
@@ -15,13 +13,22 @@ const stub = (name: string) => () => {
15
13
 
16
14
  const STUB_HANDLERS: CelHandlers = {
17
15
  sha256: stub("sha256"),
16
+ md5: stub("md5"),
17
+ sha1: stub("sha1"),
18
+ sha512: stub("sha512"),
19
+ hmac: stub("hmac"),
20
+ base64Encode: stub("base64Encode"),
21
+ base64Decode: stub("base64Decode"),
18
22
  json: stub("json"),
19
23
  };
20
24
 
21
- /** Build a CEL `Environment` with Telo's stdlib of functions. Always registers the
22
- * same function signatures (so `env.check()` succeeds for type-inference) the
23
- * handlers govern what the function does when called at runtime. Analyzer-only
24
- * callers can omit handlers; runtime callers (kernel) must supply real ones.
25
+ /** Build a CEL `Environment` with Telo's stdlib. Every function comes from the
26
+ * single-source catalog (`CEL_FUNCTIONS`), so registration and the documented
27
+ * surface (`telo cel functions`) can never drift. Always registers the same
28
+ * signatures (so `env.check()` succeeds for type-inference); the host-injected
29
+ * handlers govern what `hostBacked` functions do at runtime. Analyzer-only
30
+ * callers can omit handlers (the stubs throw if such a function is evaluated);
31
+ * runtime callers (kernel) supply real ones.
25
32
  *
26
33
  * Also registers the `Stream` object type, backed by the `Stream` class from
27
34
  * `@telorun/sdk`. CEL's type-checker rejects values whose constructor isn't
@@ -31,20 +38,16 @@ const STUB_HANDLERS: CelHandlers = {
31
38
  * no fields, so terminal access (passing the value through CEL) succeeds but
32
39
  * member access raises a CEL error at runtime — matching the analyzer's
33
40
  * static check on `x-telo-stream`-marked properties. */
34
- export function buildCelEnvironment(handlers: CelHandlers = STUB_HANDLERS): Environment {
35
- return new Environment({ unlistedVariablesAreDyn: true, enableOptionalTypes: true })
36
- .registerFunction("join(list, string): string", (list: unknown[], sep: string) =>
37
- list.map(String).join(sep),
38
- )
39
- .registerFunction("keys(map): list", (map: unknown) => {
40
- if (map instanceof Map) return [...map.keys()];
41
- return Object.keys(map as Record<string, unknown>);
42
- })
43
- .registerFunction("values(map): list", (map: unknown) => {
44
- if (map instanceof Map) return [...map.values()];
45
- return Object.values(map as Record<string, unknown>);
46
- })
47
- .registerFunction("sha256(string): string", (s: string) => handlers.sha256(s))
48
- .registerFunction("json(dyn): string", (value: unknown) => handlers.json(value))
49
- .registerType("Stream", Stream as unknown as new (...args: unknown[]) => unknown);
41
+ export function buildCelEnvironment(handlers: Partial<CelHandlers> = {}): Environment {
42
+ const h: CelHandlers = { ...STUB_HANDLERS, ...handlers };
43
+ let env = new Environment({ unlistedVariablesAreDyn: true, enableOptionalTypes: true });
44
+ for (const fn of CEL_FUNCTIONS) {
45
+ const impl = fn.build(h);
46
+ // `register` lists one cel-js signature per arity (overloaded functions);
47
+ // it falls back to `signature` for the single-arity common case.
48
+ for (const sig of fn.register ?? [fn.signature]) {
49
+ env = env.registerFunction(sig, impl);
50
+ }
51
+ }
52
+ return env.registerType("Stream", Stream as unknown as new (...args: unknown[]) => unknown);
50
53
  }