@jsb188/app 1.1.11 → 1.1.12

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 (59) hide show
  1. package/package.json +7 -4
  2. package/src/constants/agent.ts +39 -62
  3. package/src/constants/app.ts +17 -0
  4. package/src/constants/wsActions.ts +7 -15
  5. package/src/i18n/account.ts +1 -1
  6. package/src/i18n/agent.ts +326 -88
  7. package/src/i18n/agentToolBusiness.ts +196 -0
  8. package/src/i18n/agentToolGrid.ts +137 -0
  9. package/src/i18n/agentToolWorkflow.ts +101 -0
  10. package/src/i18n/agent_note.ts +109 -0
  11. package/src/i18n/app.ts +23 -17
  12. package/src/i18n/auth.ts +28 -30
  13. package/src/i18n/billing.ts +3 -85
  14. package/src/i18n/c.ts +907 -0
  15. package/src/i18n/campaign.ts +842 -140
  16. package/src/i18n/datetime.ts +6 -0
  17. package/src/i18n/editor.ts +58 -0
  18. package/src/i18n/error.ts +307 -168
  19. package/src/i18n/field_doc_editor.ts +21 -0
  20. package/src/i18n/field_doc_programs.ts +52 -0
  21. package/src/i18n/field_docs.ts +170 -8
  22. package/src/i18n/index.ts +21 -5
  23. package/src/i18n/log.ts +232 -38
  24. package/src/i18n/memory.ts +18 -4
  25. package/src/i18n/note.ts +5 -3
  26. package/src/i18n/org.ts +93 -44
  27. package/src/i18n/schedule.ts +209 -0
  28. package/src/i18n/sheet.ts +102 -145
  29. package/src/i18n/sheet_formula.ts +165 -0
  30. package/src/i18n/workflow.ts +48 -9
  31. package/src/main.ts +2 -2
  32. package/src/platform.ts +89 -49
  33. package/src/types/ai.d.ts +19 -0
  34. package/src/types/app.d.ts +50 -57
  35. package/src/types/other.d.ts +8 -1
  36. package/src/utils/api.ts +46 -0
  37. package/src/utils/clientIP.ts +213 -0
  38. package/src/utils/color.ts +77 -0
  39. package/src/utils/csv.ts +19 -0
  40. package/src/utils/datetime.ts +207 -31
  41. package/src/utils/deferredSave.ts +89 -0
  42. package/src/utils/email.ts +50 -0
  43. package/src/utils/expression.helpers.ts +470 -0
  44. package/src/utils/expression.test.ts +793 -0
  45. package/src/utils/expression.ts +1633 -239
  46. package/src/utils/language.ts +9 -0
  47. package/src/utils/logic.ts +9 -162
  48. package/src/utils/number.ts +30 -11
  49. package/src/utils/object.ts +29 -0
  50. package/src/utils/promise.ts +78 -7
  51. package/src/utils/queryReset.ts +101 -14
  52. package/src/utils/string.test.ts +24 -39
  53. package/src/utils/string.ts +73 -143
  54. package/src/utils/url_client.ts +83 -14
  55. package/src/constants/billing.ts +0 -146
  56. package/src/i18n/agentDoc.ts +0 -110
  57. package/src/i18n/form.ts +0 -496
  58. package/src/types/form.d.ts +0 -101
  59. package/src/utils/billing.ts +0 -141
@@ -1,3 +1,13 @@
1
+ import {
2
+ calculateExpressionDecimal,
3
+ compareExpressionValues,
4
+ parseDecoratedExpressionNumber,
5
+ parseExpressionDate,
6
+ parsePlainExpressionNumber,
7
+ roundExpressionDecimal,
8
+ sumExpressionNumbers,
9
+ } from './expression.helpers.ts';
10
+
1
11
  /**
2
12
  * Safe expression mini-DSL for declarative row transforms (no eval / no Function).
3
13
  *
@@ -6,32 +16,525 @@
6
16
  * and bracket segments for labels with spaces/symbols — `[Crop name]`, `metadata.[Unit price]`
7
17
  * - Literals: numbers, single-quoted strings ('it''s' escapes a quote), true, false, null
8
18
  * - Operators: + - * / (numeric), = != > >= < <= (comparisons), and or not, parentheses
9
- * - Functions: concat, coalesce, num, round, abs, upper, lower, trim, substr,
10
- * dateFormat, if, contains
19
+ * - Functions: see EXPRESSION_FUNCTIONS (text, number, date, logic and collection helpers)
20
+ *
21
+ * Values: a field reference may resolve to an array or object. The raw value is kept
22
+ * while it flows through `if`/`coalesce`/collection functions and is only converted to a
23
+ * scalar (`toScalar`) where a scalar is required (arithmetic, comparison, text functions,
24
+ * final output — arrays/objects become JSON text there).
11
25
  *
12
26
  * Deterministic null behavior: arithmetic with a non-numeric operand returns null,
13
- * division by zero returns null, string functions return null for null input.
27
+ * division by zero returns null, text functions return null for null input.
14
28
  */
15
29
 
16
- export const EXPRESSION_MAX_LENGTH = 300;
17
- export const EXPRESSION_MAX_DEPTH = 8;
30
+ export const EXPRESSION_MAX_LENGTH = 600;
31
+ export const EXPRESSION_MAX_DEPTH = 10;
32
+
33
+ export type ExpressionFunctionCategory =
34
+ | 'text'
35
+ | 'number'
36
+ | 'date'
37
+ | 'logic'
38
+ | 'collection';
39
+
40
+ export interface ExpressionFunctionSpec {
41
+ name: string;
42
+ signature: string;
43
+ description: string;
44
+ example: string;
45
+ category: ExpressionFunctionCategory;
46
+ minArgs: number;
47
+ maxArgs: number | null; // null = variadic
48
+ }
18
49
 
19
- export const EXPRESSION_FUNCTION_NAMES = [
20
- 'concat',
21
- 'coalesce',
22
- 'num',
23
- 'round',
24
- 'abs',
25
- 'upper',
26
- 'lower',
27
- 'trim',
28
- 'substr',
29
- 'dateFormat',
30
- 'if',
31
- 'contains',
32
- ] as const;
50
+ /**
51
+ * Function registry: the single source for parsing, evaluation, the prompt
52
+ * cheatsheet and the model-facing name list.
53
+ */
33
54
 
