@jsb188/app 1.1.10 → 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.
- package/package.json +57 -45
- package/src/constants/agent.ts +51 -41
- package/src/constants/app.ts +34 -13
- package/src/constants/emoji.ts +9144 -8936
- package/src/constants/other.ts +1 -5
- package/src/constants/user.ts +16 -25
- package/src/constants/wsActions.ts +27 -0
- package/src/i18n/account.ts +129 -107
- package/src/i18n/agent.ts +331 -73
- package/src/i18n/agentToolBusiness.ts +196 -0
- package/src/i18n/agentToolGrid.ts +137 -0
- package/src/i18n/agentToolWorkflow.ts +101 -0
- package/src/i18n/agent_note.ts +109 -0
- package/src/i18n/app.ts +107 -91
- package/src/i18n/auth.ts +117 -102
- package/src/i18n/billing.ts +5 -92
- package/src/i18n/c.ts +907 -0
- package/src/i18n/campaign.ts +919 -0
- package/src/i18n/country.ts +248 -248
- package/src/i18n/datetime.ts +32 -26
- package/src/i18n/editor.ts +58 -0
- package/src/i18n/error.ts +577 -192
- package/src/i18n/field_doc_editor.ts +21 -0
- package/src/i18n/field_doc_programs.ts +52 -0
- package/src/i18n/field_docs.ts +190 -0
- package/src/i18n/index.ts +42 -19
- package/src/i18n/log.ts +272 -238
- package/src/i18n/memory.ts +53 -0
- package/src/i18n/message.ts +3 -4
- package/src/i18n/note.ts +19 -0
- package/src/i18n/org.ts +164 -109
- package/src/i18n/schedule.ts +209 -0
- package/src/i18n/sheet.ts +333 -4
- package/src/i18n/sheet_formula.ts +165 -0
- package/src/i18n/workflow.ts +109 -23
- package/src/main.ts +68 -64
- package/src/platform.ts +90 -49
- package/src/types/ai.d.ts +52 -23
- package/src/types/app.d.ts +95 -44
- package/src/types/auth.d.ts +66 -40
- package/src/types/console.d.ts +3 -0
- package/src/types/other.d.ts +13 -6
- package/src/types.d.ts +12 -14
- package/src/utils/account.ts +64 -58
- package/src/utils/api.ts +326 -77
- package/src/utils/authSession.ts +24 -0
- package/src/utils/clientIP.ts +213 -0
- package/src/utils/color.ts +279 -0
- package/src/utils/cron.ts +49 -18
- package/src/utils/csv.ts +19 -0
- package/src/utils/datetime.ts +445 -117
- package/src/utils/deferredSave.ts +89 -0
- package/src/utils/email.ts +50 -0
- package/src/utils/emoji.ts +107 -84
- package/src/utils/expression.helpers.ts +470 -0
- package/src/utils/expression.test.ts +793 -0
- package/src/utils/expression.ts +2261 -0
- package/src/utils/interval.ts +80 -0
- package/src/utils/language.ts +9 -0
- package/src/utils/logic.ts +141 -121
- package/src/utils/managedSession.ts +34 -0
- package/src/utils/managedSessionBff.test.ts +60 -0
- package/src/utils/managedSessionBff.ts +117 -0
- package/src/utils/number.ts +85 -38
- package/src/utils/object.ts +227 -30
- package/src/utils/promise.ts +98 -0
- package/src/utils/queryReset.ts +266 -0
- package/src/utils/recurringTask.ts +60 -0
- package/src/utils/schema.ts +293 -0
- package/src/utils/string.test.ts +205 -208
- package/src/utils/string.ts +426 -463
- package/src/utils/timeZone.ts +309 -851
- package/src/utils/url_client.ts +145 -72
- package/tsconfig.json +10 -10
- package/src/constants/billing.ts +0 -146
- package/src/i18n/form.ts +0 -376
- package/src/i18n/product.ts +0 -76
- package/src/types/form.d.ts +0 -97
- package/src/utils/billing.ts +0 -134
|
@@ -0,0 +1,2261 @@
|
|
|
1
|
+
import {
|
|
2
|
+
calculateExpressionDecimal,
|
|
3
|
+
compareExpressionValues,
|
|
4
|
+
parseDecoratedExpressionNumber,
|
|
5
|
+
parseExpressionDate,
|
|
6
|
+
parsePlainExpressionNumber,
|
|
7
|
+
roundExpressionDecimal,
|
|
8
|
+
sumExpressionNumbers,
|
|
9
|
+
} from './expression.helpers.ts';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Safe expression mini-DSL for declarative row transforms (no eval / no Function).
|
|
13
|
+
*
|
|
14
|
+
* Supported syntax:
|
|
15
|
+
* - Field refs: dotted paths against a row object — `metadata.quantity`, `files.0.name`,
|
|
16
|
+
* and bracket segments for labels with spaces/symbols — `[Crop name]`, `metadata.[Unit price]`
|
|
17
|
+
* - Literals: numbers, single-quoted strings ('it''s' escapes a quote), true, false, null
|
|
18
|
+
* - Operators: + - * / (numeric), = != > >= < <= (comparisons), and or not, parentheses
|
|
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).
|
|
25
|
+
*
|
|
26
|
+
* Deterministic null behavior: arithmetic with a non-numeric operand returns null,
|
|
27
|
+
* division by zero returns null, text functions return null for null input.
|
|
28
|
+
*/
|
|
29
|
+
|
|
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
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Function registry: the single source for parsing, evaluation, the prompt
|
|
52
|
+
* cheatsheet and the model-facing name list.
|
|
53
|
+
*/
|
|
54
|
+
|
|
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);
|
|
538
|
+
|
|
539
|
+
export type ExpressionValue = string | number | boolean | null;
|
|
540
|
+
|
|
541
|
+
export type ExpressionNode =
|
|
542
|
+
| { kind: 'literal'; value: ExpressionValue }
|
|
543
|
+
| { kind: 'field'; path: string[] }
|
|
544
|
+
| { kind: 'unary'; op: '-' | 'not'; operand: ExpressionNode }
|
|
545
|
+
| { kind: 'binary'; op: string; left: ExpressionNode; right: ExpressionNode }
|
|
546
|
+
| { kind: 'call'; name: ExpressionFunctionName; args: ExpressionNode[] };
|
|
547
|
+
|
|
548
|
+
export interface CompiledExpression {
|
|
549
|
+
source: string;
|
|
550
|
+
node: ExpressionNode;
|
|
551
|
+
fieldRefs: string[]; // Full dotted paths referenced by the expression
|
|
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
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Error thrown for any parse or validation problem; message names the offender
|
|
576
|
+
* so an LLM caller can self-correct.
|
|
577
|
+
*/
|
|
578
|
+
|
|
579
|
+
export class ExpressionError extends Error {
|
|
580
|
+
constructor(message: string) {
|
|
581
|
+
super(message);
|
|
582
|
+
this.name = 'ExpressionError';
|
|
583
|
+
}
|
|
584
|
+
}
|
|
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
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Tokenizer
|
|
650
|
+
*/
|
|
651
|
+
|
|
652
|
+
interface ExpressionToken {
|
|
653
|
+
type:
|
|
654
|
+
| 'number'
|
|
655
|
+
| 'string'
|
|
656
|
+
| 'ident'
|
|
657
|
+
| 'field'
|
|
658
|
+
| 'op'
|
|
659
|
+
| 'lparen'
|
|
660
|
+
| 'rparen'
|
|
661
|
+
| 'comma';
|
|
662
|
+
text: string;
|
|
663
|
+
path?: string[];
|
|
664
|
+
}
|
|
665
|
+
|
|
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
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Read one field path starting at the given index; supports bare and [bracket] segments.
|
|
725
|
+
*/
|
|
726
|
+
|
|
727
|
+
function readFieldPath(input: string, startIndex: number) {
|
|
728
|
+
const path: string[] = [];
|
|
729
|
+
let index = startIndex;
|
|
730
|
+
let first = true;
|
|
731
|
+
|
|
732
|
+
while (index < input.length) {
|
|
733
|
+
const rest = input.slice(index);
|
|
734
|
+
|
|
735
|
+
if (rest[0] === '[') {
|
|
736
|
+
const closeIndex = rest.indexOf(']');
|
|
737
|
+
if (closeIndex === -1) {
|
|
738
|
+
throw new ExpressionError(
|
|
739
|
+
`Unclosed "[" in field reference at position ${index}.`,
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
|
|
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();
|
|
749
|
+
if (!segment) {
|
|
750
|
+
throw new ExpressionError(
|
|
751
|
+
`Empty "[]" field segment at position ${index}.`,
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
path.push(segment);
|
|
756
|
+
index += closeIndex + 1;
|
|
757
|
+
} else {
|
|
758
|
+
const segmentMatch = rest.match(
|
|
759
|
+
first
|
|
760
|
+
? FILE_CONSTANTS.tokenPatterns.bareSegment
|
|
761
|
+
: FILE_CONSTANTS.tokenPatterns.pathSegment,
|
|
762
|
+
);
|
|
763
|
+
if (!segmentMatch) {
|
|
764
|
+
break;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
path.push(segmentMatch[0]);
|
|
768
|
+
index += segmentMatch[0].length;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
first = false;
|
|
772
|
+
|
|
773
|
+
// Continue the path across "." separators only
|
|
774
|
+
if (input[index] === '.') {
|
|
775
|
+
index += 1;
|
|
776
|
+
} else {
|
|
777
|
+
break;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
return { path, endIndex: index };
|
|
782
|
+
}
|
|
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
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Convert an expression string into a flat token list.
|
|
815
|
+
*/
|
|
816
|
+
|
|
817
|
+
function tokenizeExpression(input: string) {
|
|
818
|
+
const tokens: ExpressionToken[] = [];
|
|
819
|
+
const patterns = FILE_CONSTANTS.tokenPatterns;
|
|
820
|
+
let index = 0;
|
|
821
|
+
|
|
822
|
+
while (index < input.length) {
|
|
823
|
+
const rest = input.slice(index);
|
|
824
|
+
const whitespaceMatch = rest.match(patterns.whitespace);
|
|
825
|
+
|
|
826
|
+
if (whitespaceMatch) {
|
|
827
|
+
index += whitespaceMatch[0].length;
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
if (rest[0] === '(') {
|
|
832
|
+
tokens.push({ type: 'lparen', text: '(' });
|
|
833
|
+
index += 1;
|
|
834
|
+
continue;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
if (rest[0] === ')') {
|
|
838
|
+
tokens.push({ type: 'rparen', text: ')' });
|
|
839
|
+
index += 1;
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (rest[0] === ',') {
|
|
844
|
+
tokens.push({ type: 'comma', text: ',' });
|
|
845
|
+
index += 1;
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
if (rest[0] === "'") {
|
|
850
|
+
const { text, endIndex } = readStringLiteral(input, index);
|
|
851
|
+
tokens.push({ type: 'string', text });
|
|
852
|
+
index = endIndex;
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
const numberMatch = rest.match(patterns.number);
|
|
857
|
+
if (numberMatch) {
|
|
858
|
+
tokens.push({ type: 'number', text: numberMatch[0] });
|
|
859
|
+
index += numberMatch[0].length;
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
|
|
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);
|
|
873
|
+
if (operatorMatch) {
|
|
874
|
+
tokens.push({ type: 'op', text: operatorMatch[0] });
|
|
875
|
+
index += operatorMatch[0].length;
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (rest[0] === '[' || patterns.bareSegment.test(rest)) {
|
|
880
|
+
const { path, endIndex } = readFieldPath(input, index);
|
|
881
|
+
const lowerFirst = path[0]?.toLowerCase();
|
|
882
|
+
|
|
883
|
+
if (
|
|
884
|
+
rest[0] !== '[' &&
|
|
885
|
+
path.length === 1 &&
|
|
886
|
+
FILE_CONSTANTS.keywords.includes(lowerFirst)
|
|
887
|
+
) {
|
|
888
|
+
tokens.push({ type: 'ident', text: lowerFirst });
|
|
889
|
+
} else {
|
|
890
|
+
tokens.push({ type: 'field', text: path.join('.'), path });
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
index = endIndex;
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
throw new ExpressionError(
|
|
898
|
+
`Unexpected character "${rest[0]}" at position ${index} near "${getInputExcerpt(input, index)}".`,
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
return tokens;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Parser (recursive descent; precedence: or < and < not < comparison < additive < multiplicative < unary)
|
|
907
|
+
*/
|
|
908
|
+
|
|
909
|
+
class ExpressionParser {
|
|
910
|
+
private tokens: ExpressionToken[];
|
|
911
|
+
private position = 0;
|
|
912
|
+
private depth = 0;
|
|
913
|
+
|
|
914
|
+
constructor(tokens: ExpressionToken[]) {
|
|
915
|
+
this.tokens = tokens;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* Parse the full token list into one AST node.
|
|
920
|
+
*/
|
|
921
|
+
|
|
922
|
+
parse(): ExpressionNode {
|
|
923
|
+
const node = this.parseOr();
|
|
924
|
+
const leftover = this.peek();
|
|
925
|
+
|
|
926
|
+
if (leftover) {
|
|
927
|
+
throw new ExpressionError(
|
|
928
|
+
`Unexpected "${leftover.text}" after end of expression.`,
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
return node;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
private peek() {
|
|
936
|
+
return this.tokens[this.position] || null;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
private next() {
|
|
940
|
+
return this.tokens[this.position++] || null;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// Depth counts only true nesting points (parens, calls, unary chains) —
|
|
944
|
+
// flat operator chains are bounded by EXPRESSION_MAX_LENGTH instead
|
|
945
|
+
private enter() {
|
|
946
|
+
this.depth += 1;
|
|
947
|
+
if (this.depth > EXPRESSION_MAX_DEPTH) {
|
|
948
|
+
throw new ExpressionError(
|
|
949
|
+
`Expression nesting exceeds the maximum depth of ${EXPRESSION_MAX_DEPTH}.`,
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
private exit() {
|
|
955
|
+
this.depth -= 1;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
private parseOr(): ExpressionNode {
|
|
959
|
+
let left = this.parseAnd();
|
|
960
|
+
|
|
961
|
+
while (this.peek()?.type === 'ident' && this.peek()?.text === 'or') {
|
|
962
|
+
this.next();
|
|
963
|
+
left = { kind: 'binary', op: 'or', left, right: this.parseAnd() };
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
return left;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
private parseAnd(): ExpressionNode {
|
|
970
|
+
let left = this.parseNot();
|
|
971
|
+
|
|
972
|
+
while (this.peek()?.type === 'ident' && this.peek()?.text === 'and') {
|
|
973
|
+
this.next();
|
|
974
|
+
left = { kind: 'binary', op: 'and', left, right: this.parseNot() };
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
return left;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
private parseNot(): ExpressionNode {
|
|
981
|
+
if (this.peek()?.type === 'ident' && this.peek()?.text === 'not') {
|
|
982
|
+
this.enter();
|
|
983
|
+
this.next();
|
|
984
|
+
const node: ExpressionNode = {
|
|
985
|
+
kind: 'unary',
|
|
986
|
+
op: 'not',
|
|
987
|
+
operand: this.parseNot(),
|
|
988
|
+
};
|
|
989
|
+
this.exit();
|
|
990
|
+
return node;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
return this.parseComparison();
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
private parseComparison(): ExpressionNode {
|
|
997
|
+
const left = this.parseAdditive();
|
|
998
|
+
const peeked = this.peek();
|
|
999
|
+
|
|
1000
|
+
if (
|
|
1001
|
+
peeked?.type === 'op' &&
|
|
1002
|
+
['=', '!=', '>', '>=', '<', '<='].includes(peeked.text)
|
|
1003
|
+
) {
|
|
1004
|
+
this.next();
|
|
1005
|
+
return {
|
|
1006
|
+
kind: 'binary',
|
|
1007
|
+
op: peeked.text,
|
|
1008
|
+
left,
|
|
1009
|
+
right: this.parseAdditive(),
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
return left;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
private parseAdditive(): ExpressionNode {
|
|
1017
|
+
let left = this.parseMultiplicative();
|
|
1018
|
+
|
|
1019
|
+
while (
|
|
1020
|
+
this.peek()?.type === 'op' &&
|
|
1021
|
+
['+', '-'].includes(this.peek()!.text)
|
|
1022
|
+
) {
|
|
1023
|
+
const op = this.next()!.text;
|
|
1024
|
+
left = { kind: 'binary', op, left, right: this.parseMultiplicative() };
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
return left;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
private parseMultiplicative(): ExpressionNode {
|
|
1031
|
+
let left = this.parseUnary();
|
|
1032
|
+
|
|
1033
|
+
while (
|
|
1034
|
+
this.peek()?.type === 'op' &&
|
|
1035
|
+
['*', '/'].includes(this.peek()!.text)
|
|
1036
|
+
) {
|
|
1037
|
+
const op = this.next()!.text;
|
|
1038
|
+
left = { kind: 'binary', op, left, right: this.parseUnary() };
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
return left;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
private parseUnary(): ExpressionNode {
|
|
1045
|
+
if (this.peek()?.type === 'op' && this.peek()?.text === '-') {
|
|
1046
|
+
this.enter();
|
|
1047
|
+
this.next();
|
|
1048
|
+
const node: ExpressionNode = {
|
|
1049
|
+
kind: 'unary',
|
|
1050
|
+
op: '-',
|
|
1051
|
+
operand: this.parseUnary(),
|
|
1052
|
+
};
|
|
1053
|
+
this.exit();
|
|
1054
|
+
return node;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
return this.parsePrimary();
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
private parsePrimary(): ExpressionNode {
|
|
1061
|
+
const token = this.next();
|
|
1062
|
+
if (!token) {
|
|
1063
|
+
throw new ExpressionError('Unexpected end of expression.');
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
switch (token.type) {
|
|
1067
|
+
case 'number':
|
|
1068
|
+
return { kind: 'literal', value: Number(token.text) };
|
|
1069
|
+
case 'string':
|
|
1070
|
+
return { kind: 'literal', value: token.text };
|
|
1071
|
+
case 'ident':
|
|
1072
|
+
if (token.text === 'true') {
|
|
1073
|
+
return { kind: 'literal', value: true };
|
|
1074
|
+
}
|
|
1075
|
+
if (token.text === 'false') {
|
|
1076
|
+
return { kind: 'literal', value: false };
|
|
1077
|
+
}
|
|
1078
|
+
if (token.text === 'null') {
|
|
1079
|
+
return { kind: 'literal', value: null };
|
|
1080
|
+
}
|
|
1081
|
+
throw new ExpressionError(`Unexpected keyword "${token.text}".`);
|
|
1082
|
+
case 'field': {
|
|
1083
|
+
// A field token followed by "(" is a function call
|
|
1084
|
+
if (this.peek()?.type === 'lparen') {
|
|
1085
|
+
return this.parseCall(token);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
return { kind: 'field', path: token.path || [token.text] };
|
|
1089
|
+
}
|
|
1090
|
+
case 'lparen': {
|
|
1091
|
+
this.enter();
|
|
1092
|
+
const node = this.parseOr();
|
|
1093
|
+
this.exit();
|
|
1094
|
+
|
|
1095
|
+
const closer = this.next();
|
|
1096
|
+
if (!closer || closer.type !== 'rparen') {
|
|
1097
|
+
throw new ExpressionError('Missing closing ")".');
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
return node;
|
|
1101
|
+
}
|
|
1102
|
+
default:
|
|
1103
|
+
throw new ExpressionError(`Unexpected "${token.text}".`);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
private parseCall(nameToken: ExpressionToken): ExpressionNode {
|
|
1108
|
+
if ((nameToken.path || []).length > 1) {
|
|
1109
|
+
throw new ExpressionError(
|
|
1110
|
+
`"${nameToken.text}" is not a valid function name. ${FILE_CONSTANTS.jsSyntaxMessage}`,
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
1113
|
+
|
|
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
|
+
: '';
|
|
1120
|
+
throw new ExpressionError(
|
|
1121
|
+
`Unknown function "${nameToken.text}".${didYouMean} Available functions: ${EXPRESSION_FUNCTION_NAMES.join(', ')}. ${FILE_CONSTANTS.jsSyntaxMessage}`,
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
this.enter();
|
|
1126
|
+
this.next(); // Consume "("
|
|
1127
|
+
|
|
1128
|
+
const args: ExpressionNode[] = [];
|
|
1129
|
+
if (this.peek()?.type !== 'rparen') {
|
|
1130
|
+
args.push(this.parseOr());
|
|
1131
|
+
while (this.peek()?.type === 'comma') {
|
|
1132
|
+
this.next();
|
|
1133
|
+
args.push(this.parseOr());
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
const closer = this.next();
|
|
1138
|
+
if (!closer || closer.type !== 'rparen') {
|
|
1139
|
+
throw new ExpressionError(
|
|
1140
|
+
`Missing closing ")" for function "${spec.name}".`,
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
this.exit();
|
|
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
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* Evaluation helpers
|
|
1214
|
+
*/
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Read a nested value from a row by path segments.
|
|
1218
|
+
*/
|
|
1219
|
+
|
|
1220
|
+
function getRowValueAtPath(row: unknown, path: string[]) {
|
|
1221
|
+
return path.reduce<unknown>((acc, pathPart) => {
|
|
1222
|
+
if (Array.isArray(acc)) {
|
|
1223
|
+
const indexValue = Number(pathPart);
|
|
1224
|
+
return Number.isInteger(indexValue) ? acc[indexValue] : undefined;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
if (acc && typeof acc === 'object') {
|
|
1228
|
+
return (acc as Record<string, unknown>)[pathPart];
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
return undefined;
|
|
1232
|
+
}, row);
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/**
|
|
1236
|
+
* Convert a complete decimal amount into a finite number, accepting known units,
|
|
1237
|
+
* currencies and valid thousands grouping.
|
|
1238
|
+
*/
|
|
1239
|
+
|
|
1240
|
+
export function toExpressionNumber(value: unknown): number | null {
|
|
1241
|
+
return parseDecoratedExpressionNumber(value);
|
|
1242
|
+
}
|
|
1243
|
+
|
|
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
|
+
*/
|
|
1250
|
+
|
|
1251
|
+
export function toStrictExpressionNumber(value: unknown): number | null {
|
|
1252
|
+
return parsePlainExpressionNumber(value);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/**
|
|
1256
|
+
* Truthiness for and/or/not/if: null, undefined, false, 0, NaN, '' and empty arrays are false.
|
|
1257
|
+
*/
|
|
1258
|
+
|
|
1259
|
+
function toExpressionBool(value: unknown) {
|
|
1260
|
+
return !(
|
|
1261
|
+
value === null ||
|
|
1262
|
+
value === undefined ||
|
|
1263
|
+
value === false ||
|
|
1264
|
+
value === 0 ||
|
|
1265
|
+
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)
|
|
1281
|
+
);
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
/**
|
|
1285
|
+
* Normalize any evaluated value into an ExpressionValue scalar.
|
|
1286
|
+
*/
|
|
1287
|
+
|
|
1288
|
+
function toScalar(value: unknown): ExpressionValue {
|
|
1289
|
+
if (value === null || value === undefined) {
|
|
1290
|
+
return null;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
if (
|
|
1294
|
+
typeof value === 'number' ||
|
|
1295
|
+
typeof value === 'string' ||
|
|
1296
|
+
typeof value === 'boolean'
|
|
1297
|
+
) {
|
|
1298
|
+
return assertExpressionResult(value);
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
if (value instanceof Date) {
|
|
1302
|
+
return value.toISOString();
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// Objects/arrays flatten to JSON so nothing silently disappears
|
|
1306
|
+
let serialized: string;
|
|
1307
|
+
try {
|
|
1308
|
+
serialized = JSON.stringify(value);
|
|
1309
|
+
} catch {
|
|
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
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
return parts.join(separator);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
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).
|
|
1360
|
+
*/
|
|
1361
|
+
|
|
1362
|
+
function compareScalars(a: ExpressionValue, b: ExpressionValue) {
|
|
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
|
+
*/
|
|
1369
|
+
|
|
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;
|
|
1376
|
+
}
|
|
1377
|
+
|
|
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}`;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
/**
|
|
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.
|
|
1423
|
+
*/
|
|
1424
|
+
|
|
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
|
|
1457
|
+
return null;
|
|
1458
|
+
}
|
|
1459
|
+
|
|
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) {
|
|
1486
|
+
return null;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
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
|
+
}
|
|
1575
|
+
|
|
1576
|
+
return unit === 'month' ? months : Math.trunc(months / 12);
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
/**
|
|
1580
|
+
* Coerce a collection argument: arrays pass through, anything else is an empty array.
|
|
1581
|
+
*/
|
|
1582
|
+
|
|
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(
|
|
1655
|
+
name: ExpressionFunctionName,
|
|
1656
|
+
args: unknown[],
|
|
1657
|
+
): unknown {
|
|
1658
|
+
const text = toNullableText(args[0]);
|
|
1659
|
+
|
|
1660
|
+
switch (name) {
|
|
1661
|
+
case 'concat':
|
|
1662
|
+
return joinExpressionText(args.map((arg) => String(toScalar(arg) ?? '')));
|
|
1663
|
+
case 'coalesce':
|
|
1664
|
+
return args.find((arg) => !isEmptyValue(arg)) ?? null;
|
|
1665
|
+
case 'upper':
|
|
1666
|
+
return text === null ? null : text.toUpperCase();
|
|
1667
|
+
case 'lower':
|
|
1668
|
+
return text === null ? null : text.toLowerCase();
|
|
1669
|
+
case 'trim':
|
|
1670
|
+
return text === null ? null : text.trim();
|
|
1671
|
+
case 'substr': {
|
|
1672
|
+
if (text === null) {
|
|
1673
|
+
return null;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
const start = Math.max(0, toExpressionNumber(toScalar(args[1])) ?? 0);
|
|
1677
|
+
const length = toExpressionNumber(toScalar(args[2]));
|
|
1678
|
+
return length === null
|
|
1679
|
+
? text.slice(start)
|
|
1680
|
+
: text.slice(start, start + Math.max(0, length));
|
|
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) {
|
|
1820
|
+
case 'dateFormat':
|
|
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) {
|
|
1868
|
+
case 'if':
|
|
1869
|
+
return toExpressionBool(args[0]) ? (args[1] ?? null) : (args[2] ?? null);
|
|
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
|
+
*/
|
|
1892
|
+
|
|
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);
|
|
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;
|
|
1945
|
+
default:
|
|
1946
|
+
throw new ExpressionError(`Unknown function "${name}".`);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
/**
|
|
1951
|
+
* Evaluate one whitelisted function call on raw (unconverted) argument values.
|
|
1952
|
+
*/
|
|
1953
|
+
|
|
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(
|
|
2027
|
+
node: ExpressionNode,
|
|
2028
|
+
row: Record<string, unknown>,
|
|
2029
|
+
): unknown {
|
|
2030
|
+
switch (node.kind) {
|
|
2031
|
+
case 'literal':
|
|
2032
|
+
return node.value;
|
|
2033
|
+
case 'field':
|
|
2034
|
+
return getRowValueAtPath(row, node.path) ?? null;
|
|
2035
|
+
case 'unary': {
|
|
2036
|
+
const operand = evaluateNode(node.operand, row);
|
|
2037
|
+
|
|
2038
|
+
if (node.op === 'not') {
|
|
2039
|
+
return !toExpressionBool(operand);
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
const numberValue = toExpressionNumber(toScalar(operand));
|
|
2043
|
+
return numberValue === null ? null : -numberValue;
|
|
2044
|
+
}
|
|
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
|
+
}
|
|
2061
|
+
return evaluateFunction(
|
|
2062
|
+
node.name,
|
|
2063
|
+
node.args.map((arg) => evaluateNode(arg, row)),
|
|
2064
|
+
);
|
|
2065
|
+
case 'binary': {
|
|
2066
|
+
if (node.op === 'and') {
|
|
2067
|
+
return (
|
|
2068
|
+
toExpressionBool(evaluateNode(node.left, row)) &&
|
|
2069
|
+
toExpressionBool(evaluateNode(node.right, row))
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
if (node.op === 'or') {
|
|
2074
|
+
return (
|
|
2075
|
+
toExpressionBool(evaluateNode(node.left, row)) ||
|
|
2076
|
+
toExpressionBool(evaluateNode(node.right, row))
|
|
2077
|
+
);
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
return evaluateBinaryOperator(
|
|
2081
|
+
node.op,
|
|
2082
|
+
toScalar(evaluateNode(node.left, row)),
|
|
2083
|
+
toScalar(evaluateNode(node.right, row)),
|
|
2084
|
+
);
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
|
|
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
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* Walk every node of an AST (pre-order).
|
|
2101
|
+
*/
|
|
2102
|
+
|
|
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);
|
|
2120
|
+
}
|
|
2121
|
+
break;
|
|
2122
|
+
default:
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
/**
|
|
2127
|
+
* Collect every field path referenced by an AST (deduped, in first-seen order).
|
|
2128
|
+
*/
|
|
2129
|
+
|
|
2130
|
+
export function getExpressionFieldRefs(node: ExpressionNode): string[] {
|
|
2131
|
+
const refs: string[] = [];
|
|
2132
|
+
|
|
2133
|
+
walkExpressionNodes(node, (current) => {
|
|
2134
|
+
if (current.kind === 'field') {
|
|
2135
|
+
const ref = current.path.join('.');
|
|
2136
|
+
if (!refs.includes(ref)) {
|
|
2137
|
+
refs.push(ref);
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
});
|
|
2141
|
+
|
|
2142
|
+
return refs;
|
|
2143
|
+
}
|
|
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
|
+
|
|
2223
|
+
/**
|
|
2224
|
+
* Parse an expression string into an AST; throws ExpressionError with a self-correction hint.
|
|
2225
|
+
*/
|
|
2226
|
+
|
|
2227
|
+
export function parseExpression(input: string): ExpressionNode {
|
|
2228
|
+
const source = String(input ?? '').trim();
|
|
2229
|
+
|
|
2230
|
+
if (!source) {
|
|
2231
|
+
throw new ExpressionError('Expression is empty.');
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
if (source.length > EXPRESSION_MAX_LENGTH) {
|
|
2235
|
+
throw new ExpressionError(
|
|
2236
|
+
`Expression is longer than ${EXPRESSION_MAX_LENGTH} characters.`,
|
|
2237
|
+
);
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
return new ExpressionParser(tokenizeExpression(source)).parse();
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
/**
|
|
2244
|
+
* Parse once and return a reusable evaluator plus the referenced field paths.
|
|
2245
|
+
*/
|
|
2246
|
+
|
|
2247
|
+
export function compileExpression(input: string): CompiledExpression {
|
|
2248
|
+
const node = parseExpression(input);
|
|
2249
|
+
|
|
2250
|
+
return {
|
|
2251
|
+
source: String(input ?? '').trim(),
|
|
2252
|
+
node,
|
|
2253
|
+
fieldRefs: getExpressionFieldRefs(node),
|
|
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)),
|
|
2260
|
+
};
|
|
2261
|
+
}
|