@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,1455 +0,0 @@
1
- import { formatLocale } from "d3-format";
2
- import { RE2JS, RE2JSSyntaxException } from "re2js";
3
- import { v1, v3, v4, v5, v6, v7, validate as uuidValidate, version as uuidVersion } from "uuid";
4
- import { PLAIN_ENCODINGS } from "@telorun/sdk";
5
- import { scanJsonPrefix } from "./json-prefix-scan.js";
6
-
7
- /** Host-injected functions that need platform APIs the templating package must
8
- * not import directly (Node `crypto` / `Buffer`), keeping it browser-safe. The
9
- * kernel supplies real implementations; the analyzer omits them (the stubs
10
- * throw, since static analysis never executes these). */
11
- export interface CelHandlers {
12
- sha256: (s: string) => string;
13
- md5: (s: string) => string;
14
- sha1: (s: string) => string;
15
- sha512: (s: string) => string;
16
- hmac: (algorithm: string, key: string, message: string) => string;
17
- base64Encode: (s: string) => string;
18
- base64Decode: (s: string) => string;
19
- json: (value: unknown) => string;
20
- /** Join a relative path onto a base with the HOST's path rules. */
21
- joinPath: (base: string, relative: string) => string;
22
- }
23
-
24
- /** RE2 regex engine for the CEL `regex*` functions — `re2js`, a pure-JS port of
25
- * Google's RE2. The dialect is RE2 (linear-time, no backtracking, ReDoS-safe) —
26
- * never JS `RegExp` — so a manifest's regex behaves the same across runtimes.
27
- * Flags map a trailing option string to RE2 flags; inline `(?s)` etc. work in
28
- * the pattern too.
29
- *
30
- * Why pure-JS and not a native RE2:
31
- * - The Rust `regex` crate via napi (N-API) is faster, but shipping it means a
32
- * cross-platform prebuild matrix + per-triple npm packages — a whole release
33
- * subsystem for one function family.
34
- * - The `re2` npm package (Google's C++ RE2) is simpler to depend on, but it's a
35
- * nan/V8 addon and **does not load under Bun** (incomplete V8 C++ ABI →
36
- * `undefined symbol`). Telo's CLI and test suite run on Bun, so that's a
37
- * non-starter.
38
- * `re2js` is pure JS: zero native addons, runs identically on Node, Bun, and the
39
- * browser (keeps this package — and the analyzer — browser-safe), and needs no
40
- * prebuilds. The cost is throughput vs. native, which is irrelevant for the
41
- * small strings CEL manifests run regex over. */
42
- const RE2_FLAG: Record<string, number> = {
43
- i: RE2JS.CASE_INSENSITIVE,
44
- m: RE2JS.MULTILINE,
45
- s: RE2JS.DOTALL,
46
- };
47
-
48
- /** RE2's parse-error kinds, in RE2's own words — the closed vocabulary an
49
- * invalid-pattern refusal ends with, so every engine words one identically. */
50
- export const RE2_PATTERN_ERROR_KINDS: readonly string[] = [
51
- "missing closing )",
52
- "missing closing ]",
53
- "unexpected )",
54
- "trailing backslash at end of expression",
55
- "invalid escape sequence",
56
- "invalid character class range",
57
- "invalid named capture",
58
- "duplicate capture group name",
59
- "invalid or unsupported Perl syntax",
60
- "missing argument to repetition operator",
61
- "invalid nested repetition operator",
62
- "invalid repeat count",
63
- "expression nests too deeply",
64
- "expression too large",
65
- ];
66
-
67
- /** A refusal a catalog function makes of its arguments — the one failure a
68
- * literal guard reports. It reads as a plain `Error` wherever it is printed. */
69
- class CatalogRefusal extends Error {}
70
- Object.defineProperty(CatalogRefusal, "name", { value: "Error" });
71
-
72
- const re2Flags = (fn: string, flags: string | undefined): number => {
73
- let bits = 0;
74
- for (const c of flags ?? "") {
75
- if (c === "g") continue; // global is implicit in replaceAll / find-loop
76
- const bit = RE2_FLAG[c];
77
- if (bit === undefined) throw new CatalogRefusal(`${fn}: unknown regex flag '${c}' (supported: i, m, s)`);
78
- bits |= bit;
79
- }
80
- return bits;
81
- };
82
-
83
- /** The refusal is Telo's: the library's `error parsing regexp:` prefix and the
84
- * fragment it quotes never reach it. A failure outside the vocabulary is a
85
- * defect here, raised as one with the library's error as its cause. */
86
- const re2Pattern = (fn: string, pattern: string, bits: number): RE2JS => {
87
- try {
88
- return RE2JS.compile(pattern, bits);
89
- } catch (e) {
90
- const kind = e instanceof RE2JSSyntaxException ? e.error : undefined;
91
- if (kind === undefined || !RE2_PATTERN_ERROR_KINDS.includes(kind)) {
92
- throw new Error(
93
- `${fn}: the RE2 compiler failed on pattern ${JSON.stringify(pattern)} with an error outside Telo's parse-error vocabulary`,
94
- { cause: e },
95
- );
96
- }
97
- throw new CatalogRefusal(`${fn}: invalid RE2 pattern ${JSON.stringify(pattern)}: ${kind}`);
98
- }
99
- };
100
-
101
- const compileRe2 = (fn: string, pattern: string, flags?: string): RE2JS =>
102
- re2Pattern(fn, pattern, re2Flags(fn, flags));
103
-
104
- export type CelFunctionCategory =
105
- | "conversion"
106
- | "time"
107
- | "uuid"
108
- | "string"
109
- | "math"
110
- | "collection"
111
- | "json"
112
- | "encoding"
113
- | "hashing"
114
- | "formatting"
115
- | "null";
116
-
117
- /** One entry in the CEL standard library — the single source of truth that both
118
- * registers the function (`build`) and documents it (everything else). `telo
119
- * cel functions` and `celFunctionCatalog()` read the metadata; `buildCelEnvironment`
120
- * calls `build`. */
121
- export interface CelFunctionDoc {
122
- /** Bare function name (`nowIso`, `uuidv4`). */
123
- readonly name: string;
124
- /** Human-facing signature for docs (`nowIso(tz?): string`). May use `?` for
125
- * optional args even though cel-js itself has no optional syntax. */
126
- readonly signature: string;
127
- /** Actual cel-js signatures to register — one per arity for an overloaded
128
- * function. When omitted, `deriveSignatures(signature)` is used: if the
129
- * signature contains `type?`-marked optional params (e.g. `fn(string?): T`),
130
- * it auto-expands to one registration per arity. Set `register` explicitly
131
- * only when the auto-derivation is insufficient. */
132
- readonly register?: readonly string[];
133
- readonly category: CelFunctionCategory;
134
- readonly summary: string;
135
- /** False → re-evaluates per call; in an `x-telo-eval: compile` field it bakes
136
- * once at load. */
137
- readonly deterministic: boolean;
138
- /** Needs a `CelHandlers` implementation (Node `crypto` / `Buffer`); the
139
- * analyzer's stub throws if such a function is actually evaluated. */
140
- readonly hostBacked: boolean;
141
- readonly build: (h: CelHandlers) => (...args: any[]) => unknown;
142
- /**
143
- * Check the arguments that were written as LITERALS, at analysis time.
144
- *
145
- * A type is all a signature can constrain, so a guard over a value —
146
- * an unparseable format specifier, a decimal count out of range, a day length
147
- * of zero, an unknown IANA zone — fires only when the expression is evaluated.
148
- * That puts a defect the manifest states in plain sight behind a run, which is
149
- * the opposite of what static analysis is for.
150
- *
151
- * `literals[i]` is the value of argument `i` when it was written as a literal,
152
- * and `undefined` when it is an expression whose value is not statically
153
- * known — so a checker MUST skip an `undefined` rather than judge it.
154
- * Returns a message, or `undefined` when there is nothing to report.
155
- *
156
- * Implementations call the SAME guard the runtime calls, so the static and
157
- * dynamic answers cannot drift into disagreement.
158
- */
159
- readonly checkArgs?: (literals: readonly unknown[]) => string | undefined;
160
- }
161
-
162
- /** Run a runtime guard for its refusal, so a `checkArgs` never restates one.
163
- * Anything else it throws is the engine failing, not the argument. */
164
- const literalGuard = (run: () => void): string | undefined => {
165
- try {
166
- run();
167
- return undefined;
168
- } catch (e) {
169
- if (e instanceof CatalogRefusal) return e.message;
170
- throw e;
171
- }
172
- };
173
-
174
- /** A regex function's literal guard: the flags and the pattern, each judged
175
- * only when written as a literal, by the compile the runtime runs. */
176
- const regexLiteralGuard =
177
- (fn: string, patternAt: number, flagsAt: number): NonNullable<CelFunctionDoc["checkArgs"]> =>
178
- (literals) =>
179
- literalGuard(() => {
180
- const pattern = literals[patternAt];
181
- const flags = literals[flagsAt];
182
- const bits = typeof flags === "string" ? re2Flags(fn, flags) : 0;
183
- if (typeof pattern === "string") re2Pattern(fn, pattern, bits);
184
- });
185
-
186
- /** The host parser's verdict stands; Telo's scan only words its refusal. The
187
- * scan reading as JSON a text the host refused is a defect here. */
188
- const parseJsonText = (text: string): unknown => {
189
- try {
190
- return JSON.parse(text);
191
- } catch (hostRefusal) {
192
- const refusal = scanJsonPrefix(text);
193
- if (refusal === undefined) {
194
- throw new Error("parseJson: the host JSON parser refused a text Telo's scan reads as valid JSON", {
195
- cause: hostRefusal,
196
- });
197
- }
198
- throw new Error(
199
- `parseJson: invalid JSON at offset ${refusal.offset}${refusal.endOfInput ? " (unexpected end of input)" : ""}`,
200
- );
201
- }
202
- };
203
-
204
- /** Public, build-free view of a catalog entry (for `--json` / docs). */
205
- export type CelFunctionInfo = Omit<CelFunctionDoc, "build">;
206
-
207
- const num = (x: unknown): number => Number(x);
208
-
209
- const minMax = (list: unknown[], isMin: boolean): unknown => {
210
- if (!Array.isArray(list) || list.length === 0) return null;
211
- let best = list[0];
212
- let bestN = num(best);
213
- for (const x of list) {
214
- const n = num(x);
215
- if (isMin ? n < bestN : n > bestN) {
216
- best = x;
217
- bestN = n;
218
- }
219
- }
220
- return best;
221
- };
222
-
223
- const sortList = (list: unknown[]): unknown[] =>
224
- [...list].sort((a, b) => {
225
- if (typeof a === "number" || typeof a === "bigint") {
226
- const d = num(a) - num(b);
227
- return d < 0 ? -1 : d > 0 ? 1 : 0;
228
- }
229
- return String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
230
- });
231
-
232
- /** The number-formatting locale, pinned rather than defaulted.
233
- *
234
- * d3-format's default locale renders a negative with U+2212 MINUS SIGN, so
235
- * `format(-1.5, '.2f')` is `"−1.50"` and not `"-1.50"` — a string that no
236
- * downstream parser, comparison or diff treats as the number it looks like.
237
- * Every field here is fixed to its ASCII form for the same reason the layer is
238
- * locale-free at all: the same manifest must render the same bytes on every
239
- * runtime, and a second engine implementing the specifier grammar has to be
240
- * able to reproduce these exactly. */
241
- const FORMAT_LOCALE = formatLocale({
242
- decimal: ".",
243
- thousands: ",",
244
- grouping: [3],
245
- currency: ["$", ""],
246
- minus: "-",
247
- percent: "%",
248
- nan: "NaN",
249
- });
250
-
251
- /** Largest integer a double represents exactly. */
252
- const MAX_EXACT_INT = 9007199254740991n;
253
-
254
- /** A CEL `int` is a BigInt in this runtime and `d3-format` throws on one
255
- * outright, so a formattable argument is converted here. Past 2^53 a double
256
- * stops representing every integer, and silently emitting a number that is not
257
- * the one the author computed is the defect class this family exists to close —
258
- * so that case raises instead. */
259
- const formattable = (fn: string, x: unknown): number => {
260
- if (typeof x === "bigint") {
261
- if (x > MAX_EXACT_INT || x < -MAX_EXACT_INT) {
262
- throw new CatalogRefusal(
263
- `${fn}: integer ${x} exceeds 2^53-1 and cannot be formatted exactly as a double`,
264
- );
265
- }
266
- return Number(x);
267
- }
268
- const n = Number(x);
269
- // The runtime backstop behind the typed registrations. A value that is not a
270
- // number formats as the string "NaN", which is the failure this family exists
271
- // to remove: it looks like an answer and prints into a document. Named here
272
- // rather than coerced, the way an instant argument is.
273
- if (!Number.isFinite(n)) {
274
- throw new CatalogRefusal(`${fn}: expected a finite number, got ${JSON.stringify(x)}`);
275
- }
276
- return n;
277
- };
278
-
279
- /** Specifier type characters d3 implements. An unknown one PARSES — `.2q`
280
- * yields `"1"` rather than throwing — so a typo would silently format against
281
- * the default type. The set is checked here so a bad specifier is refused
282
- * rather than quietly answered. */
283
- const FORMAT_TYPES = new Set([..."efgrs%pbodxXcn"]);
284
-
285
- /** A specifier is a CEL value, so it can be request-derived — an `Http.Server`
286
- * evaluating `format(x, request.query.spec)` would otherwise grow this map for
287
- * the life of the process, and it is module-global, so every in-process kernel
288
- * shares it. Cleared wholesale at the cap rather than evicted one at a time: a
289
- * manifest's real specifier set is a handful of constants that repopulate
290
- * immediately, and an LRU is machinery for a hit rate nothing here needs. */
291
- const FORMATTER_CACHE_MAX = 256;
292
- const formatterCache = new Map<string, (n: number) => string>();
293
-
294
- const formatter = (fn: string, spec: unknown): ((n: number) => string) => {
295
- const text = String(spec);
296
- const cached = formatterCache.get(text);
297
- if (cached) return cached;
298
- const type = text.slice(-1);
299
- if (text !== "" && /[a-zA-Z%]/.test(type) && !FORMAT_TYPES.has(type)) {
300
- throw new CatalogRefusal(`${fn}: unknown format type '${type}' (one of ${[...FORMAT_TYPES].join("")})`);
301
- }
302
- // The `.precision` group — width is the digits BEFORE the dot, so this is the
303
- // only `.`-digits sequence the grammar admits.
304
- const precision = /\.(\d+)/.exec(text);
305
- if (precision) digitCount(fn, precision[1]);
306
- let built: (n: number) => string;
307
- try {
308
- built = FORMAT_LOCALE.format(text);
309
- } catch {
310
- throw new CatalogRefusal(`${fn}: invalid format specifier ${JSON.stringify(text)}`);
311
- }
312
- if (formatterCache.size >= FORMATTER_CACHE_MAX) formatterCache.clear();
313
- formatterCache.set(text, built);
314
- return built;
315
- };
316
-
317
- /** Decimal places, bounded. The ceiling is well below what `toFixed` accepts
318
- * because past it the digits are an artefact of the binary representation
319
- * rather than of the value.
320
- *
321
- * ONE rule, enforced wherever a precision is written: `formatter` applies it to
322
- * a specifier's `.precision` group too. Bounding only this spelling let an
323
- * author route around the guard by writing `format(x, '.11f')` instead of
324
- * `fixed(x, 11)` — the family giving two answers to one question. It is not the
325
- * grammar subsetting the "full d3 surface" decision refuses: every specifier
326
- * type and flag stays available, and only the digit count is capped. */
327
- const MAX_DECIMALS = 10;
328
-
329
- const digitCount = (fn: string, digits: unknown): number => {
330
- const n = Number(digits);
331
- if (!Number.isInteger(n) || n < 0 || n > MAX_DECIMALS) {
332
- throw new CatalogRefusal(
333
- `${fn}: decimal places must be an integer 0-${MAX_DECIMALS}, got ${String(digits)}`,
334
- );
335
- }
336
- return n;
337
- };
338
-
339
- /** Render a minute count against a declared day length. The day is a policy
340
- * argument, never an assumption — see the catalog entry's summary. */
341
- const durationText = (minutes: unknown, minutesPerDay: unknown): string => {
342
- const perDay = Math.round(formattable("formatDuration", minutesPerDay));
343
- if (!Number.isFinite(perDay) || perDay <= 0) {
344
- throw new CatalogRefusal(`formatDuration: minutesPerDay must be a positive number, got ${perDay}`);
345
- }
346
- const total = Math.round(formattable("formatDuration", minutes));
347
- if (!Number.isFinite(total)) {
348
- throw new CatalogRefusal(`formatDuration: minutes must be a finite number`);
349
- }
350
- const magnitude = Math.abs(total);
351
- const days = Math.floor(magnitude / perDay);
352
- const withinDay = magnitude % perDay;
353
- const hours = Math.floor(withinDay / 60);
354
- const mins = withinDay % 60;
355
- const parts: string[] = [];
356
- if (days) parts.push(`${days}d`);
357
- if (hours) parts.push(`${hours}h`);
358
- if (mins) parts.push(`${mins}m`);
359
- if (parts.length === 0) parts.push("0m");
360
- return `${total < 0 ? "-" : ""}${parts.join(" ")}`;
361
- };
362
-
363
- /** Refuse an unknown zone in this family's own voice. Left to `Intl`, the
364
- * failure is a raw `RangeError` naming neither the function nor what was
365
- * wrong with the argument — the only refusal here that did not read
366
- * `<fn>: <what is wrong>`, and whose wording belongs to the JS engine rather
367
- * than to Telo. Also the guard `checkArgs` runs at analysis time, so a literal
368
- * zone is checked once and answered identically in both places. */
369
- const assertZone = (fn: string, tz: string): string => {
370
- try {
371
- new Intl.DateTimeFormat("en-US", { timeZone: tz });
372
- } catch {
373
- throw new CatalogRefusal(`${fn}: unknown IANA time zone ${JSON.stringify(tz)}`);
374
- }
375
- return tz;
376
- };
377
-
378
- /** `Intl.DateTimeFormat` is an ECMA-402 global in Node (full ICU) and browsers,
379
- * so timezone handling needs no Node-only API and stays browser-safe. */
380
- const zoneParts = (date: Date, tz: string, opts: Intl.DateTimeFormatOptions): Record<string, string> => {
381
- const parts: Record<string, string> = {};
382
- for (const p of new Intl.DateTimeFormat("en-US", { timeZone: tz, ...opts }).formatToParts(date)) {
383
- parts[p.type] = p.value;
384
- }
385
- return parts;
386
- };
387
-
388
- /** Current instant as ISO-8601 in `tz`: UTC `…Z` for "UTC", else the zone's
389
- * offset (e.g. `2026-06-06T18:30:00.000-05:00`). Uses only standard Intl
390
- * fields and derives the offset arithmetically, so it needs no newer Intl
391
- * type-lib features and stays portable. */
392
- const isoInZone = (now: Date, tz: string): string => {
393
- if (tz === "UTC" || tz === "Z") return now.toISOString();
394
- const p = zoneParts(now, tz, {
395
- hourCycle: "h23",
396
- year: "numeric",
397
- month: "2-digit",
398
- day: "2-digit",
399
- hour: "2-digit",
400
- minute: "2-digit",
401
- second: "2-digit",
402
- });
403
- // Sub-second is timezone-independent; read it off the instant directly.
404
- const ms = String(now.getUTCMilliseconds()).padStart(3, "0");
405
- // Offset = the zone's wall-clock read as UTC, minus the real instant.
406
- const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
407
- const offsetMin = Math.round((asUtc - now.getTime()) / 60000);
408
- const offset =
409
- offsetMin === 0
410
- ? "Z"
411
- : `${offsetMin > 0 ? "+" : "-"}${String(Math.floor(Math.abs(offsetMin) / 60)).padStart(2, "0")}:${String(Math.abs(offsetMin) % 60).padStart(2, "0")}`;
412
- return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}.${ms}${offset}`;
413
- };
414
-
415
- /** Calendar date (`YYYY-MM-DD`) of an instant in `tz`. */
416
- const dateInZone = (now: Date, tz: string): string => {
417
- if (tz === "UTC" || tz === "Z") return now.toISOString().slice(0, 10);
418
- const p = zoneParts(now, tz, { year: "numeric", month: "2-digit", day: "2-digit" });
419
- return `${p.year}-${p.month}-${p.day}`;
420
- };
421
-
422
- /** An instant is only a date once a zone is chosen, so every calendar function
423
- * reads its fields through one of these. `Intl` rejects an unknown zone, which
424
- * is what turns a typo into an error rather than a silently-UTC answer. */
425
- interface ZonedFields {
426
- year: number;
427
- month: number;
428
- day: number;
429
- hour: number;
430
- minute: number;
431
- second: number;
432
- }
433
-
434
- const zonedFields = (date: Date, tz: string): ZonedFields => {
435
- const p = zoneParts(date, tz, {
436
- hourCycle: "h23",
437
- year: "numeric",
438
- month: "2-digit",
439
- day: "2-digit",
440
- hour: "2-digit",
441
- minute: "2-digit",
442
- second: "2-digit",
443
- });
444
- return {
445
- year: +p.year!,
446
- month: +p.month!,
447
- day: +p.day!,
448
- hour: +p.hour!,
449
- minute: +p.minute!,
450
- second: +p.second!,
451
- };
452
- };
453
-
454
- /** The zone's offset at `date`, in milliseconds — its wall clock read as UTC,
455
- * minus the real instant. The same arithmetic `isoInZone` does. */
456
- const zoneOffsetMs = (date: Date, tz: string): number => {
457
- const f = zonedFields(date, tz);
458
- return Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second) - date.getTime();
459
- };
460
-
461
- const sameWallClock = (a: ZonedFields, b: ZonedFields): boolean =>
462
- a.year === b.year &&
463
- a.month === b.month &&
464
- a.day === b.day &&
465
- a.hour === b.hour &&
466
- a.minute === b.minute &&
467
- a.second === b.second;
468
-
469
- /** The instant whose wall clock in `tz` is the given fields.
470
- *
471
- * The offset depends on the instant being solved for, so this takes the offset
472
- * at the UTC reading, corrects, and then CHECKS by reading the result back.
473
- * That check is the whole point: a plain fixpoint settles on an instant whose
474
- * wall clock is not the one asked for whenever the requested time does not
475
- * exist, and it settles BACKWARDS — which silently moves the calendar day, the
476
- * one thing `addMonths` and `startOfMonth` exist to control. Chile jumps
477
- * 00:00 → 01:00 on 2026-09-06 and Cuba on 2026-03-08, so "the 6th at midnight"
478
- * there is not a time; a fixpoint answered "the 5th at 23:00".
479
- *
480
- * Resolution follows Java's `ZonedDateTime` and Temporal's `compatible`:
481
- * a wall clock that exists twice (a fall-back) takes the EARLIER instant, and
482
- * one that does not exist (a spring-forward gap) shifts FORWARD out of the gap,
483
- * which keeps the requested day. */
484
- const instantOfZoned = (f: ZonedFields, tz: string): Date => {
485
- const asUtc = Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second);
486
- const offsetA = zoneOffsetMs(new Date(asUtc), tz);
487
- const candidateA = asUtc - offsetA;
488
- const offsetB = zoneOffsetMs(new Date(candidateA), tz);
489
- if (offsetA === offsetB) return new Date(candidateA);
490
-
491
- const candidateB = asUtc - offsetB;
492
- const aHolds = sameWallClock(zonedFields(new Date(candidateA), tz), f);
493
- const bHolds = sameWallClock(zonedFields(new Date(candidateB), tz), f);
494
- if (aHolds && bHolds) return new Date(Math.min(candidateA, candidateB));
495
- if (aHolds) return new Date(candidateA);
496
- if (bHolds) return new Date(candidateB);
497
- return new Date(Math.max(candidateA, candidateB));
498
- };
499
-
500
- /** `Date.UTC` maps years 0-99 to 1900-1999, so the year is set explicitly. */
501
- const daysInMonth = (year: number, month: number): number => {
502
- const d = new Date(Date.UTC(2000, month, 0));
503
- d.setUTCFullYear(year, month, 0);
504
- return d.getUTCDate();
505
- };
506
-
507
- /** An instant argument arrives as a `Date`; anything else is a caller error the
508
- * type-checker did not catch (a `dyn` slot), so it is named rather than
509
- * coerced into an Invalid Date that formats as `NaN`. */
510
- const instantArg = (fn: string, v: unknown): Date => {
511
- if (v instanceof Date && Number.isFinite(v.getTime())) return v;
512
- throw new Error(`${fn}: expected a timestamp`);
513
- };
514
-
515
- /** Drop entries whose value is null or the empty string. Nothing else: an empty
516
- * list or map is a value someone deliberately built. CEL hands a map over as a
517
- * plain object or a `Map` depending on how it was produced, so both are read. */
518
- const compactValue = (v: unknown): unknown => {
519
- const keep = (x: unknown): boolean => x !== null && x !== undefined && x !== "";
520
- if (Array.isArray(v)) return v.filter(keep);
521
- if (v instanceof Map) {
522
- return new Map([...v.entries()].filter(([, value]) => keep(value)));
523
- }
524
- // A PLAIN object only. Rebuilding an arbitrary object from its entries is how
525
- // a byte buffer becomes `{"0":137,…}` and an instant becomes `{}` — silently,
526
- // and looking like a value. The same rule the compile walker follows, and the
527
- // same "name it rather than coerce it" the instant argument follows.
528
- if (v !== null && typeof v === "object") {
529
- const proto = Object.getPrototypeOf(v);
530
- if (proto !== Object.prototype && proto !== null) {
531
- throw new Error(`compact: expected a map or a list, got ${v.constructor?.name ?? "an object"}`);
532
- }
533
- return Object.fromEntries(Object.entries(v as Record<string, unknown>).filter(([, value]) => keep(value)));
534
- }
535
- throw new Error(`compact: expected a map or a list, got ${JSON.stringify(v)}`);
536
- };
537
-
538
- /** A CEL map as entries. Read the way `compact` reads one — a map arrives as a
539
- * plain object or a `Map` depending on how it was produced — and refusing
540
- * anything that is not one, since rebuilding an arbitrary object from its
541
- * entries is how a byte buffer becomes `{"0":137,…}` silently. A LIST is named
542
- * rather than coerced: CEL's `+` already concatenates lists, so a list here is
543
- * a mistake with a spelling that works, not a case to support. */
544
- const mapEntries = (fn: string, v: unknown): [string, unknown][] => {
545
- if (v instanceof Map) return [...v.entries()] as [string, unknown][];
546
- if (Array.isArray(v)) throw new Error(`${fn}: expected a map, got a list — use '+' to join lists`);
547
- if (v !== null && typeof v === "object") {
548
- const proto = Object.getPrototypeOf(v);
549
- if (proto !== Object.prototype && proto !== null) {
550
- throw new Error(`${fn}: expected a map, got ${v.constructor?.name ?? "an object"}`);
551
- }
552
- return Object.entries(v as Record<string, unknown>);
553
- }
554
- throw new Error(`${fn}: expected a map, got ${JSON.stringify(v)}`);
555
- };
556
-
557
- /** Right-hand precedence, so `merge(defaults, overrides)` reads as it looks.
558
- *
559
- * The map case is the one with no spelling at all — `+` joins lists and
560
- * strings and refuses maps — so a child kind inheriting a map-valued field
561
- * could only REPLACE it. That turns a default the parent set for a reason into
562
- * something every consumer must restate, and a consumer who restates it
563
- * incompletely gets a system that works until the omitted entry matters.
564
- *
565
- * Follows the LEFT argument's shape: this extends that map, so what comes back
566
- * is what was extended. */
567
- const mergeMaps = (a: unknown, b: unknown): unknown => {
568
- const entries = [...mapEntries("merge", a), ...mapEntries("merge", b)];
569
- return a instanceof Map ? new Map(entries) : Object.fromEntries(entries);
570
- };
571
-
572
- const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
573
-
574
- /** Base64 → bytes, written out rather than delegated: `Buffer` is not browser-
575
- * safe and `atob` round-trips through a string, which is the corruption this
576
- * pair exists to avoid. Accepts the URL-safe alphabet and tolerates missing
577
- * padding, both of which appear in real API payloads; a character outside the
578
- * alphabet is a hard error rather than a silently dropped byte. */
579
- function decodeBase64ToBytes(input: string): Uint8Array {
580
- const clean = input.replace(/[\r\n\t ]/g, "").replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
581
- // A remainder of 1 cannot come from any byte sequence: base64 encodes 3 bytes
582
- // as 4 characters, so the valid remainders are 0, 2 and 3. Left to the loop it
583
- // would leave 6 bits unwritten and return a SHORT buffer — the silently dropped
584
- // byte this function refuses for a bad character.
585
- if (clean.length % 4 === 1) {
586
- throw new Error("bytesFromBase64: input length is not valid base64");
587
- }
588
- const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
589
- let bits = 0;
590
- let acc = 0;
591
- let written = 0;
592
- for (const ch of clean) {
593
- const value = BASE64_ALPHABET.indexOf(ch);
594
- if (value < 0) throw new Error(`bytesFromBase64: '${ch}' is not a base64 character`);
595
- acc = (acc << 6) | value;
596
- bits += 6;
597
- if (bits >= 8) {
598
- bits -= 8;
599
- out[written++] = (acc >> bits) & 0xff;
600
- }
601
- }
602
- return out.subarray(0, written);
603
- }
604
-
605
- function encodeBytesToBase64(input: Uint8Array): string {
606
- let out = "";
607
- for (let i = 0; i < input.length; i += 3) {
608
- const a = input[i]!;
609
- const b = i + 1 < input.length ? input[i + 1]! : undefined;
610
- const c = i + 2 < input.length ? input[i + 2]! : undefined;
611
- out += BASE64_ALPHABET[a >> 2];
612
- out += BASE64_ALPHABET[((a & 0x03) << 4) | ((b ?? 0) >> 4)];
613
- out += b === undefined ? "=" : BASE64_ALPHABET[((b & 0x0f) << 2) | ((c ?? 0) >> 6)];
614
- out += c === undefined ? "=" : BASE64_ALPHABET[c & 0x3f];
615
- }
616
- return out;
617
- }
618
-
619
- export const CEL_FUNCTIONS: readonly CelFunctionDoc[] = [
620
- // Collections
621
- {
622
- name: "join",
623
- signature: "join(list, string): string",
624
- category: "collection",
625
- summary: "Join list elements into a string with a separator.",
626
- deterministic: true,
627
- hostBacked: false,
628
- build: () => (list: unknown[], sep: string) => list.map(String).join(sep),
629
- },
630
- {
631
- name: "keys",
632
- signature: "keys(map): list",
633
- category: "collection",
634
- summary: "List a map's keys.",
635
- deterministic: true,
636
- hostBacked: false,
637
- build: () => (map: unknown) =>
638
- map instanceof Map ? [...map.keys()] : Object.keys(map as Record<string, unknown>),
639
- },
640
- {
641
- name: "values",
642
- signature: "values(map): list",
643
- category: "collection",
644
- summary: "List a map's values.",
645
- deterministic: true,
646
- hostBacked: false,
647
- build: () => (map: unknown) =>
648
- map instanceof Map ? [...map.values()] : Object.values(map as Record<string, unknown>),
649
- },
650
- {
651
- name: "distinct",
652
- signature: "distinct(list): list",
653
- category: "collection",
654
- summary: "Remove duplicate elements, preserving order.",
655
- deterministic: true,
656
- hostBacked: false,
657
- build: () => (list: unknown[]) => [...new Set(list)],
658
- },
659
- {
660
- name: "reverse",
661
- signature: "reverse(list): list",
662
- category: "collection",
663
- summary: "Reverse a list (copy; never mutates the input).",
664
- deterministic: true,
665
- hostBacked: false,
666
- build: () => (list: unknown[]) => [...list].reverse(),
667
- },
668
- {
669
- name: "flatten",
670
- signature: "flatten(list): list",
671
- category: "collection",
672
- summary: "Flatten one level of nested lists.",
673
- deterministic: true,
674
- hostBacked: false,
675
- build: () => (list: unknown[]) => list.flat(),
676
- },
677
- {
678
- name: "sort",
679
- signature: "sort(list): list",
680
- category: "collection",
681
- summary: "Sort a list numerically (numbers) or lexicographically; copy.",
682
- deterministic: true,
683
- hostBacked: false,
684
- build: () => (list: unknown[]) => sortList(list),
685
- },
686
- {
687
- name: "range",
688
- signature: "range(int): list<int>",
689
- category: "collection",
690
- summary: "Integers [0, n-1] (empty for n <= 0); materializes indices for an unknown-length list.",
691
- deterministic: true,
692
- hostBacked: false,
693
- build: () => (n: unknown) =>
694
- Array.from({ length: Math.max(0, Math.trunc(num(n))) }, (_unused, i) => BigInt(i)),
695
- },
696
- {
697
- name: "enumerate",
698
- signature: "enumerate(list): list",
699
- category: "collection",
700
- summary: "Pair each element with its zero-based position as {index, value}.",
701
- deterministic: true,
702
- hostBacked: false,
703
- build: () => (list: unknown[]) =>
704
- list.map((value, i) => ({ index: BigInt(i), value })),
705
- },
706
- // Strings
707
- {
708
- name: "lower",
709
- signature: "lower(string): string",
710
- category: "string",
711
- summary: "Lowercase a string.",
712
- deterministic: true,
713
- hostBacked: false,
714
- build: () => (s: string) => s.toLowerCase(),
715
- },
716
- {
717
- name: "upper",
718
- signature: "upper(string): string",
719
- category: "string",
720
- summary: "Uppercase a string.",
721
- deterministic: true,
722
- hostBacked: false,
723
- build: () => (s: string) => s.toUpperCase(),
724
- },
725
- {
726
- name: "trim",
727
- signature: "trim(string): string",
728
- category: "string",
729
- summary: "Strip leading/trailing whitespace.",
730
- deterministic: true,
731
- hostBacked: false,
732
- build: () => (s: string) => s.trim(),
733
- },
734
- {
735
- name: "replace",
736
- signature: "replace(string, string, string): string",
737
- category: "string",
738
- summary: "Replace all occurrences of a substring.",
739
- deterministic: true,
740
- hostBacked: false,
741
- build: () => (s: string, a: string, b: string) => s.split(a).join(b),
742
- },
743
- {
744
- name: "split",
745
- signature: "split(string, string): list",
746
- category: "string",
747
- summary: "Split a string on a separator into a list.",
748
- deterministic: true,
749
- hostBacked: false,
750
- build: () => (s: string, sep: string) => s.split(sep),
751
- },
752
- {
753
- name: "regexReplace",
754
- signature: "regexReplace(string, string, string, string?): string",
755
- category: "string",
756
- summary:
757
- "Replace every regex match (RE2 syntax) with a replacement ($1 backrefs); flags like 'i', 'm', 's'.",
758
- deterministic: true,
759
- hostBacked: false,
760
- checkArgs: regexLiteralGuard("regexReplace", 1, 3),
761
- build: () => (s: string, pattern: string, replacement: string, flags?: string) =>
762
- compileRe2("regexReplace", pattern, flags).matcher(s).replaceAll(replacement),
763
- },
764
- {
765
- name: "regexExtract",
766
- signature: "regexExtract(string, string, string?): string",
767
- category: "string",
768
- summary: "First whole match of a regex (RE2 syntax), or '' when there is none.",
769
- deterministic: true,
770
- hostBacked: false,
771
- checkArgs: regexLiteralGuard("regexExtract", 1, 2),
772
- build: () => (s: string, pattern: string, flags?: string) => {
773
- const m = compileRe2("regexExtract", pattern, flags).matcher(s);
774
- return m.find() ? (m.group() ?? "") : "";
775
- },
776
- },
777
- {
778
- name: "regexExtractAll",
779
- signature: "regexExtractAll(string, string, string?): list<string>",
780
- category: "string",
781
- summary: "Every whole match of a regex (RE2 syntax), in order.",
782
- deterministic: true,
783
- hostBacked: false,
784
- checkArgs: regexLiteralGuard("regexExtractAll", 1, 2),
785
- build: () => (s: string, pattern: string, flags?: string) => {
786
- const m = compileRe2("regexExtractAll", pattern, flags).matcher(s);
787
- const out: string[] = [];
788
- while (m.find()) out.push(m.group() ?? "");
789
- return out;
790
- },
791
- },
792
- {
793
- name: "regexGroups",
794
- signature: "regexGroups(string, string, string?): list<string>",
795
- category: "string",
796
- summary:
797
- "Capture groups of the first regex match (RE2 syntax); empty list when there is no match.",
798
- deterministic: true,
799
- hostBacked: false,
800
- checkArgs: regexLiteralGuard("regexGroups", 1, 2),
801
- build: () => (s: string, pattern: string, flags?: string) => {
802
- const m = compileRe2("regexGroups", pattern, flags).matcher(s);
803
- if (!m.find()) return [];
804
- return Array.from({ length: m.groupCount() }, (_unused, i) => m.group(i + 1) ?? "");
805
- },
806
- },
807
- {
808
- name: "trimPrefix",
809
- signature: "trimPrefix(string, string): string",
810
- category: "string",
811
- summary: "Strip a leading prefix if present.",
812
- deterministic: true,
813
- hostBacked: false,
814
- build: () => (s: string, prefix: string) => (s.startsWith(prefix) ? s.slice(prefix.length) : s),
815
- },
816
- {
817
- name: "trimSuffix",
818
- signature: "trimSuffix(string, string): string",
819
- category: "string",
820
- summary: "Strip a trailing suffix if present.",
821
- deterministic: true,
822
- hostBacked: false,
823
- build: () => (s: string, suffix: string) =>
824
- suffix && s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s,
825
- },
826
- // One `slice` over the three sequence types rather than three names: CEL
827
- // already treats `size()` that way, and the alternative teaches an author that
828
- // slicing bytes is a different operation from slicing a string.
829
- //
830
- // OVERLOADED BY PARAMETER TYPE, so a wrong receiver is rejected — `slice(42, 0,
831
- // 1)` matches nothing. What cannot ALSO be registered is a `dyn` parameter
832
- // variant: cel-js refuses overloads that overlap, and a `dyn` first parameter
833
- // overlaps all three. That is why the RETURN is `dyn` rather than the input's
834
- // own type. A step result whose producer declares no output type is `dyn`, and
835
- // with concrete returns the checker resolves such a call to whichever overload
836
- // was registered first and pins the result to it — so slicing an untyped byte
837
- // buffer came back typed `string`, and a byte consumer downstream reported a
838
- // mismatch against perfectly valid CEL. Precision on the way out would be lost
839
- // at the CEL boundary anyway, where type arguments are erased; being wrong
840
- // about an untyped receiver would not be.
841
- {
842
- name: "slice",
843
- signature: "slice(dyn, int, int): dyn",
844
- register: [
845
- "slice(bytes, int, int): dyn",
846
- "slice(string, int, int): dyn",
847
- "slice(list, int, int): dyn",
848
- ],
849
- // Not "string": it is the one function over strings, bytes AND lists, and the
850
- // category is what groups it in the generated reference — filing it under
851
- // strings hides it from the byte and list readers who need it most.
852
- category: "collection",
853
- summary: "Take the half-open range [start, end) of a string, bytes or list.",
854
- deterministic: true,
855
- hostBacked: false,
856
- // Indices arrive as BigInt (a CEL int is int64), and both `String.slice` and
857
- // `TypedArray.subarray` reject one. `subarray` rather than `slice` for bytes:
858
- // a view costs no copy, and every consumer treats the result as read-only.
859
- build: () => (value: string | Uint8Array | unknown[], start: bigint, end: bigint) => {
860
- const from = Number(start);
861
- const to = Number(end);
862
- return value instanceof Uint8Array ? value.subarray(from, to) : value.slice(from, to);
863
- },
864
- },
865
- // Math
866
- {
867
- name: "abs",
868
- signature: "abs(dyn): double",
869
- category: "math",
870
- summary: "Absolute value.",
871
- deterministic: true,
872
- hostBacked: false,
873
- build: () => (x: unknown) => Math.abs(num(x)),
874
- },
875
- {
876
- name: "floor",
877
- signature: "floor(dyn): double",
878
- category: "math",
879
- summary: "Round down to an integer.",
880
- deterministic: true,
881
- hostBacked: false,
882
- build: () => (x: unknown) => Math.floor(num(x)),
883
- },
884
- {
885
- name: "ceil",
886
- signature: "ceil(dyn): double",
887
- category: "math",
888
- summary: "Round up to an integer.",
889
- deterministic: true,
890
- hostBacked: false,
891
- build: () => (x: unknown) => Math.ceil(num(x)),
892
- },
893
- {
894
- name: "round",
895
- signature: "round(dyn, int?): double",
896
- register: [
897
- "round(double): double",
898
- "round(int): double",
899
- "round(double, int): double",
900
- "round(int, int): double",
901
- ],
902
- category: "math",
903
- summary:
904
- "Round to the nearest integer, or to the given number of decimal places (0–10). The two-argument form shares the formatter's rounding rule, so a rounded value and the cell rendered beside it agree at the boundary. An integer past 2^53 is refused rather than rounded to a neighbour.",
905
- deterministic: true,
906
- hostBacked: false,
907
- // Both arities go through `formattable`, so the 2^53 refusal does not depend
908
- // on which one the author wrote. Guarding only the two-argument form left
909
- // `round(x)` silently answering with a neighbouring integer — the defect
910
- // this family exists to close, reachable by writing one fewer argument.
911
- build: () => (x: unknown, digits?: unknown) =>
912
- digits === undefined
913
- ? Math.round(formattable("round", x))
914
- : Number(formattable("round", x).toFixed(digitCount("round", digits))),
915
- checkArgs: (lit) =>
916
- literalGuard(() => {
917
- if (lit[1] !== undefined) digitCount("round", lit[1]);
918
- if (typeof lit[0] === "bigint") formattable("round", lit[0]);
919
- }),
920
- },
921
- {
922
- name: "min",
923
- signature: "min(list): dyn",
924
- category: "math",
925
- summary: "Smallest element (by numeric value); null for an empty list.",
926
- deterministic: true,
927
- hostBacked: false,
928
- build: () => (list: unknown[]) => minMax(list, true),
929
- },
930
- {
931
- name: "max",
932
- signature: "max(list): dyn",
933
- category: "math",
934
- summary: "Largest element (by numeric value); null for an empty list.",
935
- deterministic: true,
936
- hostBacked: false,
937
- build: () => (list: unknown[]) => minMax(list, false),
938
- },
939
- {
940
- name: "sum",
941
- signature: "sum(list): double",
942
- category: "math",
943
- summary: "Sum of a list's numeric elements; 0 for an empty list.",
944
- deterministic: true,
945
- hostBacked: false,
946
- build: () => (list: unknown[]) =>
947
- Array.isArray(list) ? list.reduce((acc: number, x) => acc + num(x), 0) : 0,
948
- },
949
- {
950
- name: "avg",
951
- signature: "avg(list): dyn",
952
- category: "math",
953
- summary: "Arithmetic mean of a list's numeric elements; null for an empty list.",
954
- deterministic: true,
955
- hostBacked: false,
956
- build: () => (list: unknown[]) =>
957
- Array.isArray(list) && list.length > 0
958
- ? list.reduce((acc: number, x) => acc + num(x), 0) / list.length
959
- : null,
960
- },
961
- // JSON
962
- {
963
- name: "json",
964
- signature: "json(dyn): string",
965
- category: "json",
966
- summary: "Serialize any value to a JSON string.",
967
- deterministic: true,
968
- hostBacked: true,
969
- build: (h) => (value: unknown) => h.json(value),
970
- },
971
- {
972
- name: "parseJson",
973
- signature: "parseJson(string): dyn",
974
- category: "json",
975
- summary: "Parse a JSON string into a value (numbers come back as doubles).",
976
- deterministic: true,
977
- hostBacked: false,
978
- build: () => (s: string) => parseJsonText(s),
979
- },
980
- // Paths. The one way to extend a host path: `variables.dataDir.joinPath('reports')`
981
- // keeps it a `Telo.HostPath` (the analyzer types that overload), where `+`
982
- // would make it a plain string. Host-backed because what a separator IS
983
- // belongs to the machine running it.
984
- {
985
- name: "joinPath",
986
- signature: "string.joinPath(string): string",
987
- register: ["string.joinPath(string): string"],
988
- category: "string",
989
- summary:
990
- "Join a relative path onto a path with the host's separator (`\\` on Windows). On a host path it yields a host path; an absolute argument is refused.",
991
- deterministic: true,
992
- hostBacked: true,
993
- build: (h) => (base: string, relative: string) => h.joinPath(base, relative),
994
- },
995
- // Encoding
996
- {
997
- name: "base64Encode",
998
- signature: "base64Encode(string): string",
999
- category: "encoding",
1000
- summary: "Encode a UTF-8 string as base64.",
1001
- deterministic: true,
1002
- hostBacked: true,
1003
- build: (h) => (s: string) => h.base64Encode(s),
1004
- },
1005
- {
1006
- name: "base64Decode",
1007
- signature: "base64Decode(string): string",
1008
- category: "encoding",
1009
- summary: "Decode a base64 string to UTF-8.",
1010
- deterministic: true,
1011
- hostBacked: true,
1012
- build: (h) => (s: string) => h.base64Decode(s),
1013
- },
1014
- // Base64 <-> BYTES, as distinct from the two above, which are UTF-8
1015
- // string<->string and silently corrupt anything that is not text. Those keep
1016
- // their meaning (changing it would change what shipped manifests mean); these
1017
- // are the correct path for binary, and the pair a byte-typed slot needs.
1018
- // Pure-JS on purpose: `Buffer` is what made the string pair host-backed, and
1019
- // this package has to stay browser-safe.
1020
- {
1021
- name: "bytesFromBase64",
1022
- signature: "bytesFromBase64(string): bytes",
1023
- category: "encoding",
1024
- summary: "Decode a base64 string to raw bytes.",
1025
- deterministic: true,
1026
- hostBacked: false,
1027
- build: () => (s: string) => decodeBase64ToBytes(s),
1028
- },
1029
- {
1030
- name: "bytesToBase64",
1031
- signature: "bytesToBase64(bytes): string",
1032
- category: "encoding",
1033
- summary: "Encode raw bytes as a base64 string.",
1034
- deterministic: true,
1035
- hostBacked: false,
1036
- build: () => (b: Uint8Array) => encodeBytesToBase64(b),
1037
- },
1038
- {
1039
- name: "urlEncode",
1040
- signature: "urlEncode(string): string",
1041
- category: "encoding",
1042
- summary: "Percent-encode a URI component.",
1043
- deterministic: true,
1044
- hostBacked: false,
1045
- build: () => (s: string) => encodeURIComponent(s),
1046
- },
1047
- {
1048
- name: "urlDecode",
1049
- signature: "urlDecode(string): string",
1050
- category: "encoding",
1051
- summary: "Decode a percent-encoded URI component.",
1052
- deterministic: true,
1053
- hostBacked: false,
1054
- build: () => (s: string) => decodeURIComponent(s),
1055
- },
1056
- // Hashing
1057
- {
1058
- name: "sha256",
1059
- signature: "sha256(string): string",
1060
- category: "hashing",
1061
- summary: "SHA-256 hash, hex-encoded.",
1062
- deterministic: true,
1063
- hostBacked: true,
1064
- build: (h) => (s: string) => h.sha256(s),
1065
- },
1066
- {
1067
- name: "md5",
1068
- signature: "md5(string): string",
1069
- category: "hashing",
1070
- summary: "MD5 hash, hex-encoded.",
1071
- deterministic: true,
1072
- hostBacked: true,
1073
- build: (h) => (s: string) => h.md5(s),
1074
- },
1075
- {
1076
- name: "sha1",
1077
- signature: "sha1(string): string",
1078
- category: "hashing",
1079
- summary: "SHA-1 hash, hex-encoded.",
1080
- deterministic: true,
1081
- hostBacked: true,
1082
- build: (h) => (s: string) => h.sha1(s),
1083
- },
1084
- {
1085
- name: "sha512",
1086
- signature: "sha512(string): string",
1087
- category: "hashing",
1088
- summary: "SHA-512 hash, hex-encoded.",
1089
- deterministic: true,
1090
- hostBacked: true,
1091
- build: (h) => (s: string) => h.sha512(s),
1092
- },
1093
- {
1094
- name: "hmac",
1095
- signature: "hmac(string, string, string): string",
1096
- category: "hashing",
1097
- summary: "HMAC of message under key for an algorithm (e.g. 'sha256'), hex.",
1098
- deterministic: true,
1099
- hostBacked: true,
1100
- build: (h) => (algo: string, key: string, msg: string) => h.hmac(algo, key, msg),
1101
- },
1102
- // Null handling
1103
- {
1104
- name: "default",
1105
- signature: "default(dyn, dyn): dyn",
1106
- category: "null",
1107
- summary: "Return the value, or the fallback when it is null.",
1108
- deterministic: true,
1109
- hostBacked: false,
1110
- build: () => (v: unknown, fallback: unknown) =>
1111
- v === null || v === undefined ? fallback : v,
1112
- },
1113
- {
1114
- name: "coalesce",
1115
- signature: "coalesce(list): dyn",
1116
- category: "null",
1117
- summary: "First non-null element of a list, or null.",
1118
- deterministic: true,
1119
- hostBacked: false,
1120
- build: () => (list: unknown[]) => {
1121
- const found = list.find((x) => x !== null && x !== undefined);
1122
- return found === undefined ? null : found;
1123
- },
1124
- },
1125
- // Time (non-deterministic). `nowIso`/`today` take an optional IANA timezone
1126
- // (default "UTC"); epoch values are absolute and take none.
1127
- {
1128
- name: "now",
1129
- signature: "now(): timestamp",
1130
- register: ["now(): google.protobuf.Timestamp"],
1131
- category: "time",
1132
- summary: "Current instant as a native timestamp, for comparison and duration arithmetic.",
1133
- deterministic: false,
1134
- hostBacked: false,
1135
- build: () => () => new Date(),
1136
- },
1137
- {
1138
- name: "nowIso",
1139
- signature: "nowIso(string?): string",
1140
- category: "time",
1141
- summary: "Current time as ISO-8601; UTC by default, or in the given IANA timezone.",
1142
- deterministic: false,
1143
- hostBacked: false,
1144
- build: () => (tz?: string) => isoInZone(new Date(), tz ?? "UTC"),
1145
- },
1146
- {
1147
- name: "today",
1148
- signature: "today(string?): string",
1149
- category: "time",
1150
- summary: "Current calendar date (YYYY-MM-DD); UTC by default, or in the given IANA timezone.",
1151
- deterministic: false,
1152
- hostBacked: false,
1153
- build: () => (tz?: string) => dateInZone(new Date(), tz ?? "UTC"),
1154
- },
1155
- {
1156
- name: "nowMillis",
1157
- signature: "nowMillis(): int",
1158
- category: "time",
1159
- summary: "Current time as epoch milliseconds (absolute; timezone-independent).",
1160
- deterministic: false,
1161
- hostBacked: false,
1162
- build: () => () => BigInt(Date.now()),
1163
- },
1164
- {
1165
- name: "nowSeconds",
1166
- signature: "nowSeconds(): int",
1167
- category: "time",
1168
- summary: "Current time as epoch seconds (absolute; timezone-independent).",
1169
- deterministic: false,
1170
- hostBacked: false,
1171
- build: () => () => BigInt(Math.floor(Date.now() / 1000)),
1172
- },
1173
- // Timestamp conversions. cel-go's standard library defines both and cel-js
1174
- // ships neither, which is what made an instant a one-way door: timestamp
1175
- // arithmetic and the `getFullYear` / `getHours` family already work, but
1176
- // nothing converted the result back into a value a manifest field accepts,
1177
- // so an expiry could be computed and not stored. Semantics follow cel-go
1178
- // exactly — RFC 3339 and epoch SECONDS — so `int(timestamp)` and
1179
- // `timestamp(int)` round-trip in one unit.
1180
- //
1181
- // `string(duration)` is cel-spec's too, and cel-js omits it: seconds with a
1182
- // trimmed fraction, the `Telo.Duration` plain encoding, so a duration renders
1183
- // one way whether it is interpolated or serialized.
1184
- {
1185
- name: "string",
1186
- signature: "string(timestamp | duration): string",
1187
- register: [
1188
- "string(google.protobuf.Timestamp): string",
1189
- "string(google.protobuf.Duration): string",
1190
- ],
1191
- category: "conversion",
1192
- summary:
1193
- "Format an instant as RFC 3339 (ISO-8601, UTC), or a duration as seconds with a trimmed fraction (`5400s`, `1.5s`).",
1194
- deterministic: true,
1195
- hostBacked: false,
1196
- build: () => (value: unknown) =>
1197
- value instanceof Date ? value.toISOString() : PLAIN_ENCODINGS["cel-duration"]!.encode(value),
1198
- },
1199
- {
1200
- name: "int",
1201
- signature: "int(timestamp): int",
1202
- register: ["int(google.protobuf.Timestamp): int"],
1203
- category: "conversion",
1204
- summary: "Epoch seconds of an instant (the unit `timestamp(int)` reads back).",
1205
- deterministic: true,
1206
- hostBacked: false,
1207
- build: () => (t: Date) => BigInt(Math.floor(t.getTime() / 1000)),
1208
- },
1209
- // Formatting. The number surface is the d3-format specifier grammar in full,
1210
- // `[[fill]align][sign][symbol][0][width][,][.precision][~][type]`, so a chart
1211
- // axis label and the table cell beside it cannot round the same value two
1212
- // ways. Rounding is therefore d3's: `f` rounds the double at the decimal
1213
- // place, so `.2f` of 1.005 is "1.00" — 1.005 is not representable and the
1214
- // nearest double sits below the half.
1215
- {
1216
- name: "format",
1217
- signature: "format(dyn, string): string",
1218
- // Registered per numeric type rather than as `dyn`. A `dyn` first parameter
1219
- // accepted a string and answered "NaN" — a value that looks like an answer
1220
- // and prints into a document. A genuinely dynamic expression still passes,
1221
- // because cel-js matches `dyn` against any declared parameter type; what
1222
- // this rejects is a STATICALLY known wrong type, at `telo check`.
1223
- register: ["format(double, string): string", "format(int, string): string"],
1224
- category: "formatting",
1225
- summary: "Format a number with a d3-format specifier (`.2f`, `,.2f`, `.1%`, `.2s`).",
1226
- deterministic: true,
1227
- hostBacked: false,
1228
- build: () => (x: unknown, spec: unknown) => formatter("format", spec)(formattable("format", x)),
1229
- checkArgs: (lit) =>
1230
- literalGuard(() => {
1231
- if (lit[1] !== undefined) formatter("format", lit[1]);
1232
- if (typeof lit[0] === "bigint") formattable("format", lit[0]);
1233
- }),
1234
- },
1235
- {
1236
- name: "fixed",
1237
- signature: "fixed(dyn, int): string",
1238
- register: ["fixed(double, int): string", "fixed(int, int): string"],
1239
- category: "formatting",
1240
- summary: "Fixed-decimal string with the given number of places (0–10).",
1241
- deterministic: true,
1242
- hostBacked: false,
1243
- build: () => (x: unknown, digits: unknown) =>
1244
- formatter("fixed", `.${digitCount("fixed", digits)}f`)(formattable("fixed", x)),
1245
- checkArgs: (lit) =>
1246
- literalGuard(() => {
1247
- if (lit[1] !== undefined) digitCount("fixed", lit[1]);
1248
- if (typeof lit[0] === "bigint") formattable("fixed", lit[0]);
1249
- }),
1250
- },
1251
- {
1252
- name: "formatDuration",
1253
- signature: "formatDuration(dyn, int): string",
1254
- register: [
1255
- "formatDuration(double, int): string",
1256
- "formatDuration(int, int): string",
1257
- ],
1258
- category: "formatting",
1259
- summary:
1260
- "Render a minute count against a declared day length: `formatDuration(510, 480)` is `1d 30m`. The day length is an argument because it is a policy, not arithmetic. The result is a rendering for a reader, not a duration literal — its `d` is the declared day, so it must not be fed back into a field that parses a duration.",
1261
- deterministic: true,
1262
- hostBacked: false,
1263
- build: () => (minutes: unknown, minutesPerDay: unknown) => durationText(minutes, minutesPerDay),
1264
- checkArgs: (lit) =>
1265
- literalGuard(() => {
1266
- if (lit[1] !== undefined) durationText(lit[0] ?? 0, lit[1]);
1267
- }),
1268
- },
1269
- {
1270
- name: "dateIn",
1271
- signature: "dateIn(timestamp, string?): string",
1272
- register: [
1273
- "dateIn(google.protobuf.Timestamp): string",
1274
- "dateIn(google.protobuf.Timestamp, string): string",
1275
- ],
1276
- category: "time",
1277
- summary: "Calendar date (`YYYY-MM-DD`) of an instant, in an IANA zone (UTC by default).",
1278
- deterministic: true,
1279
- hostBacked: false,
1280
- build: () => (t: unknown, tz?: string) => dateInZone(instantArg("dateIn", t), assertZone("dateIn", tz ?? "UTC")),
1281
- checkArgs: (lit) =>
1282
- literalGuard(() => {
1283
- if (typeof lit[1] === "string") assertZone("dateIn", lit[1]);
1284
- }),
1285
- },
1286
- {
1287
- name: "isoIn",
1288
- signature: "isoIn(timestamp, string?): string",
1289
- register: [
1290
- "isoIn(google.protobuf.Timestamp): string",
1291
- "isoIn(google.protobuf.Timestamp, string): string",
1292
- ],
1293
- category: "time",
1294
- summary: "ISO-8601 rendering of an instant, in an IANA zone (UTC by default).",
1295
- deterministic: true,
1296
- hostBacked: false,
1297
- build: () => (t: unknown, tz?: string) => isoInZone(instantArg("isoIn", t), assertZone("isoIn", tz ?? "UTC")),
1298
- checkArgs: (lit) =>
1299
- literalGuard(() => {
1300
- if (typeof lit[1] === "string") assertZone("isoIn", lit[1]);
1301
- }),
1302
- },
1303
- {
1304
- name: "startOfMonth",
1305
- signature: "startOfMonth(timestamp, string?): timestamp",
1306
- register: [
1307
- "startOfMonth(google.protobuf.Timestamp): google.protobuf.Timestamp",
1308
- "startOfMonth(google.protobuf.Timestamp, string): google.protobuf.Timestamp",
1309
- ],
1310
- category: "time",
1311
- summary: "Midnight on the 1st of the instant's month, in an IANA zone (UTC by default).",
1312
- deterministic: true,
1313
- hostBacked: false,
1314
- checkArgs: (lit) =>
1315
- literalGuard(() => {
1316
- if (typeof lit[1] === "string") assertZone("startOfMonth", lit[1]);
1317
- }),
1318
- build: () => (t: unknown, tz?: string) => {
1319
- const zone = assertZone("startOfMonth", tz ?? "UTC");
1320
- const f = zonedFields(instantArg("startOfMonth", t), zone);
1321
- return instantOfZoned(
1322
- { year: f.year, month: f.month, day: 1, hour: 0, minute: 0, second: 0 },
1323
- zone,
1324
- );
1325
- },
1326
- },
1327
- {
1328
- name: "addMonths",
1329
- signature: "addMonths(timestamp, int, string?): timestamp",
1330
- register: [
1331
- "addMonths(google.protobuf.Timestamp, int): google.protobuf.Timestamp",
1332
- "addMonths(google.protobuf.Timestamp, int, string): google.protobuf.Timestamp",
1333
- ],
1334
- category: "time",
1335
- summary:
1336
- "Shift an instant by whole months in an IANA zone, clamping the day of month (Jan 31 + 1 month is Feb 28).",
1337
- deterministic: true,
1338
- hostBacked: false,
1339
- checkArgs: (lit) =>
1340
- literalGuard(() => {
1341
- if (typeof lit[2] === "string") assertZone("addMonths", lit[2]);
1342
- }),
1343
- build: () => (t: unknown, months: unknown, tz?: string) => {
1344
- const zone = assertZone("addMonths", tz ?? "UTC");
1345
- const f = zonedFields(instantArg("addMonths", t), zone);
1346
- const shifted = f.year * 12 + (f.month - 1) + Number(months);
1347
- // `%` takes the dividend's sign in JS, so a negative total would yield
1348
- // month 0. Unreachable for realistic dates and wrong for free otherwise.
1349
- const year = Math.floor(shifted / 12);
1350
- const month = (((shifted % 12) + 12) % 12) + 1;
1351
- return instantOfZoned({ ...f, year, month, day: Math.min(f.day, daysInMonth(year, month)) }, zone);
1352
- },
1353
- },
1354
- {
1355
- name: "compact",
1356
- signature: "compact(dyn): dyn",
1357
- // A `dyn` parameter accepted an instant (yielding `{}`) and a byte buffer
1358
- // (yielding `{"0":137,…}`), both silently and both passing `telo check`.
1359
- register: ["compact(list): list", "compact(map): map"],
1360
- category: "collection",
1361
- summary: "Drop entries whose value is null or the empty string, from a map or a list.",
1362
- deterministic: true,
1363
- hostBacked: false,
1364
- build: () => (v: unknown) => compactValue(v),
1365
- },
1366
- {
1367
- name: "merge",
1368
- signature: "merge(map, map): map",
1369
- register: ["merge(map, map): map"],
1370
- category: "collection",
1371
- summary:
1372
- "Combine two maps, with the right-hand map winning on a shared key. Use it to add to a map rather than replace it — `merge(defaults, overrides)`.",
1373
- deterministic: true,
1374
- hostBacked: false,
1375
- build: () => (a: unknown, b: unknown) => mergeMaps(a, b),
1376
- },
1377
- // UUID
1378
- {
1379
- name: "uuidv1",
1380
- signature: "uuidv1(): string",
1381
- category: "uuid",
1382
- summary: "Time-based UUID (v1).",
1383
- deterministic: false,
1384
- hostBacked: false,
1385
- build: () => () => v1(),
1386
- },
1387
- {
1388
- name: "uuidv4",
1389
- signature: "uuidv4(): string",
1390
- category: "uuid",
1391
- summary: "Random UUID (v4).",
1392
- deterministic: false,
1393
- hostBacked: false,
1394
- build: () => () => v4(),
1395
- },
1396
- {
1397
- name: "uuidv6",
1398
- signature: "uuidv6(): string",
1399
- category: "uuid",
1400
- summary: "Time-ordered UUID (v6).",
1401
- deterministic: false,
1402
- hostBacked: false,
1403
- build: () => () => v6(),
1404
- },
1405
- {
1406
- name: "uuidv7",
1407
- signature: "uuidv7(): string",
1408
- category: "uuid",
1409
- summary: "Time-ordered UUID (v7).",
1410
- deterministic: false,
1411
- hostBacked: false,
1412
- build: () => () => v7(),
1413
- },
1414
- {
1415
- name: "uuidv3",
1416
- signature: "uuidv3(string, string): string",
1417
- category: "uuid",
1418
- summary: "Name-based UUID (v3, MD5) under a namespace UUID.",
1419
- deterministic: true,
1420
- hostBacked: false,
1421
- build: () => (name: string, ns: string) => v3(name, ns),
1422
- },
1423
- {
1424
- name: "uuidv5",
1425
- signature: "uuidv5(string, string): string",
1426
- category: "uuid",
1427
- summary: "Name-based UUID (v5, SHA-1) under a namespace UUID.",
1428
- deterministic: true,
1429
- hostBacked: false,
1430
- build: () => (name: string, ns: string) => v5(name, ns),
1431
- },
1432
- {
1433
- name: "uuidValidate",
1434
- signature: "uuidValidate(string): bool",
1435
- category: "uuid",
1436
- summary: "True if the string is a valid UUID.",
1437
- deterministic: true,
1438
- hostBacked: false,
1439
- build: () => (s: string) => uuidValidate(s),
1440
- },
1441
- {
1442
- name: "uuidVersion",
1443
- signature: "uuidVersion(string): int",
1444
- category: "uuid",
1445
- summary: "The version number of a UUID.",
1446
- deterministic: true,
1447
- hostBacked: false,
1448
- build: () => (s: string) => BigInt(uuidVersion(s)),
1449
- },
1450
- ];
1451
-
1452
- /** Build-free catalog for the CLI / docs (`telo cel functions`). */
1453
- export function celFunctionCatalog(): CelFunctionInfo[] {
1454
- return CEL_FUNCTIONS.map(({ build: _build, ...info }) => info);
1455
- }