34
- type ExpressionFunctionName = (typeof EXPRESSION_FUNCTION_NAMES)[number];
55
+ export const EXPRESSION_FUNCTIONS = [
56
+ // Text
57
+ {
58
+ name: 'concat',
59
+ signature: 'concat(a, b, ...)',
60
+ description:
61
+ 'Joins every argument as text; null arguments become empty text.',
62
+ example: "concat(firstName, ' ', lastName)",
63
+ category: 'text',
64
+ minArgs: 1,
65
+ maxArgs: null,
66
+ },
67
+ {
68
+ name: 'coalesce',
69
+ signature: 'coalesce(a, b, ...)',
70
+ description:
71
+ 'Returns the first argument that is not null, empty text or an empty array; null when all are empty.',
72
+ example: "coalesce(metadata.vendor, counterparty.name, 'Unknown')",
73
+ category: 'text',
74
+ minArgs: 1,
75
+ maxArgs: null,
76
+ },
77
+ {
78
+ name: 'upper',
79
+ signature: 'upper(text)',
80
+ description: 'Upper-cases text; null stays null.',
81
+ example: 'upper(status)',
82
+ category: 'text',
83
+ minArgs: 1,
84
+ maxArgs: 1,
85
+ },
86
+ {
87
+ name: 'lower',
88
+ signature: 'lower(text)',
89
+ description: 'Lower-cases text; null stays null.',
90
+ example: 'lower(email)',
91
+ category: 'text',
92
+ minArgs: 1,
93
+ maxArgs: 1,
94
+ },
95
+ {
96
+ name: 'trim',
97
+ signature: 'trim(text)',
98
+ description: 'Removes surrounding whitespace; null stays null.',
99
+ example: 'trim([Vendor Name])',
100
+ category: 'text',
101
+ minArgs: 1,
102
+ maxArgs: 1,
103
+ },
104
+ {
105
+ name: 'substr',
106
+ signature: 'substr(text, start, length)',
107
+ description:
108
+ 'Text from the 0-based start position; length is optional (to the end when omitted); null stays null.',
109
+ example: 'substr(sku, 0, 3)',
110
+ category: 'text',
111
+ minArgs: 2,
112
+ maxArgs: 3,
113
+ },
114
+ {
115
+ name: 'replace',
116
+ signature: 'replace(text, find, replacement)',
117
+ description:
118
+ 'Replaces every occurrence of find (case-sensitive) with replacement; null text stays null, an empty find leaves the text unchanged.',
119
+ example: "replace(phone, '-', '')",
120
+ category: 'text',
121
+ minArgs: 3,
122
+ maxArgs: 3,
123
+ },
124
+ {
125
+ name: 'len',
126
+ signature: 'len(text)',
127
+ description: 'Number of characters in the text; null stays null.',
128
+ example: 'len(notes)',
129
+ category: 'text',
130
+ minArgs: 1,
131
+ maxArgs: 1,
132
+ },
133
+ {
134
+ name: 'startsWith',
135
+ signature: 'startsWith(text, prefix)',
136
+ description:
137
+ 'True when the text starts with prefix (case-insensitive); false for null text.',
138
+ example: "startsWith(sku, 'ORG-')",
139
+ category: 'text',
140
+ minArgs: 2,
141
+ maxArgs: 2,
142
+ },
143
+ {
144
+ name: 'endsWith',
145
+ signature: 'endsWith(text, suffix)',
146
+ description:
147
+ 'True when the text ends with suffix (case-insensitive); false for null text.',
148
+ example: "endsWith(fileName, '.pdf')",
149
+ category: 'text',
150
+ minArgs: 2,
151
+ maxArgs: 2,
152
+ },
153
+ {
154
+ name: 'padStart',
155
+ signature: 'padStart(text, length, fill)',
156
+ description:
157
+ 'Pads the start of the text with fill (default a space) until it is length characters long; null stays null.',
158
+ example: "padStart(invoiceNumber, 6, '0')",
159
+ category: 'text',
160
+ minArgs: 2,
161
+ maxArgs: 3,
162
+ },
163
+ {
164
+ name: 'left',
165
+ signature: 'left(text, n)',
166
+ description: 'The first n characters of the text; null stays null.',
167
+ example: 'left(date, 7)',
168
+ category: 'text',
169
+ minArgs: 2,
170
+ maxArgs: 2,
171
+ },
172
+ {
173
+ name: 'right',
174
+ signature: 'right(text, n)',
175
+ description: 'The last n characters of the text; null stays null.',
176
+ example: 'right(phone, 4)',
177
+ category: 'text',
178
+ minArgs: 2,
179
+ maxArgs: 2,
180
+ },
181
+ {
182
+ name: 'split',
183
+ signature: 'split(text, separator, index)',
184
+ description:
185
+ 'Splits the text on separator and returns the 0-based index part; null when the text is null or the index is out of range.',
186
+ example: "split(fullName, ' ', 0)",
187
+ category: 'text',
188
+ minArgs: 3,
189
+ maxArgs: 3,
190
+ },
191
+ {
192
+ name: 'contains',
193
+ signature: 'contains(text, search)',
194
+ description:
195
+ 'True when the text contains search (case-insensitive); false for null text.',
196
+ example: "contains(notes, 'organic')",
197
+ category: 'text',
198
+ minArgs: 2,
199
+ maxArgs: 2,
200
+ },
201
+ // Number
202
+ {
203
+ name: 'num',
204
+ signature: 'num(x)',
205
+ description:
206
+ 'Converts a complete decimal amount with optional currency or recognized units, such as "$1,200.50" or "12 lbs"; null for unrelated text.',
207
+ example: 'num(metadata.quantity) * num([Unit price])',
208
+ category: 'number',
209
+ minArgs: 1,
210
+ maxArgs: 1,
211
+ },
212
+ {
213
+ name: 'round',
214
+ signature: 'round(x, digits)',
215
+ description:
216
+ 'Rounds to digits decimal places (default 0, max 8); null for a non-numeric value.',
217
+ example: 'round(total * 0.0825, 2)',
218
+ category: 'number',
219
+ minArgs: 1,
220
+ maxArgs: 2,
221
+ },
222
+ {
223
+ name: 'abs',
224
+ signature: 'abs(x)',
225
+ description: 'Absolute value; null for a non-numeric value.',
226
+ example: 'abs(delta)',
227
+ category: 'number',
228
+ minArgs: 1,
229
+ maxArgs: 1,
230
+ },
231
+ {
232
+ name: 'min',
233
+ signature: 'min(a, b, ...)',
234
+ description:
235
+ 'Smallest numeric argument; non-numeric arguments are ignored, null when none is numeric.',
236
+ example: 'min(quantity, 100)',
237
+ category: 'number',
238
+ minArgs: 1,
239
+ maxArgs: null,
240
+ },
241
+ {
242
+ name: 'max',
243
+ signature: 'max(a, b, ...)',
244
+ description:
245
+ 'Largest numeric argument; non-numeric arguments are ignored, null when none is numeric.',
246
+ example: 'max(total - discount, 0)',
247
+ category: 'number',
248
+ minArgs: 1,
249
+ maxArgs: null,
250
+ },
251
+ {
252
+ name: 'floor',
253
+ signature: 'floor(x)',
254
+ description:
255
+ 'Rounds down to the nearest integer; null for a non-numeric value.',
256
+ example: 'floor(hours)',
257
+ category: 'number',
258
+ minArgs: 1,
259
+ maxArgs: 1,
260
+ },
261
+ {
262
+ name: 'ceil',
263
+ signature: 'ceil(x)',
264
+ description:
265
+ 'Rounds up to the nearest integer; null for a non-numeric value.',
266
+ example: 'ceil(weight / 50)',
267
+ category: 'number',
268
+ minArgs: 1,
269
+ maxArgs: 1,
270
+ },
271
+ {
272
+ name: 'mod',
273
+ signature: 'mod(a, b)',
274
+ description:
275
+ 'Remainder of a divided by b (sign follows a); null when either is non-numeric or b is 0.',
276
+ example: 'mod(rowNumber, 2)',
277
+ category: 'number',
278
+ minArgs: 2,
279
+ maxArgs: 2,
280
+ },
281
+ // Date
282
+ {
283
+ name: 'dateFormat',
284
+ signature: 'dateFormat(d, format, timeZone)',
285
+ description:
286
+ 'Formats an ISO or YYYY-MM-DD date using tokens YYYY, MM, DD, HH, mm, ss, MMM (Jan), MMMM (January), ddd (Mon), dddd (Monday); default format YYYY-MM-DD. Works in UTC unless the optional timeZone (an IANA name such as America/Los_Angeles, e.g. the row timeZone column) converts the moment first; null for an invalid date or unknown time zone.',
287
+ example: "dateFormat(startsAt, 'YYYY-MM-DD HH:mm', timeZone)",
288
+ category: 'date',
289
+ minArgs: 1,
290
+ maxArgs: 3,
291
+ },
292
+ {
293
+ name: 'year',
294
+ signature: 'year(d)',
295
+ description: 'Four-digit year of the date (UTC); null for an invalid date.',
296
+ example: 'year(date)',
297
+ category: 'date',
298
+ minArgs: 1,
299
+ maxArgs: 1,
300
+ },
301
+ {
302
+ name: 'month',
303
+ signature: 'month(d)',
304
+ description:
305
+ 'Month number 1-12 of the date (UTC); null for an invalid date.',
306
+ example: 'month(date)',
307
+ category: 'date',
308
+ minArgs: 1,
309
+ maxArgs: 1,
310
+ },
311
+ {
312
+ name: 'day',
313
+ signature: 'day(d)',
314
+ description:
315
+ 'Day of month 1-31 of the date (UTC); null for an invalid date.',
316
+ example: 'day(date)',
317
+ category: 'date',
318
+ minArgs: 1,
319
+ maxArgs: 1,
320
+ },
321
+ {
322
+ name: 'weekday',
323
+ signature: 'weekday(d)',
324
+ description:
325
+ 'Day of week as a number, 0 = Sunday through 6 = Saturday (UTC); null for an invalid date.',
326
+ example: 'weekday(date)',
327
+ category: 'date',
328
+ minArgs: 1,
329
+ maxArgs: 1,
330
+ },
331
+ {
332
+ name: 'weekdayName',
333
+ signature: 'weekdayName(d)',
334
+ description:
335
+ "English day-of-week name such as 'Monday' (UTC); null for an invalid date.",
336
+ example: 'weekdayName(date)',
337
+ category: 'date',
338
+ minArgs: 1,
339
+ maxArgs: 1,
340
+ },
341
+ {
342
+ name: 'monthName',
343
+ signature: 'monthName(d)',
344
+ description:
345
+ "English month name such as 'January' (UTC); null for an invalid date.",
346
+ example: 'monthName(date)',
347
+ category: 'date',
348
+ minArgs: 1,
349
+ maxArgs: 1,
350
+ },
351
+ {
352
+ name: 'dateAdd',
353
+ signature: "dateAdd(d, n, 'day'|'month'|'year')",
354
+ description:
355
+ 'Adds n units (negative subtracts) and returns a YYYY-MM-DD text; month/year additions clamp to the last day of the target month; null for an invalid date or amount.',
356
+ example: "dateAdd(date, 30, 'day')",
357
+ category: 'date',
358
+ minArgs: 3,
359
+ maxArgs: 3,
360
+ },
361
+ {
362
+ name: 'dateDiff',
363
+ signature: "dateDiff(a, b, 'day'|'month'|'year')",
364
+ description:
365
+ 'Whole units from a to b as an integer (positive when b is later); null when either date is invalid.',
366
+ example: "dateDiff(orderDate, deliveryDate, 'day')",
367
+ category: 'date',
368
+ minArgs: 3,
369
+ maxArgs: 3,
370
+ },
371
+ // Logic
372
+ {
373
+ name: 'if',
374
+ signature: 'if(condition, whenTrue, whenFalse)',
375
+ description:
376
+ 'Returns whenTrue when the condition is truthy, otherwise whenFalse (null when omitted); null, false, 0, empty text and empty arrays are falsy.',
377
+ example: "if(quantity > 0, 'in stock', 'out')",
378
+ category: 'logic',
379
+ minArgs: 2,
380
+ maxArgs: 3,
381
+ },
382
+ {
383
+ name: 'isNull',
384
+ signature: 'isNull(x)',
385
+ description: 'True when the value is null or missing.',
386
+ example: 'isNull(metadata.vendor)',
387
+ category: 'logic',
388
+ minArgs: 1,
389
+ maxArgs: 1,
390
+ },
391
+ {
392
+ name: 'isEmpty',
393
+ signature: 'isEmpty(x)',
394
+ description:
395
+ 'True when the value is null, missing, empty text or an empty array.',
396
+ example: 'isEmpty(metadata.values)',
397
+ category: 'logic',
398
+ minArgs: 1,
399
+ maxArgs: 1,
400
+ },
401
+ {
402
+ name: 'eq',
403
+ signature: 'eq(a, b)',
404
+ description:
405
+ 'Case-insensitive, whitespace-trimmed text equality; two nulls are equal, a null and a value are not.',
406
+ example: "eq(status, 'paid')",
407
+ category: 'logic',
408
+ minArgs: 2,
409
+ maxArgs: 2,
410
+ },
411
+ {
412
+ name: 'between',
413
+ signature: 'between(x, low, high)',
414
+ description:
415
+ 'True when low <= x <= high numerically; false when any argument is non-numeric.',
416
+ example: 'between(temperature, 33, 41)',
417
+ category: 'logic',
418
+ minArgs: 3,
419
+ maxArgs: 3,
420
+ },
421
+ // Collection (array argument = field reference or a function returning an array)
422
+ {
423
+ name: 'lookup',
424
+ signature: 'lookup(array, matchField, matchValue, valueField)',
425
+ description:
426
+ 'valueField of the FIRST element whose matchField equals matchValue (trimmed, case-insensitive text match); null when nothing matches or the array is empty.',
427
+ example: "lookup(metadata.values, 'label', 'EBT', 'value')",
428
+ category: 'collection',
429
+ minArgs: 4,
430
+ maxArgs: 4,
431
+ },
432
+ {
433
+ name: 'sumWhere',
434
+ signature: 'sumWhere(array, matchField, matchValue, valueField)',
435
+ description:
436
+ 'Numeric sum of valueField over ALL elements whose matchField equals matchValue; 0 when nothing matches.',
437
+ example: "sumWhere(metadata.values, 'label', 'MM', 'value')",
438
+ category: 'collection',
439
+ minArgs: 4,
440
+ maxArgs: 4,
441
+ },
442
+ {
443
+ name: 'countWhere',
444
+ signature: 'countWhere(array, matchField, matchValue)',
445
+ description:
446
+ 'Number of elements whose matchField equals matchValue; 0 for an empty array.',
447
+ example: "countWhere(items, 'category', 'produce')",
448
+ category: 'collection',
449
+ minArgs: 3,
450
+ maxArgs: 3,
451
+ },
452
+ {
453
+ name: 'count',
454
+ signature: 'count(array)',
455
+ description: 'Number of elements; 0 when the value is not an array.',
456
+ example: 'count(metadata.values)',
457
+ category: 'collection',
458
+ minArgs: 1,
459
+ maxArgs: 1,
460
+ },
461
+ {
462
+ name: 'sumOf',
463
+ signature: 'sumOf(array, field)',
464
+ description:
465
+ 'Numeric sum of field across all elements (non-numeric values ignored); 0 for an empty array.',
466
+ example: "sumOf(items, 'total')",
467
+ category: 'collection',
468
+ minArgs: 2,
469
+ maxArgs: 2,
470
+ },
471
+ {
472
+ name: 'minOf',
473
+ signature: 'minOf(array, field)',
474
+ description:
475
+ 'Smallest numeric field value across the elements; null when none is numeric.',
476
+ example: "minOf(items, 'price')",
477
+ category: 'collection',
478
+ minArgs: 2,
479
+ maxArgs: 2,
480
+ },
481
+ {
482
+ name: 'maxOf',
483
+ signature: 'maxOf(array, field)',
484
+ description:
485
+ 'Largest numeric field value across the elements; null when none is numeric.',
486
+ example: "maxOf(items, 'price')",
487
+ category: 'collection',
488
+ minArgs: 2,
489
+ maxArgs: 2,
490
+ },
491
+ {
492
+ name: 'first',
493
+ signature: 'first(array, field)',
494
+ description:
495
+ 'field of the first element; null for an empty array. Pass null as field for the whole element.',
496
+ example: "first(items, 'name')",
497
+ category: 'collection',
498
+ minArgs: 2,
499
+ maxArgs: 2,
500
+ },
501
+ {
502
+ name: 'last',
503
+ signature: 'last(array, field)',
504
+ description:
505
+ 'field of the last element; null for an empty array. Pass null as field for the whole element.',
506
+ example: "last(items, 'name')",
507
+ category: 'collection',
508
+ minArgs: 2,
509
+ maxArgs: 2,
510
+ },
511
+ {
512
+ name: 'joinText',
513
+ signature: 'joinText(array, field, separator)',
514
+ description:
515
+ "Concatenates the non-empty field values with separator (default ', '); empty text for an empty array.",
516
+ example: "joinText(items, 'name', '; ')",
517
+ category: 'collection',
518
+ minArgs: 2,
519
+ maxArgs: 3,
520
+ },
521
+ {
522
+ name: 'hasAny',
523
+ signature: 'hasAny(array, matchField, matchValue)',
524
+ description:
525
+ 'True when at least one element has matchField equal to matchValue; false for an empty array.',
526
+ example: "hasAny(metadata.values, 'label', 'EBT')",
527
+ category: 'collection',
528
+ minArgs: 3,
529
+ maxArgs: 3,
530
+ },
531
+ ] as const satisfies readonly ExpressionFunctionSpec[];
532
+
533
+ export type ExpressionFunctionName =
534
+ (typeof EXPRESSION_FUNCTIONS)[number]['name'];
535
+
536
+ export const EXPRESSION_FUNCTION_NAMES: readonly ExpressionFunctionName[] =
537
+ EXPRESSION_FUNCTIONS.map((spec) => spec.name);
35
538
 
