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