36
539
  export type ExpressionValue = string | number | boolean | null;
37
540
 
@@ -47,6 +550,25 @@ export interface CompiledExpression {
47
550
  node: ExpressionNode;
48
551
  fieldRefs: string[]; // Full dotted paths referenced by the expression
49
552
  evaluate: (row: Record<string, unknown>) => ExpressionValue;
553
+ // Same evaluation without the final scalar conversion: arrays/objects stay intact
554
+ evaluateRaw: (row: Record<string, unknown>) => unknown;
555
+ evaluatePredicate: (row: Record<string, unknown>) => boolean;
556
+ }
557
+
558
+ interface ExpressionDateParts {
559
+ year: number;
560
+ month: number; // 1-12
561
+ day: number;
562
+ hour: number;
563
+ minute: number;
564
+ second: number;
565
+ weekday: number; // 0 = Sunday
566
+ }
567
+
568
+ export interface ExpressionCollectionFieldRefs {
569
+ functionName: ExpressionFunctionName;
570
+ arrayPath: string; // Dotted path of the array field reference
571
+ elementPaths: string[]; // Element paths named by the string-literal field arguments
50
572
  }
51
573
 
52
574
  /**
@@ -61,6 +583,68 @@ export class ExpressionError extends Error {
61
583
  }
62
584
  }
63
585
 
586
+ const FILE_CONSTANTS = {
587
+ tokenPatterns: {
588
+ whitespace: /^\s+/,
589
+ number: /^\d+(\.\d+)?/,
590
+ bareSegment: /^[A-Za-z_][A-Za-z0-9_]*/,
591
+ pathSegment: /^[A-Za-z0-9_]+/,
592
+ operator: /^(!=|>=|<=|=|>|<|\+|-|\*|\/)/,
593
+ jsOperator: /^(===|!==|&&|\|\||\?\?|\?\.|\?|!(?!=)|"|`)/,
594
+ bracketForbidden: /['"=(),\n\r]/,
595
+ naiveDateTime: /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,
596
+ dateFormatToken: /YYYY|MMMM|MMM|MM|DD|dddd|ddd|HH|mm|ss/g,
597
+ },
598
+ keywords: ['and', 'or', 'not', 'true', 'false', 'null'],
599
+ jsSyntaxMessage:
600
+ 'JavaScript syntax (methods, ?., ??, ===, "double quotes") is not supported.',
601
+ bracketMessage:
602
+ 'Bracket segments name a column; use lookup(...) to read array elements.',
603
+ excerptRadius: 10,
604
+ maxSuggestions: 3,
605
+ maxResultChars: 1048576,
606
+ maxCollectionItems: 1000000,
607
+ dateUnits: ['day', 'month', 'year'],
608
+ dateUnitArgIndex: { dateAdd: 2, dateDiff: 2 } as Record<string, number>,
609
+ // Argument positions that must be string literals naming an element path
610
+ collectionFieldArgs: {
611
+ lookup: [1, 3],
612
+ sumWhere: [1, 3],
613
+ countWhere: [1],
614
+ sumOf: [1],
615
+ minOf: [1],
616
+ maxOf: [1],
617
+ first: [1],
618
+ last: [1],
619
+ joinText: [1],
620
+ hasAny: [1],
621
+ } as Record<string, number[]>,
622
+ monthNames: [
623
+ 'January',
624
+ 'February',
625
+ 'March',
626
+ 'April',
627
+ 'May',
628
+ 'June',
629
+ 'July',
630
+ 'August',
631
+ 'September',
632
+ 'October',
633
+ 'November',
634
+ 'December',
635
+ ],
636
+ dayNames: [
637
+ 'Sunday',
638
+ 'Monday',
639
+ 'Tuesday',
640
+ 'Wednesday',
641
+ 'Thursday',
642
+ 'Friday',
643
+ 'Saturday',
644
+ ],
645
+ msPerDay: 86400000,
646
+ };
647
+
64
648
  /**
65
649
  * Tokenizer
66
650
  */
@@ -79,13 +663,62 @@ interface ExpressionToken {
79
663
  path?: string[];
80
664
  }
81
665
 
82
- const TOKEN_PATTERNS = {
83
- whitespace: /^\s+/,
84
- number: /^\d+(\.\d+)?/,
85
- bareSegment: /^[A-Za-z_][A-Za-z0-9_]*/,
86
- pathSegment: /^[A-Za-z0-9_]+/,
87
- operator: /^(!=|>=|<=|=|>|<|\+|-|\*|\/)/,
88
- };
666
+ /**
667
+ * Look up a registry entry by (case-insensitive) name.
668
+ */
669
+
670
+ function findExpressionFunctionSpec(name: string) {
671
+ const lowerName = name.toLowerCase();
672
+ return EXPRESSION_FUNCTIONS.find(
673
+ (spec) => spec.name.toLowerCase() === lowerName,
674
+ );
675
+ }
676
+
677
+ /**
678
+ * Closest registered function names for an unknown name (prefix, then substring, then shared 3-char prefix).
679
+ */
680
+
681
+ function getClosestFunctionNames(name: string) {
682
+ const lowerName = name.toLowerCase();
683
+ const prefix = lowerName.slice(0, 3);
684
+
685
+ const rankName = (fnName: string) => {
686
+ const lowerFnName = fnName.toLowerCase();
687
+ if (
688
+ lowerFnName.startsWith(lowerName) ||
689
+ lowerName.startsWith(lowerFnName)
690
+ ) {
691
+ return 0;
692
+ }
693
+ if (lowerFnName.includes(lowerName) || lowerName.includes(lowerFnName)) {
694
+ return 1;
695
+ }
696
+ return prefix.length === 3 && lowerFnName.startsWith(prefix) ? 2 : null;
697
+ };
698
+
699
+ const ranked: { fnName: string; rank: number }[] = [];
700
+ for (const fnName of EXPRESSION_FUNCTION_NAMES) {
701
+ const rank = rankName(fnName);
702
+ if (rank !== null) {
703
+ ranked.push({ fnName, rank });
704
+ }
705
+ }
706
+
707
+ return ranked
708
+ .sort((a, b) => a.rank - b.rank)
709
+ .slice(0, FILE_CONSTANTS.maxSuggestions)
710
+ .map((entry) => entry.fnName);
711
+ }
712
+
713
+ /**
714
+ * A short excerpt of the input around a position, for error messages.
715
+ */
716
+
717
+ function getInputExcerpt(input: string, position: number) {
718
+ const start = Math.max(0, position - FILE_CONSTANTS.excerptRadius);
719
+ const end = Math.min(input.length, position + FILE_CONSTANTS.excerptRadius);
720
+ return `${start > 0 ? '…' : ''}${input.slice(start, end)}${end < input.length ? '…' : ''}`;
721
+ }
89
722
 
90
723
  /**
91
724
  * Read one field path starting at the given index; supports bare and [bracket] segments.
@@ -107,7 +740,12 @@ function readFieldPath(input: string, startIndex: number) {
107
740
  );
108
741
  }
109
742
 
110
- const segment = rest.slice(1, closeIndex).trim();
743
+ const rawSegment = rest.slice(1, closeIndex);
744
+ if (FILE_CONSTANTS.tokenPatterns.bracketForbidden.test(rawSegment)) {
745
+ throw new ExpressionError(FILE_CONSTANTS.bracketMessage);
746
+ }
747
+
748
+ const segment = rawSegment.trim();
111
749
  if (!segment) {
112
750
  throw new ExpressionError(
113
751
  `Empty "[]" field segment at position ${index}.`,
@@ -118,7 +756,9 @@ function readFieldPath(input: string, startIndex: number) {
118
756
  index += closeIndex + 1;
119
757
  } else {
120
758
  const segmentMatch = rest.match(
121
- first ? TOKEN_PATTERNS.bareSegment : TOKEN_PATTERNS.pathSegment,
759
+ first
760
+ ? FILE_CONSTANTS.tokenPatterns.bareSegment
761
+ : FILE_CONSTANTS.tokenPatterns.pathSegment,
122
762
  );
123
763
  if (!segmentMatch) {
124
764
  break;
@@ -141,17 +781,47 @@ function readFieldPath(input: string, startIndex: number) {
141
781
  return { path, endIndex: index };
142
782
  }
143
783
 
784
+ /**
785
+ * Read a single-quoted string literal ('' escapes a quote); returns the text and the index after the closing quote.
786
+ */
787
+
788
+ function readStringLiteral(input: string, startIndex: number) {
789
+ let text = '';
790
+ let cursor = startIndex + 1;
791
+
792
+ while (cursor < input.length) {
793
+ if (input[cursor] === "'" && input[cursor + 1] === "'") {
794
+ text += "'";
795
+ cursor += 2;
796
+ } else if (input[cursor] === "'") {
797
+ break;
798
+ } else {
799
+ text += input[cursor];
800
+ cursor += 1;
801
+ }
802
+ }
803
+
804
+ if (cursor >= input.length) {
805
+ throw new ExpressionError(
806
+ `Unclosed string starting at position ${startIndex}.`,
807
+ );
808
+ }
809
+
810
+ return { text, endIndex: cursor + 1 };
811
+ }
812
+
144
813
  /**
145
814
  * Convert an expression string into a flat token list.
146
815
  */
147
816
 
148
817
  function tokenizeExpression(input: string) {
149
818
  const tokens: ExpressionToken[] = [];
819
+ const patterns = FILE_CONSTANTS.tokenPatterns;
150
820
  let index = 0;
151
821
 
152
822
  while (index < input.length) {
153
823
  const rest = input.slice(index);
154
- const whitespaceMatch = rest.match(TOKEN_PATTERNS.whitespace);
824
+ const whitespaceMatch = rest.match(patterns.whitespace);
155
825
 
156
826
  if (whitespaceMatch) {
157
827
  index += whitespaceMatch[0].length;
@@ -177,53 +847,43 @@ function tokenizeExpression(input: string) {
177
847
  }
178
848
 
179
849
  if (rest[0] === "'") {
180
- // Single-quoted string; '' escapes a quote
181
- let text = '';
182
- let cursor = index + 1;
183
- while (cursor < input.length) {
184
- if (input[cursor] === "'" && input[cursor + 1] === "'") {
185
- text += "'";
186
- cursor += 2;
187
- } else if (input[cursor] === "'") {
188
- break;
189
- } else {
190
- text += input[cursor];
191
- cursor += 1;
192
- }
193
- }
194
-
195
- if (cursor >= input.length) {
196
- throw new ExpressionError(
197
- `Unclosed string starting at position ${index}.`,
198
- );
199
- }
200
-
850
+ const { text, endIndex } = readStringLiteral(input, index);
201
851
  tokens.push({ type: 'string', text });
202
- index = cursor + 1;
852
+ index = endIndex;
203
853
  continue;
204
854
  }
205
855
 
206
- const numberMatch = rest.match(TOKEN_PATTERNS.number);
856
+ const numberMatch = rest.match(patterns.number);
207
857
  if (numberMatch) {
208
858
  tokens.push({ type: 'number', text: numberMatch[0] });
209
859
  index += numberMatch[0].length;
210
860
  continue;
211
861
  }
212
862
 
213
- const operatorMatch = rest.match(TOKEN_PATTERNS.operator);
863
+ // JavaScript operators are checked before the DSL operators so "===" is
864
+ // reported as JS syntax instead of a dangling "=="
865
+ const jsOperatorMatch = rest.match(patterns.jsOperator);
866
+ if (jsOperatorMatch) {
867
+ throw new ExpressionError(
868
+ `Unexpected "${jsOperatorMatch[0]}" at position ${index} near "${getInputExcerpt(input, index)}". ${FILE_CONSTANTS.jsSyntaxMessage}`,
869
+ );
870
+ }
871
+
872
+ const operatorMatch = rest.match(patterns.operator);
214
873
  if (operatorMatch) {
215
874
  tokens.push({ type: 'op', text: operatorMatch[0] });
216
875
  index += operatorMatch[0].length;
217
876
  continue;
218
877
  }
219
878
 
220
- if (rest[0] === '[' || TOKEN_PATTERNS.bareSegment.test(rest)) {
879
+ if (rest[0] === '[' || patterns.bareSegment.test(rest)) {
221
880
  const { path, endIndex } = readFieldPath(input, index);
222
881
  const lowerFirst = path[0]?.toLowerCase();
223
882
 
224
883
  if (
884
+ rest[0] !== '[' &&
225
885
  path.length === 1 &&
226
- ['and', 'or', 'not', 'true', 'false', 'null'].includes(lowerFirst)
886
+ FILE_CONSTANTS.keywords.includes(lowerFirst)
227
887
  ) {
228
888
  tokens.push({ type: 'ident', text: lowerFirst });
229
889
  } else {
@@ -235,7 +895,7 @@ function tokenizeExpression(input: string) {
235
895
  }
236
896
 
237
897
  throw new ExpressionError(
238
- `Unexpected character "${rest[0]}" at position ${index}.`,
898
+ `Unexpected character "${rest[0]}" at position ${index} near "${getInputExcerpt(input, index)}".`,
239
899
  );
240
900
  }
241
901
 
@@ -447,17 +1107,18 @@ class ExpressionParser {
447
1107
  private parseCall(nameToken: ExpressionToken): ExpressionNode {
448
1108
  if ((nameToken.path || []).length > 1) {
449
1109
  throw new ExpressionError(
450
- `"${nameToken.text}" is not a valid function name.`,
1110
+ `"${nameToken.text}" is not a valid function name. ${FILE_CONSTANTS.jsSyntaxMessage}`,
451
1111
  );
452
1112
  }
453
1113
 
454
- const name = EXPRESSION_FUNCTION_NAMES.find(
455
- (fnName) => fnName.toLowerCase() === nameToken.text.toLowerCase(),
456
- );
457
-
458
- if (!name) {
1114
+ const spec = findExpressionFunctionSpec(nameToken.text);
1115
+ if (!spec) {
1116
+ const suggestions = getClosestFunctionNames(nameToken.text);
1117
+ const didYouMean = suggestions.length
1118
+ ? ` Did you mean ${suggestions.join(', ')}?`
1119
+ : '';
459
1120
  throw new ExpressionError(
460
- `Unknown function "${nameToken.text}". Available functions: ${EXPRESSION_FUNCTION_NAMES.join(', ')}.`,
1121
+ `Unknown function "${nameToken.text}".${didYouMean} Available functions: ${EXPRESSION_FUNCTION_NAMES.join(', ')}. ${FILE_CONSTANTS.jsSyntaxMessage}`,
461
1122
  );
462
1123
  }
463
1124
 
@@ -475,11 +1136,76 @@ class ExpressionParser {
475
1136
 
476
1137
  const closer = this.next();
477
1138
  if (!closer || closer.type !== 'rparen') {
478
- throw new ExpressionError(`Missing closing ")" for function "${name}".`);
1139
+ throw new ExpressionError(
1140
+ `Missing closing ")" for function "${spec.name}".`,
1141
+ );
479
1142
  }
480
1143
 
481
1144
  this.exit();
482
- return { kind: 'call', name, args };
1145
+ validateCallArguments(spec, args);
1146
+ return { kind: 'call', name: spec.name, args };
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * Static checks on a parsed call: arity, collection array/field argument shapes and date unit literals.
1152
+ */
1153
+
1154
+ function validateCallArguments(
1155
+ spec: ExpressionFunctionSpec,
1156
+ args: ExpressionNode[],
1157
+ ) {
1158
+ if (
1159
+ args.length < spec.minArgs ||
1160
+ (spec.maxArgs !== null && args.length > spec.maxArgs)
1161
+ ) {
1162
+ const expected =
1163
+ spec.maxArgs === null
1164
+ ? `at least ${spec.minArgs}`
1165
+ : spec.minArgs === spec.maxArgs
1166
+ ? `${spec.minArgs}`
1167
+ : `${spec.minArgs} to ${spec.maxArgs}`;
1168
+ throw new ExpressionError(
1169
+ `Function "${spec.name}" expects ${expected} argument(s) but received ${args.length}. Usage: ${spec.signature}.`,
1170
+ );
1171
+ }
1172
+
1173
+ if (spec.category === 'collection') {
1174
+ if (args[0].kind !== 'field' && args[0].kind !== 'call') {
1175
+ throw new ExpressionError(
1176
+ `The first argument of "${spec.name}" must be a field reference to an array (for example metadata.values) or a function returning one. Usage: ${spec.signature}.`,
1177
+ );
1178
+ }
1179
+
1180
+ for (const argIndex of FILE_CONSTANTS.collectionFieldArgs[spec.name] ||
1181
+ []) {
1182
+ const arg = args[argIndex];
1183
+ const isNullLiteral = arg?.kind === 'literal' && arg.value === null;
1184
+ const allowsNull = spec.name === 'first' || spec.name === 'last';
1185
+ if (
1186
+ arg &&
1187
+ !(arg.kind === 'literal' && typeof arg.value === 'string') &&
1188
+ !(isNullLiteral && allowsNull)
1189
+ ) {
1190
+ throw new ExpressionError(
1191
+ `Argument ${argIndex + 1} of "${spec.name}" must be a quoted element field name such as 'label'. Usage: ${spec.signature}.`,
1192
+ );
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ const unitArgIndex = FILE_CONSTANTS.dateUnitArgIndex[spec.name];
1198
+ if (unitArgIndex !== undefined) {
1199
+ const unitArg = args[unitArgIndex];
1200
+ if (
1201
+ unitArg.kind === 'literal' &&
1202
+ (typeof unitArg.value !== 'string' ||
1203
+ normalizeDateUnit(unitArg.value) === null)
1204
+ ) {
1205
+ throw new ExpressionError(
1206
+ `The unit of "${spec.name}" must be 'day', 'month' or 'year'. Usage: ${spec.signature}.`,
1207
+ );
1208
+ }
483
1209
  }
484
1210
  }
485
1211
 
@@ -491,7 +1217,7 @@ class ExpressionParser {
491
1217
  * Read a nested value from a row by path segments.
492
1218
  */
493
1219
 
494
- function getRowValueAtPath(row: Record<string, unknown>, path: string[]) {
1220
+ function getRowValueAtPath(row: unknown, path: string[]) {
495
1221
  return path.reduce<unknown>((acc, pathPart) => {
496
1222
  if (Array.isArray(acc)) {
497
1223
  const indexValue = Number(pathPart);
@@ -507,43 +1233,27 @@ function getRowValueAtPath(row: Record<string, unknown>, path: string[]) {
507
1233
  }
508
1234
 
509
1235
  /**
510
- * Convert a value into a finite number, tolerating units/currency/comma noise.
1236
+ * Convert a complete decimal amount into a finite number, accepting known units,
1237
+ * currencies and valid thousands grouping.
511
1238
  */
512
1239
 
513
1240
  export function toExpressionNumber(value: unknown): number | null {
514
- if (typeof value === 'number') {
515
- return Number.isFinite(value) ? value : null;
516
- }
517
-
518
- if (typeof value === 'boolean') {
519
- return value ? 1 : 0;
520
- }
521
-
522
- if (typeof value === 'string') {
523
- const trimmed = value.trim();
524
- if (!trimmed) {
525
- return null;
526
- }
527
-
528
- // Direct parse first (handles "12", "3.5", "1e3"), then strip common
529
- // unit/currency/grouping noise like "$1,200.50", "12 lbs", "45%"
530
- const directValue = Number(trimmed);
531
- if (Number.isFinite(directValue)) {
532
- return directValue;
533
- }
1241
+ return parseDecoratedExpressionNumber(value);
1242
+ }
534
1243
 
535
- const strippedMatch = trimmed.replace(/,/g, '').match(/-?\d+(\.\d+)?/);
536
- if (strippedMatch) {
537
- const parsedValue = Number(strippedMatch[0]);
538
- return Number.isFinite(parsedValue) ? parsedValue : null;
539
- }
540
- }
1244
+ /**
1245
+ * Convert a value into a finite number ONLY when it is a plain number (12, '3.5', ' 1e3 ').
1246
+ * Used for comparisons and distinct counting, where the lenient parser would read the
1247
+ * first digit run of dates ('2026-08-01' -> 2026), times ('10:59' -> 10) and prefixed ids
1248
+ * ('org-12' -> 12) and make unrelated values compare equal.
1249
+ */
541
1250
 
542
- return null;
1251
+ export function toStrictExpressionNumber(value: unknown): number | null {
1252
+ return parsePlainExpressionNumber(value);
543
1253
  }
544
1254
 
545
1255
  /**
546
- * Truthiness for and/or/not/if: null, undefined, false, 0, NaN, and '' are false.
1256
+ * Truthiness for and/or/not/if: null, undefined, false, 0, NaN, '' and empty arrays are false.
547
1257
  */
548
1258
 
549
1259
  function toExpressionBool(value: unknown) {
@@ -553,7 +1263,21 @@ function toExpressionBool(value: unknown) {
553
1263
  value === false ||
554
1264
  value === 0 ||
555
1265
  value === '' ||
556
- (typeof value === 'number' && Number.isNaN(value))
1266
+ (typeof value === 'number' && Number.isNaN(value)) ||
1267
+ (Array.isArray(value) && value.length === 0)
1268
+ );
1269
+ }
1270
+
1271
+ /**
1272
+ * Empty check shared by coalesce/isEmpty: null, undefined, '' and empty arrays are empty.
1273
+ */
1274
+
1275
+ function isEmptyValue(value: unknown) {
1276
+ return (
1277
+ value === null ||
1278
+ value === undefined ||
1279
+ value === '' ||
1280
+ (Array.isArray(value) && value.length === 0)
557
1281
  );
558
1282
  }
559
1283
 
@@ -571,7 +1295,7 @@ function toScalar(value: unknown): ExpressionValue {
571
1295
  typeof value === 'string' ||
572
1296
  typeof value === 'boolean'
573
1297
  ) {
574
- return value;
1298
+ return assertExpressionResult(value);
575
1299
  }
576
1300
 
577
1301
  if (value instanceof Date) {
@@ -579,142 +1303,735 @@ function toScalar(value: unknown): ExpressionValue {
579
1303
  }
580
1304
 
581
1305
  // Objects/arrays flatten to JSON so nothing silently disappears
1306
+ let serialized: string;
582
1307
  try {
583
- return JSON.stringify(value);
1308
+ serialized = JSON.stringify(value);
584
1309
  } catch {
585
- return String(value);
1310
+ throw new ExpressionError('Expression value cannot be serialized.');
1311
+ }
1312
+ return assertExpressionResult(serialized);
1313
+ }
1314
+
1315
+ /*
1316
+ * Reject non-finite or oversized scalar results before another expression uses them.
1317
+ */
1318
+ function assertExpressionResult<T>(value: T): T {
1319
+ if (typeof value === 'number' && !Number.isFinite(value)) {
1320
+ throw new ExpressionError('Expression produced a non-finite number.');
1321
+ }
1322
+ if (
1323
+ typeof value === 'string' &&
1324
+ value.length > FILE_CONSTANTS.maxResultChars
1325
+ ) {
1326
+ throw new ExpressionError(
1327
+ `Expression text exceeds ${FILE_CONSTANTS.maxResultChars} characters.`,
1328
+ );
1329
+ }
1330
+ return value;
1331
+ }
1332
+
1333
+ /*
1334
+ * Join text only after its total size is known to fit the per-cell budget.
1335
+ */
1336
+ function joinExpressionText(parts: string[], separator = '') {
1337
+ const length =
1338
+ parts.reduce((size, part) => size + part.length, 0) +
1339
+ Math.max(0, parts.length - 1) * separator.length;
1340
+ if (length > FILE_CONSTANTS.maxResultChars) {
1341
+ throw new ExpressionError(
1342
+ `Expression text exceeds ${FILE_CONSTANTS.maxResultChars} characters.`,
1343
+ );
586
1344
  }
1345
+ return parts.join(separator);
587
1346
  }
588
1347
 
589
1348
  /**
590
- * Compare two scalars: numeric when both parse as numbers, string otherwise.
1349
+ * Scalar text of a value, or null when the value is null/missing.
1350
+ */
1351
+
1352
+ function toNullableText(value: unknown): string | null {
1353
+ const scalar = toScalar(value);
1354
+ return scalar === null ? null : String(scalar);
1355
+ }
1356
+
1357
+ /**
1358
+ * Compare two scalars: numeric when both are plain numbers, text otherwise (so ISO
1359
+ * dates, HH:mm times and prefixed ids order correctly as text).
591
1360
  */
592
1361
 
593
1362
  function compareScalars(a: ExpressionValue, b: ExpressionValue) {
594
- const aNumber = toExpressionNumber(a);
595
- const bNumber = toExpressionNumber(b);
1363
+ return compareExpressionValues(a, b);
1364
+ }
1365
+
1366
+ /**
1367
+ * Loose equality used by eq() and collection matching: trimmed, case-insensitive text; two nulls are equal.
1368
+ */
596
1369
 
597
- if (aNumber !== null && bNumber !== null) {
598
- return aNumber - bNumber;
1370
+ function looselyEquals(a: unknown, b: unknown) {
1371
+ const aText = toNullableText(a);
1372
+ const bText = toNullableText(b);
1373
+
1374
+ if (aText === null || bText === null) {
1375
+ return aText === bText;
599
1376
  }
600
1377
 
601
- return String(a ?? '').localeCompare(String(b ?? ''));
1378
+ return aText.trim().toLowerCase() === bText.trim().toLowerCase();
1379
+ }
1380
+
1381
+ /**
1382
+ * Parse a date-like value (Date, ISO string or YYYY-MM-DD) as a UTC moment; naive date-times are read as UTC.
1383
+ */
1384
+
1385
+ function parseDateValue(value: unknown): Date | null {
1386
+ return parseExpressionDate(value);
1387
+ }
1388
+
1389
+ /**
1390
+ * Normalize a unit argument ('day', 'days', 'MONTH', ...) to day|month|year, or null when unknown.
1391
+ */
1392
+
1393
+ function normalizeDateUnit(value: unknown): 'day' | 'month' | 'year' | null {
1394
+ const unit = String(value ?? '')
1395
+ .trim()
1396
+ .toLowerCase()
1397
+ .replace(/s$/, '');
1398
+ return FILE_CONSTANTS.dateUnits.includes(unit)
1399
+ ? (unit as 'day' | 'month' | 'year')
1400
+ : null;
1401
+ }
1402
+
1403
+ /**
1404
+ * Format a date as YYYY-MM-DD in UTC.
1405
+ */
1406
+
1407
+ function toISODateText(date: Date) {
1408
+ if (
1409
+ !Number.isFinite(date.getTime()) ||
1410
+ date.getUTCFullYear() < 0 ||
1411
+ date.getUTCFullYear() > 9999
1412
+ ) {
1413
+ return null;
1414
+ }
1415
+ const year = String(date.getUTCFullYear()).padStart(4, '0');
1416
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
1417
+ const day = String(date.getUTCDate()).padStart(2, '0');
1418
+ return `${year}-${month}-${day}`;
602
1419
  }
603
1420
 
604
1421
  /**
605
- * Format a date-like value with YYYY/MM/DD tokens (UTC-based so date-only strings never shift).
1422
+ * Split a moment into calendar parts, in UTC (no or UTC zone) or in an IANA time zone; null when the zone is unknown.
606
1423
  */
607
1424
 
608
- function formatDateValue(value: unknown, format: unknown) {
609
- const valueText =
610
- value instanceof Date ? value.toISOString() : String(value ?? '').trim();
611
- if (!valueText) {
1425
+ function getDateParts(
1426
+ date: Date,
1427
+ timeZone: unknown,
1428
+ ): ExpressionDateParts | null {
1429
+ const zone = String(timeZone ?? '').trim();
1430
+ if (!zone || zone.toUpperCase() === 'UTC') {
1431
+ return {
1432
+ year: date.getUTCFullYear(),
1433
+ month: date.getUTCMonth() + 1,
1434
+ day: date.getUTCDate(),
1435
+ hour: date.getUTCHours(),
1436
+ minute: date.getUTCMinutes(),
1437
+ second: date.getUTCSeconds(),
1438
+ weekday: date.getUTCDay(),
1439
+ };
1440
+ }
1441
+
1442
+ let formatter: Intl.DateTimeFormat;
1443
+ try {
1444
+ formatter = new Intl.DateTimeFormat('en-US', {
1445
+ timeZone: zone,
1446
+ hourCycle: 'h23',
1447
+ year: 'numeric',
1448
+ month: 'numeric',
1449
+ day: 'numeric',
1450
+ hour: 'numeric',
1451
+ minute: 'numeric',
1452
+ second: 'numeric',
1453
+ weekday: 'short',
1454
+ });
1455
+ } catch {
1456
+ // Intl rejects unknown IANA names with a RangeError
612
1457
  return null;
613
1458
  }
614
1459
 
615
- // Date-only strings parse as UTC midnight; full ISO strings keep their moment
616
- const parsedDate = new Date(valueText);
617
- if (Number.isNaN(parsedDate.getTime())) {
1460
+ const parts: Record<string, string> = {};
1461
+ for (const part of formatter.formatToParts(date)) {
1462
+ parts[part.type] = part.value;
1463
+ }
1464
+
1465
+ return {
1466
+ year: Number(parts.year),
1467
+ month: Number(parts.month),
1468
+ day: Number(parts.day),
1469
+ hour: Number(parts.hour) % 24,
1470
+ minute: Number(parts.minute),
1471
+ second: Number(parts.second),
1472
+ weekday: FILE_CONSTANTS.dayNames.findIndex((name) =>
1473
+ name.startsWith(parts.weekday),
1474
+ ),
1475
+ };
1476
+ }
1477
+
1478
+ /**
1479
+ * Format a date-like value with YYYY/MM/DD/HH/mm/ss/MMM/MMMM/ddd/dddd tokens, in UTC or in the given IANA time zone.
1480
+ */
1481
+
1482
+ function formatDateValue(value: unknown, format: unknown, timeZone?: unknown) {
1483
+ const parsedDate = parseDateValue(value);
1484
+ const parts = parsedDate ? getDateParts(parsedDate, timeZone) : null;
1485
+ if (!parts) {
618
1486
  return null;
619
1487
  }
620
1488
 
621
- const year = String(parsedDate.getUTCFullYear()).padStart(4, '0');
622
- const month = String(parsedDate.getUTCMonth() + 1).padStart(2, '0');
623
- const day = String(parsedDate.getUTCDate()).padStart(2, '0');
1489
+ const monthName = FILE_CONSTANTS.monthNames[parts.month - 1];
1490
+ const dayName = FILE_CONSTANTS.dayNames[parts.weekday];
1491
+ const pad = (n: number, width = 2) => String(n).padStart(width, '0');
1492
+
1493
+ // Single pass so substituted names (e.g. "December") are never re-tokenized
1494
+ return String(format ?? 'YYYY-MM-DD').replace(
1495
+ FILE_CONSTANTS.tokenPatterns.dateFormatToken,
1496
+ (token) => {
1497
+ switch (token) {
1498
+ case 'YYYY':
1499
+ return pad(parts.year, 4);
1500
+ case 'MMMM':
1501
+ return monthName;
1502
+ case 'MMM':
1503
+ return monthName.slice(0, 3);
1504
+ case 'MM':
1505
+ return pad(parts.month);
1506
+ case 'DD':
1507
+ return pad(parts.day);
1508
+ case 'dddd':
1509
+ return dayName;
1510
+ case 'ddd':
1511
+ return dayName.slice(0, 3);
1512
+ case 'HH':
1513
+ return pad(parts.hour);
1514
+ case 'mm':
1515
+ return pad(parts.minute);
1516
+ case 'ss':
1517
+ return pad(parts.second);
1518
+ default:
1519
+ return token;
1520
+ }
1521
+ },
1522
+ );
1523
+ }
1524
+
1525
+ /**
1526
+ * Add whole day/month/year units to a UTC date; month/year additions clamp to the target month's last day.
1527
+ */
1528
+
1529
+ function addDateUnits(
1530
+ date: Date,
1531
+ amount: number,
1532
+ unit: 'day' | 'month' | 'year',
1533
+ ) {
1534
+ const result = new Date(date.getTime());
1535
+
1536
+ if (unit === 'day') {
1537
+ result.setUTCDate(result.getUTCDate() + amount);
1538
+ return result;
1539
+ }
1540
+
1541
+ const dayOfMonth = result.getUTCDate();
1542
+ result.setUTCDate(1);
1543
+ result.setUTCMonth(
1544
+ result.getUTCMonth() + (unit === 'month' ? amount : amount * 12),
1545
+ );
1546
+
1547
+ const lastDayOfMonth = new Date(
1548
+ Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0),
1549
+ ).getUTCDate();
1550
+ result.setUTCDate(Math.min(dayOfMonth, lastDayOfMonth));
1551
+ return result;
1552
+ }
1553
+
1554
+ /**
1555
+ * Whole calendar units from a to b (positive when b is later).
1556
+ */
1557
+
1558
+ function diffDateUnits(a: Date, b: Date, unit: 'day' | 'month' | 'year') {
1559
+ if (unit === 'day') {
1560
+ const aDay = Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate());
1561
+ const bDay = Date.UTC(b.getUTCFullYear(), b.getUTCMonth(), b.getUTCDate());
1562
+ return Math.round((bDay - aDay) / FILE_CONSTANTS.msPerDay);
1563
+ }
1564
+
1565
+ let months =
1566
+ (b.getUTCFullYear() - a.getUTCFullYear()) * 12 +
1567
+ (b.getUTCMonth() - a.getUTCMonth());
1568
+
1569
+ // Drop the partial month when the day-of-month has not been reached yet
1570
+ if (months > 0 && b.getUTCDate() < a.getUTCDate()) {
1571
+ months -= 1;
1572
+ } else if (months < 0 && b.getUTCDate() > a.getUTCDate()) {
1573
+ months += 1;
1574
+ }
624
1575
 
625
- return String(format ?? 'YYYY-MM-DD')
626
- .replace(/YYYY/g, year)
627
- .replace(/MM/g, month)
628
- .replace(/DD/g, day);
1576
+ return unit === 'month' ? months : Math.trunc(months / 12);
629
1577
  }
630
1578
 
631
1579
  /**
632
- * Evaluate one whitelisted function call.
1580
+ * Coerce a collection argument: arrays pass through, anything else is an empty array.
633
1581
  */
634
1582
 
635
- function evaluateFunction(
1583
+ function toElementArray(value: unknown): unknown[] {
1584
+ if (
1585
+ Array.isArray(value) &&
1586
+ value.length > FILE_CONSTANTS.maxCollectionItems
1587
+ ) {
1588
+ throw new ExpressionError('Collection exceeds the expression work limit.');
1589
+ }
1590
+ return Array.isArray(value) ? value : [];
1591
+ }
1592
+
1593
+ /**
1594
+ * Read an element field by dotted path; an empty/null field yields the element itself.
1595
+ * A key that literally contains a dot ('Qty.') wins over the dotted-path walk.
1596
+ */
1597
+
1598
+ function getElementField(element: unknown, field: unknown) {
1599
+ const fieldText = toNullableText(field);
1600
+ if (fieldText === null || fieldText.trim() === '') {
1601
+ return element;
1602
+ }
1603
+
1604
+ if (
1605
+ element &&
1606
+ typeof element === 'object' &&
1607
+ !Array.isArray(element) &&
1608
+ Object.prototype.hasOwnProperty.call(element, fieldText)
1609
+ ) {
1610
+ return (element as Record<string, unknown>)[fieldText];
1611
+ }
1612
+
1613
+ return getRowValueAtPath(element, fieldText.split('.'));
1614
+ }
1615
+
1616
+ /**
1617
+ * Elements whose matchField loosely equals matchValue.
1618
+ */
1619
+
1620
+ function filterElements(
1621
+ array: unknown[],
1622
+ matchField: unknown,
1623
+ matchValue: unknown,
1624
+ ) {
1625
+ return array.filter((element) =>
1626
+ looselyEquals(getElementField(element, matchField), matchValue),
1627
+ );
1628
+ }
1629
+
1630
+ /**
1631
+ * Numeric values of a field across elements (non-numeric skipped).
1632
+ */
1633
+
1634
+ function getElementNumbers(array: unknown[], field: unknown) {
1635
+ return array
1636
+ .map((element) =>
1637
+ toExpressionNumber(toScalar(getElementField(element, field))),
1638
+ )
1639
+ .filter((n): n is number => n !== null);
1640
+ }
1641
+
1642
+ /**
1643
+ * Sum of a number list (0 when empty).
1644
+ */
1645
+
1646
+ function sumNumbers(numbers: number[]) {
1647
+ return sumExpressionNumbers(numbers);
1648
+ }
1649
+
1650
+ /**
1651
+ * Evaluate a text-category function on raw arguments.
1652
+ */
1653
+
1654
+ function evaluateTextFunction(
636
1655
  name: ExpressionFunctionName,
637
- args: ExpressionValue[],
638
- ): ExpressionValue {
1656
+ args: unknown[],
1657
+ ): unknown {
1658
+ const text = toNullableText(args[0]);
1659
+
639
1660
  switch (name) {
640
1661
  case 'concat':
641
- return args.map((arg) => String(arg ?? '')).join('');
1662
+ return joinExpressionText(args.map((arg) => String(toScalar(arg) ?? '')));
642
1663
  case 'coalesce':
643
- return (
644
- args.find((arg) => arg !== null && arg !== undefined && arg !== '') ??
645
- null
646
- );
647
- case 'num':
648
- return toExpressionNumber(args[0]);
649
- case 'round': {
650
- const numberValue = toExpressionNumber(args[0]);
651
- if (numberValue === null) {
652
- return null;
653
- }
654
-
655
- const digits = Math.max(0, Math.min(8, toExpressionNumber(args[1]) ?? 0));
656
- const factor = Math.pow(10, digits);
657
- return Math.round(numberValue * factor) / factor;
658
- }
659
- case 'abs': {
660
- const numberValue = toExpressionNumber(args[0]);
661
- return numberValue === null ? null : Math.abs(numberValue);
662
- }
1664
+ return args.find((arg) => !isEmptyValue(arg)) ?? null;
663
1665
  case 'upper':
664
- return args[0] === null || args[0] === undefined
665
- ? null
666
- : String(args[0]).toUpperCase();
1666
+ return text === null ? null : text.toUpperCase();
667
1667
  case 'lower':
668
- return args[0] === null || args[0] === undefined
669
- ? null
670
- : String(args[0]).toLowerCase();
1668
+ return text === null ? null : text.toLowerCase();
671
1669
  case 'trim':
672
- return args[0] === null || args[0] === undefined
673
- ? null
674
- : String(args[0]).trim();
1670
+ return text === null ? null : text.trim();
675
1671
  case 'substr': {
676
- if (args[0] === null || args[0] === undefined) {
1672
+ if (text === null) {
677
1673
  return null;
678
1674
  }
679
1675
 
680
- const text = String(args[0]);
681
- const start = Math.max(0, toExpressionNumber(args[1]) ?? 0);
682
- const length = toExpressionNumber(args[2]);
1676
+ const start = Math.max(0, toExpressionNumber(toScalar(args[1])) ?? 0);
1677
+ const length = toExpressionNumber(toScalar(args[2]));
683
1678
  return length === null
684
1679
  ? text.slice(start)
685
1680
  : text.slice(start, start + Math.max(0, length));
686
1681
  }
1682
+ case 'replace': {
1683
+ if (text === null) {
1684
+ return null;
1685
+ }
1686
+
1687
+ const find = String(toScalar(args[1]) ?? '');
1688
+ return find === ''
1689
+ ? text
1690
+ : joinExpressionText(text.split(find), String(toScalar(args[2]) ?? ''));
1691
+ }
1692
+ case 'len':
1693
+ return text === null ? null : text.length;
1694
+ case 'startsWith':
1695
+ return text === null
1696
+ ? false
1697
+ : text
1698
+ .toLowerCase()
1699
+ .startsWith(String(toScalar(args[1]) ?? '').toLowerCase());
1700
+ case 'endsWith':
1701
+ return text === null
1702
+ ? false
1703
+ : text
1704
+ .toLowerCase()
1705
+ .endsWith(String(toScalar(args[1]) ?? '').toLowerCase());
1706
+ case 'padStart': {
1707
+ if (text === null) {
1708
+ return null;
1709
+ }
1710
+
1711
+ const length = Math.max(0, toExpressionNumber(toScalar(args[1])) ?? 0);
1712
+ if (length > FILE_CONSTANTS.maxResultChars) {
1713
+ throw new ExpressionError(
1714
+ `Expression text exceeds ${FILE_CONSTANTS.maxResultChars} characters.`,
1715
+ );
1716
+ }
1717
+ const fill = toNullableText(args[2]);
1718
+ return text.padStart(length, fill === null || fill === '' ? ' ' : fill);
1719
+ }
1720
+ case 'left': {
1721
+ if (text === null) {
1722
+ return null;
1723
+ }
1724
+ return text.slice(
1725
+ 0,
1726
+ Math.max(0, toExpressionNumber(toScalar(args[1])) ?? 0),
1727
+ );
1728
+ }
1729
+ case 'right': {
1730
+ if (text === null) {
1731
+ return null;
1732
+ }
1733
+
1734
+ const n = Math.max(0, toExpressionNumber(toScalar(args[1])) ?? 0);
1735
+ return n === 0 ? '' : text.slice(-n);
1736
+ }
1737
+ case 'split': {
1738
+ const separator = toNullableText(args[1]);
1739
+ const index = toExpressionNumber(toScalar(args[2]));
1740
+ if (text === null || separator === null || index === null) {
1741
+ return null;
1742
+ }
1743
+
1744
+ const parts = text.split(separator);
1745
+ const partIndex = Math.trunc(index);
1746
+ return partIndex >= 0 && partIndex < parts.length
1747
+ ? parts[partIndex]
1748
+ : null;
1749
+ }
1750
+ case 'contains':
1751
+ return text === null
1752
+ ? false
1753
+ : text
1754
+ .toLowerCase()
1755
+ .includes(String(toScalar(args[1]) ?? '').toLowerCase());
1756
+ default:
1757
+ throw new ExpressionError(`Unknown function "${name}".`);
1758
+ }
1759
+ }
1760
+
1761
+ /**
1762
+ * Evaluate a number-category function on raw arguments.
1763
+ */
1764
+
1765
+ function evaluateNumberFunction(
1766
+ name: ExpressionFunctionName,
1767
+ args: unknown[],
1768
+ ): unknown {
1769
+ const numbers = args.map((arg) => toExpressionNumber(toScalar(arg)));
1770
+ const first = numbers[0] ?? null;
1771
+
1772
+ switch (name) {
1773
+ case 'num':
1774
+ return first;
1775
+ case 'round': {
1776
+ if (first === null) {
1777
+ return null;
1778
+ }
1779
+
1780
+ return roundExpressionDecimal(first, numbers[1] ?? 0);
1781
+ }
1782
+ case 'abs':
1783
+ return first === null ? null : Math.abs(first);
1784
+ case 'min':
1785
+ case 'max': {
1786
+ const present = numbers.filter((n): n is number => n !== null);
1787
+ if (!present.length) {
1788
+ return null;
1789
+ }
1790
+ return present.reduce((best, value) =>
1791
+ name === 'min' ? Math.min(best, value) : Math.max(best, value),
1792
+ );
1793
+ }
1794
+ case 'floor':
1795
+ return first === null ? null : Math.floor(first);
1796
+ case 'ceil':
1797
+ return first === null ? null : Math.ceil(first);
1798
+ case 'mod': {
1799
+ const divisor = numbers[1] ?? null;
1800
+ return first === null || divisor === null || divisor === 0
1801
+ ? null
1802
+ : first % divisor;
1803
+ }
1804
+ default:
1805
+ throw new ExpressionError(`Unknown function "${name}".`);
1806
+ }
1807
+ }
1808
+
1809
+ /**
1810
+ * Evaluate a date-category function on raw arguments (UTC).
1811
+ */
1812
+
1813
+ function evaluateDateFunction(
1814
+ name: ExpressionFunctionName,
1815
+ args: unknown[],
1816
+ ): unknown {
1817
+ const date = parseDateValue(toScalar(args[0]));
1818
+
1819
+ switch (name) {
687
1820
  case 'dateFormat':
688
- return formatDateValue(args[0], args[1]);
1821
+ return formatDateValue(
1822
+ toScalar(args[0]),
1823
+ toScalar(args[1]),
1824
+ toScalar(args[2]),
1825
+ );
1826
+ case 'year':
1827
+ return date ? date.getUTCFullYear() : null;
1828
+ case 'month':
1829
+ return date ? date.getUTCMonth() + 1 : null;
1830
+ case 'day':
1831
+ return date ? date.getUTCDate() : null;
1832
+ case 'weekday':
1833
+ return date ? date.getUTCDay() : null;
1834
+ case 'weekdayName':
1835
+ return date ? FILE_CONSTANTS.dayNames[date.getUTCDay()] : null;
1836
+ case 'monthName':
1837
+ return date ? FILE_CONSTANTS.monthNames[date.getUTCMonth()] : null;
1838
+ case 'dateAdd': {
1839
+ const amount = toExpressionNumber(toScalar(args[1]));
1840
+ const unit = normalizeDateUnit(toScalar(args[2]));
1841
+ if (!date || amount === null || !unit) {
1842
+ return null;
1843
+ }
1844
+ return toISODateText(addDateUnits(date, Math.trunc(amount), unit));
1845
+ }
1846
+ case 'dateDiff': {
1847
+ const other = parseDateValue(toScalar(args[1]));
1848
+ const unit = normalizeDateUnit(toScalar(args[2]));
1849
+ if (!date || !other || !unit) {
1850
+ return null;
1851
+ }
1852
+ return diffDateUnits(date, other, unit);
1853
+ }
1854
+ default:
1855
+ throw new ExpressionError(`Unknown function "${name}".`);
1856
+ }
1857
+ }
1858
+
1859
+ /**
1860
+ * Evaluate a logic-category function on raw arguments.
1861
+ */
1862
+
1863
+ function evaluateLogicFunction(
1864
+ name: ExpressionFunctionName,
1865
+ args: unknown[],
1866
+ ): unknown {
1867
+ switch (name) {
689
1868
  case 'if':
690
1869
  return toExpressionBool(args[0]) ? (args[1] ?? null) : (args[2] ?? null);
691
- case 'contains': {
692
- if (args[0] === null || args[0] === undefined) {
693
- return false;
694
- }
1870
+ case 'isNull':
1871
+ return args[0] === null || args[0] === undefined;
1872
+ case 'isEmpty':
1873
+ return isEmptyValue(args[0]);
1874
+ case 'eq':
1875
+ return looselyEquals(args[0], args[1]);
1876
+ case 'between': {
1877
+ const [x, low, high] = args.map((arg) =>
1878
+ toExpressionNumber(toScalar(arg)),
1879
+ );
1880
+ return (
1881
+ x !== null && low !== null && high !== null && x >= low && x <= high
1882
+ );
1883
+ }
1884
+ default:
1885
+ throw new ExpressionError(`Unknown function "${name}".`);
1886
+ }
1887
+ }
1888
+
1889
+ /**
1890
+ * Evaluate a collection-category function; the first argument is the raw array.
1891
+ */
695
1892
 
696
- return String(args[0])
697
- .toLowerCase()
698
- .includes(String(args[1] ?? '').toLowerCase());
1893
+ function evaluateCollectionFunction(
1894
+ name: ExpressionFunctionName,
1895
+ args: unknown[],
1896
+ ): unknown {
1897
+ const array = toElementArray(args[0]);
1898
+
1899
+ switch (name) {
1900
+ case 'lookup': {
1901
+ const match = filterElements(array, args[1], args[2])[0];
1902
+ return match === undefined
1903
+ ? null
1904
+ : (getElementField(match, args[3]) ?? null);
699
1905
  }
1906
+ case 'sumWhere':
1907
+ return sumNumbers(
1908
+ getElementNumbers(filterElements(array, args[1], args[2]), args[3]),
1909
+ );
1910
+ case 'countWhere':
1911
+ return filterElements(array, args[1], args[2]).length;
1912
+ case 'count':
1913
+ return array.length;
1914
+ case 'sumOf':
1915
+ return sumNumbers(getElementNumbers(array, args[1]));
1916
+ case 'minOf':
1917
+ case 'maxOf': {
1918
+ const numbers = getElementNumbers(array, args[1]);
1919
+ if (!numbers.length) {
1920
+ return null;
1921
+ }
1922
+ return numbers.reduce((best, value) =>
1923
+ name === 'minOf' ? Math.min(best, value) : Math.max(best, value),
1924
+ );
1925
+ }
1926
+ case 'first':
1927
+ case 'last': {
1928
+ if (!array.length) {
1929
+ return null;
1930
+ }
1931
+ const element = name === 'first' ? array[0] : array[array.length - 1];
1932
+ return getElementField(element, args[1]) ?? null;
1933
+ }
1934
+ case 'joinText': {
1935
+ const separator = toNullableText(args[2]) ?? ', ';
1936
+ return joinExpressionText(
1937
+ array
1938
+ .map((element) => toNullableText(getElementField(element, args[1])))
1939
+ .filter((value): value is string => value !== null && value !== ''),
1940
+ separator,
1941
+ );
1942
+ }
1943
+ case 'hasAny':
1944
+ return filterElements(array, args[1], args[2]).length > 0;
700
1945
  default:
701
1946
  throw new ExpressionError(`Unknown function "${name}".`);
702
1947
  }
703
1948
  }
704
1949
 
705
1950
  /**
706
- * Evaluate one AST node against a row.
1951
+ * Evaluate one whitelisted function call on raw (unconverted) argument values.
707
1952
  */
708
1953
 
709
- function evaluateNode(
1954
+ function evaluateFunction(
1955
+ name: ExpressionFunctionName,
1956
+ args: unknown[],
1957
+ ): unknown {
1958
+ const spec = findExpressionFunctionSpec(name);
1959
+
1960
+ switch (spec?.category) {
1961
+ case 'text':
1962
+ return evaluateTextFunction(name, args);
1963
+ case 'number':
1964
+ return evaluateNumberFunction(name, args);
1965
+ case 'date':
1966
+ return evaluateDateFunction(name, args);
1967
+ case 'logic':
1968
+ return evaluateLogicFunction(name, args);
1969
+ case 'collection':
1970
+ return evaluateCollectionFunction(name, args);
1971
+ default:
1972
+ throw new ExpressionError(`Unknown function "${name}".`);
1973
+ }
1974
+ }
1975
+
1976
+ /**
1977
+ * Evaluate a binary operator on two scalars.
1978
+ */
1979
+
1980
+ function evaluateBinaryOperator(
1981
+ op: string,
1982
+ left: ExpressionValue,
1983
+ right: ExpressionValue,
1984
+ ): ExpressionValue {
1985
+ switch (op) {
1986
+ case '+':
1987
+ case '-':
1988
+ case '*':
1989
+ case '/': {
1990
+ const leftNumber = toExpressionNumber(left);
1991
+ const rightNumber = toExpressionNumber(right);
1992
+
1993
+ if (leftNumber === null || rightNumber === null) {
1994
+ return null;
1995
+ }
1996
+
1997
+ return calculateExpressionDecimal(leftNumber, op, rightNumber);
1998
+ }
1999
+ case '=':
2000
+ if (left === null || right === null) {
2001
+ return left === right;
2002
+ }
2003
+ return compareScalars(left, right) === 0;
2004
+ case '!=':
2005
+ if (left === null || right === null) {
2006
+ return left !== right;
2007
+ }
2008
+ return compareScalars(left, right) !== 0;
2009
+ case '>':
2010
+ return compareScalars(left, right) > 0;
2011
+ case '>=':
2012
+ return compareScalars(left, right) >= 0;
2013
+ case '<':
2014
+ return compareScalars(left, right) < 0;
2015
+ case '<=':
2016
+ return compareScalars(left, right) <= 0;
2017
+ default:
2018
+ throw new ExpressionError(`Unknown operator "${op}".`);
2019
+ }
2020
+ }
2021
+
2022
+ /**
2023
+ * Evaluate one AST node against a row; returns the raw value (arrays/objects intact).
2024
+ */
2025
+
2026
+ function evaluateNodeValue(
710
2027
  node: ExpressionNode,
711
2028
  row: Record<string, unknown>,
712
- ): ExpressionValue {
2029
+ ): unknown {
713
2030
  switch (node.kind) {
714
2031
  case 'literal':
715
2032
  return node.value;
716
2033
  case 'field':
717
- return toScalar(getRowValueAtPath(row, node.path));
2034
+ return getRowValueAtPath(row, node.path) ?? null;
718
2035
  case 'unary': {
719
2036
  const operand = evaluateNode(node.operand, row);
720
2037
 
@@ -722,10 +2039,25 @@ function evaluateNode(
722
2039
  return !toExpressionBool(operand);
723
2040
  }
724
2041
 
725
- const numberValue = toExpressionNumber(operand);
2042
+ const numberValue = toExpressionNumber(toScalar(operand));
726
2043
  return numberValue === null ? null : -numberValue;
727
2044
  }
728
2045
  case 'call':
2046
+ if (node.name === 'if') {
2047
+ const branch = toExpressionBool(evaluateNode(node.args[0], row))
2048
+ ? node.args[1]
2049
+ : node.args[2];
2050
+ return branch ? evaluateNode(branch, row) : null;
2051
+ }
2052
+ if (node.name === 'coalesce') {
2053
+ for (const argument of node.args) {
2054
+ const value = evaluateNode(argument, row);
2055
+ if (!isEmptyValue(value)) {
2056
+ return value;
2057
+ }
2058
+ }
2059
+ return null;
2060
+ }
729
2061
  return evaluateFunction(
730
2062
  node.name,
731
2063
  node.args.map((arg) => evaluateNode(arg, row)),
@@ -745,55 +2077,49 @@ function evaluateNode(
745
2077
  );
746
2078
  }
747
2079
 
748
- const left = evaluateNode(node.left, row);
749
- const right = evaluateNode(node.right, row);
2080
+ return evaluateBinaryOperator(
2081
+ node.op,
2082
+ toScalar(evaluateNode(node.left, row)),
2083
+ toScalar(evaluateNode(node.right, row)),
2084
+ );
2085
+ }
2086
+ }
2087
+ }
750
2088
 
751
- switch (node.op) {
752
- case '+':
753
- case '-':
754
- case '*':
755
- case '/': {
756
- const leftNumber = toExpressionNumber(left);
757
- const rightNumber = toExpressionNumber(right);
2089
+ /*
2090
+ * Evaluate one node and enforce the scalar output limits at every operation.
2091
+ */
2092
+ function evaluateNode(
2093
+ node: ExpressionNode,
2094
+ row: Record<string, unknown>,
2095
+ ): unknown {
2096
+ return assertExpressionResult(evaluateNodeValue(node, row));
2097
+ }
758
2098
 
759
- if (leftNumber === null || rightNumber === null) {
760
- return null;
761
- }
2099
+ /**
2100
+ * Walk every node of an AST (pre-order).
2101
+ */
762
2102
 
763
- switch (node.op) {
764
- case '+':
765
- return leftNumber + rightNumber;
766
- case '-':
767
- return leftNumber - rightNumber;
768
- case '*':
769
- return leftNumber * rightNumber;
770
- case '/':
771
- return rightNumber === 0 ? null : leftNumber / rightNumber;
772
- }
773
- return null;
774
- }
775
- case '=':
776
- if (left === null || right === null) {
777
- return left === right;
778
- }
779
- return compareScalars(left, right) === 0;
780
- case '!=':
781
- if (left === null || right === null) {
782
- return left !== right;
783
- }
784
- return compareScalars(left, right) !== 0;
785
- case '>':
786
- return compareScalars(left, right) > 0;
787
- case '>=':
788
- return compareScalars(left, right) >= 0;
789
- case '<':
790
- return compareScalars(left, right) < 0;
791
- case '<=':
792
- return compareScalars(left, right) <= 0;
793
- default:
794
- throw new ExpressionError(`Unknown operator "${node.op}".`);
2103
+ function walkExpressionNodes(
2104
+ node: ExpressionNode,
2105
+ visit: (current: ExpressionNode) => void,
2106
+ ) {
2107
+ visit(node);
2108
+
2109
+ switch (node.kind) {
2110
+ case 'unary':
2111
+ walkExpressionNodes(node.operand, visit);
2112
+ break;
2113
+ case 'binary':
2114
+ walkExpressionNodes(node.left, visit);
2115
+ walkExpressionNodes(node.right, visit);
2116
+ break;
2117
+ case 'call':
2118
+ for (const arg of node.args) {
2119
+ walkExpressionNodes(arg, visit);
795
2120
  }
796
- }
2121
+ break;
2122
+ default:
797
2123
  }
798
2124
  }
799
2125
 
@@ -804,33 +2130,96 @@ function evaluateNode(
804
2130
  export function getExpressionFieldRefs(node: ExpressionNode): string[] {
805
2131
  const refs: string[] = [];
806
2132
 
807
- const walk = (current: ExpressionNode) => {
808
- switch (current.kind) {
809
- case 'field': {
810
- const ref = current.path.join('.');
811
- if (!refs.includes(ref)) {
812
- refs.push(ref);
813
- }
814
- break;
2133
+ walkExpressionNodes(node, (current) => {
2134
+ if (current.kind === 'field') {
2135
+ const ref = current.path.join('.');
2136
+ if (!refs.includes(ref)) {
2137
+ refs.push(ref);
815
2138
  }
816
- case 'unary':
817
- walk(current.operand);
818
- break;
819
- case 'binary':
820
- walk(current.left);
821
- walk(current.right);
822
- break;
823
- case 'call':
824
- current.args.forEach(walk);
825
- break;
826
- default:
827
2139
  }
828
- };
2140
+ });
829
2141
 
830
- walk(node);
831
2142
  return refs;
832
2143
  }
833
2144
 
2145
+ /**
2146
+ * For every collection call whose array argument is a field reference, the array path and the
2147
+ * element paths named by its string-literal field arguments (so a validator can check them
2148
+ * against the array's element schema).
2149
+ */
2150
+
2151
+ export function getExpressionCollectionFieldRefs(
2152
+ node: ExpressionNode,
2153
+ ): ExpressionCollectionFieldRefs[] {
2154
+ const refs: ExpressionCollectionFieldRefs[] = [];
2155
+
2156
+ walkExpressionNodes(node, (current) => {
2157
+ if (current.kind !== 'call' || current.args[0]?.kind !== 'field') {
2158
+ return;
2159
+ }
2160
+
2161
+ if (findExpressionFunctionSpec(current.name)?.category !== 'collection') {
2162
+ return;
2163
+ }
2164
+
2165
+ const elementPaths = (
2166
+ FILE_CONSTANTS.collectionFieldArgs[current.name] || []
2167
+ )
2168
+ .map((argIndex) => current.args[argIndex])
2169
+ .filter(
2170
+ (arg): arg is { kind: 'literal'; value: string } =>
2171
+ arg?.kind === 'literal' &&
2172
+ typeof arg.value === 'string' &&
2173
+ arg.value !== '',
2174
+ )
2175
+ .map((arg) => arg.value);
2176
+
2177
+ refs.push({
2178
+ functionName: current.name,
2179
+ arrayPath: current.args[0].path.join('.'),
2180
+ elementPaths: Array.from(new Set(elementPaths)),
2181
+ });
2182
+ });
2183
+
2184
+ return refs;
2185
+ }
2186
+
2187
+ /**
2188
+ * Prompt text describing the grammar and every registered function (one line each).
2189
+ */
2190
+
2191
+ export function renderExpressionCheatsheet(): string {
2192
+ const categories: ExpressionFunctionCategory[] = [
2193
+ 'text',
2194
+ 'number',
2195
+ 'date',
2196
+ 'logic',
2197
+ 'collection',
2198
+ ];
2199
+
2200
+ const functionLines = categories.flatMap((category) => [
2201
+ `[${category}]`,
2202
+ ...EXPRESSION_FUNCTIONS.filter((spec) => spec.category === category).map(
2203
+ (spec) =>
2204
+ ` ${spec.signature} — ${spec.description} e.g. ${spec.example}`,
2205
+ ),
2206
+ ]);
2207
+
2208
+ return [
2209
+ 'Expression grammar:',
2210
+ '- Field references: dotted paths from the row root, e.g. metadata.quantity or files.0.name. Wrap a column whose name has spaces or symbols in brackets: [Vendor Name], metadata.[Unit price]. A bracket segment names ONE column; it cannot contain quotes, parentheses, commas, "=" or a filter condition.',
2211
+ "- Literals: numbers (12, 3.5), single-quoted text ('EBT', 'it''s' for an embedded quote), true, false, null. Double quotes are not supported.",
2212
+ "- Operators: + - * / on numbers; = != > >= < <= comparisons (numeric only when BOTH sides are plain numbers such as 12 or '3.5'; anything else compares as text, so YYYY-MM-DD dates, HH:mm times and ids like 'org-12' order correctly as text and date >= '2026-08-15' works); and, or, not; parentheses for grouping. Precedence: or < and < not < comparison < + - < * / < unary -.",
2213
+ '- Null semantics: a missing field is null; arithmetic with a non-numeric operand or division by zero yields null; text functions return null for null input; null, false, 0, empty text and empty arrays are falsy in and/or/not/if; = and != treat null as equal only to null.',
2214
+ '- Arrays and objects: a field may hold an array (e.g. metadata.values); pass it directly to a collection function. Wherever a scalar is required an array/object becomes its JSON text, so use lookup/sumWhere/joinText to read elements.',
2215
+ `- ${FILE_CONSTANTS.jsSyntaxMessage} Method calls such as text.toUpperCase() are not supported; use upper(text).`,
2216
+ `- Limits: ${EXPRESSION_MAX_LENGTH} characters, nesting depth ${EXPRESSION_MAX_DEPTH}.`,
2217
+ '',
2218
+ 'Functions (signature — description e.g. example):',
2219
+ ...functionLines,
2220
+ ].join('\n');
2221
+ }
2222
+
834
2223
  /**
835
2224
  * Parse an expression string into an AST; throws ExpressionError with a self-correction hint.
836
2225
  */
@@ -862,6 +2251,11 @@ export function compileExpression(input: string): CompiledExpression {
862
2251
  source: String(input ?? '').trim(),
863
2252
  node,
864
2253
  fieldRefs: getExpressionFieldRefs(node),
865
- evaluate: (row: Record<string, unknown>) => evaluateNode(node, row),
2254
+ evaluate: (row: Record<string, unknown>) =>
2255
+ toScalar(evaluateNode(node, row)),
2256
+ evaluateRaw: (row: Record<string, unknown>) =>
2257
+ evaluateNode(node, row) ?? null,
2258
+ evaluatePredicate: (row: Record<string, unknown>) =>
2259
+ toExpressionBool(evaluateNode(node, row)),
866
2260
  };
867
2261
  }