@jsb188/app 1.1.10 → 1.1.11

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 (63) hide show
  1. package/package.json +54 -45
  2. package/src/constants/agent.ts +58 -25
  3. package/src/constants/app.ts +18 -14
  4. package/src/constants/billing.ts +92 -92
  5. package/src/constants/emoji.ts +9144 -8936
  6. package/src/constants/other.ts +1 -5
  7. package/src/constants/user.ts +16 -25
  8. package/src/constants/wsActions.ts +35 -0
  9. package/src/i18n/account.ts +129 -107
  10. package/src/i18n/agent.ts +63 -43
  11. package/src/i18n/agentDoc.ts +110 -0
  12. package/src/i18n/app.ts +101 -91
  13. package/src/i18n/auth.ts +119 -102
  14. package/src/i18n/billing.ts +73 -78
  15. package/src/i18n/campaign.ts +217 -0
  16. package/src/i18n/country.ts +248 -248
  17. package/src/i18n/datetime.ts +26 -26
  18. package/src/i18n/error.ts +428 -182
  19. package/src/i18n/field_docs.ts +28 -0
  20. package/src/i18n/form.ts +464 -344
  21. package/src/i18n/index.ts +25 -18
  22. package/src/i18n/log.ts +53 -213
  23. package/src/i18n/memory.ts +39 -0
  24. package/src/i18n/message.ts +3 -4
  25. package/src/i18n/note.ts +17 -0
  26. package/src/i18n/org.ts +115 -109
  27. package/src/i18n/sheet.ts +376 -4
  28. package/src/i18n/workflow.ts +70 -23
  29. package/src/main.ts +66 -62
  30. package/src/platform.ts +25 -24
  31. package/src/types/ai.d.ts +33 -23
  32. package/src/types/app.d.ts +95 -37
  33. package/src/types/auth.d.ts +66 -40
  34. package/src/types/console.d.ts +3 -0
  35. package/src/types/form.d.ts +65 -61
  36. package/src/types/other.d.ts +6 -6
  37. package/src/types.d.ts +12 -14
  38. package/src/utils/account.ts +64 -58
  39. package/src/utils/api.ts +280 -77
  40. package/src/utils/authSession.ts +24 -0
  41. package/src/utils/billing.ts +110 -103
  42. package/src/utils/color.ts +202 -0
  43. package/src/utils/cron.ts +49 -18
  44. package/src/utils/datetime.ts +255 -103
  45. package/src/utils/emoji.ts +107 -84
  46. package/src/utils/expression.ts +867 -0
  47. package/src/utils/interval.ts +80 -0
  48. package/src/utils/logic.ts +209 -36
  49. package/src/utils/managedSession.ts +34 -0
  50. package/src/utils/managedSessionBff.test.ts +60 -0
  51. package/src/utils/managedSessionBff.ts +117 -0
  52. package/src/utils/number.ts +60 -32
  53. package/src/utils/object.ts +198 -30
  54. package/src/utils/promise.ts +27 -0
  55. package/src/utils/queryReset.ts +179 -0
  56. package/src/utils/recurringTask.ts +60 -0
  57. package/src/utils/schema.ts +293 -0
  58. package/src/utils/string.test.ts +220 -208
  59. package/src/utils/string.ts +471 -438
  60. package/src/utils/timeZone.ts +309 -851
  61. package/src/utils/url_client.ts +73 -69
  62. package/tsconfig.json +10 -10
  63. package/src/i18n/product.ts +0 -76
@@ -0,0 +1,867 @@
1
+ /**
2
+ * Safe expression mini-DSL for declarative row transforms (no eval / no Function).
3
+ *
4
+ * Supported syntax:
5
+ * - Field refs: dotted paths against a row object — `metadata.quantity`, `files.0.name`,
6
+ * and bracket segments for labels with spaces/symbols — `[Crop name]`, `metadata.[Unit price]`
7
+ * - Literals: numbers, single-quoted strings ('it''s' escapes a quote), true, false, null
8
+ * - Operators: + - * / (numeric), = != > >= < <= (comparisons), and or not, parentheses
9
+ * - Functions: concat, coalesce, num, round, abs, upper, lower, trim, substr,
10
+ * dateFormat, if, contains
11
+ *
12
+ * Deterministic null behavior: arithmetic with a non-numeric operand returns null,
13
+ * division by zero returns null, string functions return null for null input.
14
+ */
15
+
16
+ export const EXPRESSION_MAX_LENGTH = 300;
17
+ export const EXPRESSION_MAX_DEPTH = 8;
18
+
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;
33
+
34
+ type ExpressionFunctionName = (typeof EXPRESSION_FUNCTION_NAMES)[number];
35
+
36
+ export type ExpressionValue = string | number | boolean | null;
37
+
38
+ export type ExpressionNode =
39
+ | { kind: 'literal'; value: ExpressionValue }
40
+ | { kind: 'field'; path: string[] }
41
+ | { kind: 'unary'; op: '-' | 'not'; operand: ExpressionNode }
42
+ | { kind: 'binary'; op: string; left: ExpressionNode; right: ExpressionNode }
43
+ | { kind: 'call'; name: ExpressionFunctionName; args: ExpressionNode[] };
44
+
45
+ export interface CompiledExpression {
46
+ source: string;
47
+ node: ExpressionNode;
48
+ fieldRefs: string[]; // Full dotted paths referenced by the expression
49
+ evaluate: (row: Record<string, unknown>) => ExpressionValue;
50
+ }
51
+
52
+ /**
53
+ * Error thrown for any parse or validation problem; message names the offender
54
+ * so an LLM caller can self-correct.
55
+ */
56
+
57
+ export class ExpressionError extends Error {
58
+ constructor(message: string) {
59
+ super(message);
60
+ this.name = 'ExpressionError';
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Tokenizer
66
+ */
67
+
68
+ interface ExpressionToken {
69
+ type:
70
+ | 'number'
71
+ | 'string'
72
+ | 'ident'
73
+ | 'field'
74
+ | 'op'
75
+ | 'lparen'
76
+ | 'rparen'
77
+ | 'comma';
78
+ text: string;
79
+ path?: string[];
80
+ }
81
+
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
+ };
89
+
90
+ /**
91
+ * Read one field path starting at the given index; supports bare and [bracket] segments.
92
+ */
93
+
94
+ function readFieldPath(input: string, startIndex: number) {
95
+ const path: string[] = [];
96
+ let index = startIndex;
97
+ let first = true;
98
+
99
+ while (index < input.length) {
100
+ const rest = input.slice(index);
101
+
102
+ if (rest[0] === '[') {
103
+ const closeIndex = rest.indexOf(']');
104
+ if (closeIndex === -1) {
105
+ throw new ExpressionError(
106
+ `Unclosed "[" in field reference at position ${index}.`,
107
+ );
108
+ }
109
+
110
+ const segment = rest.slice(1, closeIndex).trim();
111
+ if (!segment) {
112
+ throw new ExpressionError(
113
+ `Empty "[]" field segment at position ${index}.`,
114
+ );
115
+ }
116
+
117
+ path.push(segment);
118
+ index += closeIndex + 1;
119
+ } else {
120
+ const segmentMatch = rest.match(
121
+ first ? TOKEN_PATTERNS.bareSegment : TOKEN_PATTERNS.pathSegment,
122
+ );
123
+ if (!segmentMatch) {
124
+ break;
125
+ }
126
+
127
+ path.push(segmentMatch[0]);
128
+ index += segmentMatch[0].length;
129
+ }
130
+
131
+ first = false;
132
+
133
+ // Continue the path across "." separators only
134
+ if (input[index] === '.') {
135
+ index += 1;
136
+ } else {
137
+ break;
138
+ }
139
+ }
140
+
141
+ return { path, endIndex: index };
142
+ }
143
+
144
+ /**
145
+ * Convert an expression string into a flat token list.
146
+ */
147
+
148
+ function tokenizeExpression(input: string) {
149
+ const tokens: ExpressionToken[] = [];
150
+ let index = 0;
151
+
152
+ while (index < input.length) {
153
+ const rest = input.slice(index);
154
+ const whitespaceMatch = rest.match(TOKEN_PATTERNS.whitespace);
155
+
156
+ if (whitespaceMatch) {
157
+ index += whitespaceMatch[0].length;
158
+ continue;
159
+ }
160
+
161
+ if (rest[0] === '(') {
162
+ tokens.push({ type: 'lparen', text: '(' });
163
+ index += 1;
164
+ continue;
165
+ }
166
+
167
+ if (rest[0] === ')') {
168
+ tokens.push({ type: 'rparen', text: ')' });
169
+ index += 1;
170
+ continue;
171
+ }
172
+
173
+ if (rest[0] === ',') {
174
+ tokens.push({ type: 'comma', text: ',' });
175
+ index += 1;
176
+ continue;
177
+ }
178
+
179
+ 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
+
201
+ tokens.push({ type: 'string', text });
202
+ index = cursor + 1;
203
+ continue;
204
+ }
205
+
206
+ const numberMatch = rest.match(TOKEN_PATTERNS.number);
207
+ if (numberMatch) {
208
+ tokens.push({ type: 'number', text: numberMatch[0] });
209
+ index += numberMatch[0].length;
210
+ continue;
211
+ }
212
+
213
+ const operatorMatch = rest.match(TOKEN_PATTERNS.operator);
214
+ if (operatorMatch) {
215
+ tokens.push({ type: 'op', text: operatorMatch[0] });
216
+ index += operatorMatch[0].length;
217
+ continue;
218
+ }
219
+
220
+ if (rest[0] === '[' || TOKEN_PATTERNS.bareSegment.test(rest)) {
221
+ const { path, endIndex } = readFieldPath(input, index);
222
+ const lowerFirst = path[0]?.toLowerCase();
223
+
224
+ if (
225
+ path.length === 1 &&
226
+ ['and', 'or', 'not', 'true', 'false', 'null'].includes(lowerFirst)
227
+ ) {
228
+ tokens.push({ type: 'ident', text: lowerFirst });
229
+ } else {
230
+ tokens.push({ type: 'field', text: path.join('.'), path });
231
+ }
232
+
233
+ index = endIndex;
234
+ continue;
235
+ }
236
+
237
+ throw new ExpressionError(
238
+ `Unexpected character "${rest[0]}" at position ${index}.`,
239
+ );
240
+ }
241
+
242
+ return tokens;
243
+ }
244
+
245
+ /**
246
+ * Parser (recursive descent; precedence: or < and < not < comparison < additive < multiplicative < unary)
247
+ */
248
+
249
+ class ExpressionParser {
250
+ private tokens: ExpressionToken[];
251
+ private position = 0;
252
+ private depth = 0;
253
+
254
+ constructor(tokens: ExpressionToken[]) {
255
+ this.tokens = tokens;
256
+ }
257
+
258
+ /**
259
+ * Parse the full token list into one AST node.
260
+ */
261
+
262
+ parse(): ExpressionNode {
263
+ const node = this.parseOr();
264
+ const leftover = this.peek();
265
+
266
+ if (leftover) {
267
+ throw new ExpressionError(
268
+ `Unexpected "${leftover.text}" after end of expression.`,
269
+ );
270
+ }
271
+
272
+ return node;
273
+ }
274
+
275
+ private peek() {
276
+ return this.tokens[this.position] || null;
277
+ }
278
+
279
+ private next() {
280
+ return this.tokens[this.position++] || null;
281
+ }
282
+
283
+ // Depth counts only true nesting points (parens, calls, unary chains) —
284
+ // flat operator chains are bounded by EXPRESSION_MAX_LENGTH instead
285
+ private enter() {
286
+ this.depth += 1;
287
+ if (this.depth > EXPRESSION_MAX_DEPTH) {
288
+ throw new ExpressionError(
289
+ `Expression nesting exceeds the maximum depth of ${EXPRESSION_MAX_DEPTH}.`,
290
+ );
291
+ }
292
+ }
293
+
294
+ private exit() {
295
+ this.depth -= 1;
296
+ }
297
+
298
+ private parseOr(): ExpressionNode {
299
+ let left = this.parseAnd();
300
+
301
+ while (this.peek()?.type === 'ident' && this.peek()?.text === 'or') {
302
+ this.next();
303
+ left = { kind: 'binary', op: 'or', left, right: this.parseAnd() };
304
+ }
305
+
306
+ return left;
307
+ }
308
+
309
+ private parseAnd(): ExpressionNode {
310
+ let left = this.parseNot();
311
+
312
+ while (this.peek()?.type === 'ident' && this.peek()?.text === 'and') {
313
+ this.next();
314
+ left = { kind: 'binary', op: 'and', left, right: this.parseNot() };
315
+ }
316
+
317
+ return left;
318
+ }
319
+
320
+ private parseNot(): ExpressionNode {
321
+ if (this.peek()?.type === 'ident' && this.peek()?.text === 'not') {
322
+ this.enter();
323
+ this.next();
324
+ const node: ExpressionNode = {
325
+ kind: 'unary',
326
+ op: 'not',
327
+ operand: this.parseNot(),
328
+ };
329
+ this.exit();
330
+ return node;
331
+ }
332
+
333
+ return this.parseComparison();
334
+ }
335
+
336
+ private parseComparison(): ExpressionNode {
337
+ const left = this.parseAdditive();
338
+ const peeked = this.peek();
339
+
340
+ if (
341
+ peeked?.type === 'op' &&
342
+ ['=', '!=', '>', '>=', '<', '<='].includes(peeked.text)
343
+ ) {
344
+ this.next();
345
+ return {
346
+ kind: 'binary',
347
+ op: peeked.text,
348
+ left,
349
+ right: this.parseAdditive(),
350
+ };
351
+ }
352
+
353
+ return left;
354
+ }
355
+
356
+ private parseAdditive(): ExpressionNode {
357
+ let left = this.parseMultiplicative();
358
+
359
+ while (
360
+ this.peek()?.type === 'op' &&
361
+ ['+', '-'].includes(this.peek()!.text)
362
+ ) {
363
+ const op = this.next()!.text;
364
+ left = { kind: 'binary', op, left, right: this.parseMultiplicative() };
365
+ }
366
+
367
+ return left;
368
+ }
369
+
370
+ private parseMultiplicative(): ExpressionNode {
371
+ let left = this.parseUnary();
372
+
373
+ while (
374
+ this.peek()?.type === 'op' &&
375
+ ['*', '/'].includes(this.peek()!.text)
376
+ ) {
377
+ const op = this.next()!.text;
378
+ left = { kind: 'binary', op, left, right: this.parseUnary() };
379
+ }
380
+
381
+ return left;
382
+ }
383
+
384
+ private parseUnary(): ExpressionNode {
385
+ if (this.peek()?.type === 'op' && this.peek()?.text === '-') {
386
+ this.enter();
387
+ this.next();
388
+ const node: ExpressionNode = {
389
+ kind: 'unary',
390
+ op: '-',
391
+ operand: this.parseUnary(),
392
+ };
393
+ this.exit();
394
+ return node;
395
+ }
396
+
397
+ return this.parsePrimary();
398
+ }
399
+
400
+ private parsePrimary(): ExpressionNode {
401
+ const token = this.next();
402
+ if (!token) {
403
+ throw new ExpressionError('Unexpected end of expression.');
404
+ }
405
+
406
+ switch (token.type) {
407
+ case 'number':
408
+ return { kind: 'literal', value: Number(token.text) };
409
+ case 'string':
410
+ return { kind: 'literal', value: token.text };
411
+ case 'ident':
412
+ if (token.text === 'true') {
413
+ return { kind: 'literal', value: true };
414
+ }
415
+ if (token.text === 'false') {
416
+ return { kind: 'literal', value: false };
417
+ }
418
+ if (token.text === 'null') {
419
+ return { kind: 'literal', value: null };
420
+ }
421
+ throw new ExpressionError(`Unexpected keyword "${token.text}".`);
422
+ case 'field': {
423
+ // A field token followed by "(" is a function call
424
+ if (this.peek()?.type === 'lparen') {
425
+ return this.parseCall(token);
426
+ }
427
+
428
+ return { kind: 'field', path: token.path || [token.text] };
429
+ }
430
+ case 'lparen': {
431
+ this.enter();
432
+ const node = this.parseOr();
433
+ this.exit();
434
+
435
+ const closer = this.next();
436
+ if (!closer || closer.type !== 'rparen') {
437
+ throw new ExpressionError('Missing closing ")".');
438
+ }
439
+
440
+ return node;
441
+ }
442
+ default:
443
+ throw new ExpressionError(`Unexpected "${token.text}".`);
444
+ }
445
+ }
446
+
447
+ private parseCall(nameToken: ExpressionToken): ExpressionNode {
448
+ if ((nameToken.path || []).length > 1) {
449
+ throw new ExpressionError(
450
+ `"${nameToken.text}" is not a valid function name.`,
451
+ );
452
+ }
453
+
454
+ const name = EXPRESSION_FUNCTION_NAMES.find(
455
+ (fnName) => fnName.toLowerCase() === nameToken.text.toLowerCase(),
456
+ );
457
+
458
+ if (!name) {
459
+ throw new ExpressionError(
460
+ `Unknown function "${nameToken.text}". Available functions: ${EXPRESSION_FUNCTION_NAMES.join(', ')}.`,
461
+ );
462
+ }
463
+
464
+ this.enter();
465
+ this.next(); // Consume "("
466
+
467
+ const args: ExpressionNode[] = [];
468
+ if (this.peek()?.type !== 'rparen') {
469
+ args.push(this.parseOr());
470
+ while (this.peek()?.type === 'comma') {
471
+ this.next();
472
+ args.push(this.parseOr());
473
+ }
474
+ }
475
+
476
+ const closer = this.next();
477
+ if (!closer || closer.type !== 'rparen') {
478
+ throw new ExpressionError(`Missing closing ")" for function "${name}".`);
479
+ }
480
+
481
+ this.exit();
482
+ return { kind: 'call', name, args };
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Evaluation helpers
488
+ */
489
+
490
+ /**
491
+ * Read a nested value from a row by path segments.
492
+ */
493
+
494
+ function getRowValueAtPath(row: Record<string, unknown>, path: string[]) {
495
+ return path.reduce<unknown>((acc, pathPart) => {
496
+ if (Array.isArray(acc)) {
497
+ const indexValue = Number(pathPart);
498
+ return Number.isInteger(indexValue) ? acc[indexValue] : undefined;
499
+ }
500
+
501
+ if (acc && typeof acc === 'object') {
502
+ return (acc as Record<string, unknown>)[pathPart];
503
+ }
504
+
505
+ return undefined;
506
+ }, row);
507
+ }
508
+
509
+ /**
510
+ * Convert a value into a finite number, tolerating units/currency/comma noise.
511
+ */
512
+
513
+ 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
+ }
534
+
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
+ }
541
+
542
+ return null;
543
+ }
544
+
545
+ /**
546
+ * Truthiness for and/or/not/if: null, undefined, false, 0, NaN, and '' are false.
547
+ */
548
+
549
+ function toExpressionBool(value: unknown) {
550
+ return !(
551
+ value === null ||
552
+ value === undefined ||
553
+ value === false ||
554
+ value === 0 ||
555
+ value === '' ||
556
+ (typeof value === 'number' && Number.isNaN(value))
557
+ );
558
+ }
559
+
560
+ /**
561
+ * Normalize any evaluated value into an ExpressionValue scalar.
562
+ */
563
+
564
+ function toScalar(value: unknown): ExpressionValue {
565
+ if (value === null || value === undefined) {
566
+ return null;
567
+ }
568
+
569
+ if (
570
+ typeof value === 'number' ||
571
+ typeof value === 'string' ||
572
+ typeof value === 'boolean'
573
+ ) {
574
+ return value;
575
+ }
576
+
577
+ if (value instanceof Date) {
578
+ return value.toISOString();
579
+ }
580
+
581
+ // Objects/arrays flatten to JSON so nothing silently disappears
582
+ try {
583
+ return JSON.stringify(value);
584
+ } catch {
585
+ return String(value);
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Compare two scalars: numeric when both parse as numbers, string otherwise.
591
+ */
592
+
593
+ function compareScalars(a: ExpressionValue, b: ExpressionValue) {
594
+ const aNumber = toExpressionNumber(a);
595
+ const bNumber = toExpressionNumber(b);
596
+
597
+ if (aNumber !== null && bNumber !== null) {
598
+ return aNumber - bNumber;
599
+ }
600
+
601
+ return String(a ?? '').localeCompare(String(b ?? ''));
602
+ }
603
+
604
+ /**
605
+ * Format a date-like value with YYYY/MM/DD tokens (UTC-based so date-only strings never shift).
606
+ */
607
+
608
+ function formatDateValue(value: unknown, format: unknown) {
609
+ const valueText =
610
+ value instanceof Date ? value.toISOString() : String(value ?? '').trim();
611
+ if (!valueText) {
612
+ return null;
613
+ }
614
+
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())) {
618
+ return null;
619
+ }
620
+
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');
624
+
625
+ return String(format ?? 'YYYY-MM-DD')
626
+ .replace(/YYYY/g, year)
627
+ .replace(/MM/g, month)
628
+ .replace(/DD/g, day);
629
+ }
630
+
631
+ /**
632
+ * Evaluate one whitelisted function call.
633
+ */
634
+
635
+ function evaluateFunction(
636
+ name: ExpressionFunctionName,
637
+ args: ExpressionValue[],
638
+ ): ExpressionValue {
639
+ switch (name) {
640
+ case 'concat':
641
+ return args.map((arg) => String(arg ?? '')).join('');
642
+ 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
+ }
663
+ case 'upper':
664
+ return args[0] === null || args[0] === undefined
665
+ ? null
666
+ : String(args[0]).toUpperCase();
667
+ case 'lower':
668
+ return args[0] === null || args[0] === undefined
669
+ ? null
670
+ : String(args[0]).toLowerCase();
671
+ case 'trim':
672
+ return args[0] === null || args[0] === undefined
673
+ ? null
674
+ : String(args[0]).trim();
675
+ case 'substr': {
676
+ if (args[0] === null || args[0] === undefined) {
677
+ return null;
678
+ }
679
+
680
+ const text = String(args[0]);
681
+ const start = Math.max(0, toExpressionNumber(args[1]) ?? 0);
682
+ const length = toExpressionNumber(args[2]);
683
+ return length === null
684
+ ? text.slice(start)
685
+ : text.slice(start, start + Math.max(0, length));
686
+ }
687
+ case 'dateFormat':
688
+ return formatDateValue(args[0], args[1]);
689
+ case 'if':
690
+ 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
+ }
695
+
696
+ return String(args[0])
697
+ .toLowerCase()
698
+ .includes(String(args[1] ?? '').toLowerCase());
699
+ }
700
+ default:
701
+ throw new ExpressionError(`Unknown function "${name}".`);
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Evaluate one AST node against a row.
707
+ */
708
+
709
+ function evaluateNode(
710
+ node: ExpressionNode,
711
+ row: Record<string, unknown>,
712
+ ): ExpressionValue {
713
+ switch (node.kind) {
714
+ case 'literal':
715
+ return node.value;
716
+ case 'field':
717
+ return toScalar(getRowValueAtPath(row, node.path));
718
+ case 'unary': {
719
+ const operand = evaluateNode(node.operand, row);
720
+
721
+ if (node.op === 'not') {
722
+ return !toExpressionBool(operand);
723
+ }
724
+
725
+ const numberValue = toExpressionNumber(operand);
726
+ return numberValue === null ? null : -numberValue;
727
+ }
728
+ case 'call':
729
+ return evaluateFunction(
730
+ node.name,
731
+ node.args.map((arg) => evaluateNode(arg, row)),
732
+ );
733
+ case 'binary': {
734
+ if (node.op === 'and') {
735
+ return (
736
+ toExpressionBool(evaluateNode(node.left, row)) &&
737
+ toExpressionBool(evaluateNode(node.right, row))
738
+ );
739
+ }
740
+
741
+ if (node.op === 'or') {
742
+ return (
743
+ toExpressionBool(evaluateNode(node.left, row)) ||
744
+ toExpressionBool(evaluateNode(node.right, row))
745
+ );
746
+ }
747
+
748
+ const left = evaluateNode(node.left, row);
749
+ const right = evaluateNode(node.right, row);
750
+
751
+ switch (node.op) {
752
+ case '+':
753
+ case '-':
754
+ case '*':
755
+ case '/': {
756
+ const leftNumber = toExpressionNumber(left);
757
+ const rightNumber = toExpressionNumber(right);
758
+
759
+ if (leftNumber === null || rightNumber === null) {
760
+ return null;
761
+ }
762
+
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}".`);
795
+ }
796
+ }
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Collect every field path referenced by an AST (deduped, in first-seen order).
802
+ */
803
+
804
+ export function getExpressionFieldRefs(node: ExpressionNode): string[] {
805
+ const refs: string[] = [];
806
+
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;
815
+ }
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
+ }
828
+ };
829
+
830
+ walk(node);
831
+ return refs;
832
+ }
833
+
834
+ /**
835
+ * Parse an expression string into an AST; throws ExpressionError with a self-correction hint.
836
+ */
837
+
838
+ export function parseExpression(input: string): ExpressionNode {
839
+ const source = String(input ?? '').trim();
840
+
841
+ if (!source) {
842
+ throw new ExpressionError('Expression is empty.');
843
+ }
844
+
845
+ if (source.length > EXPRESSION_MAX_LENGTH) {
846
+ throw new ExpressionError(
847
+ `Expression is longer than ${EXPRESSION_MAX_LENGTH} characters.`,
848
+ );
849
+ }
850
+
851
+ return new ExpressionParser(tokenizeExpression(source)).parse();
852
+ }
853
+
854
+ /**
855
+ * Parse once and return a reusable evaluator plus the referenced field paths.
856
+ */
857
+
858
+ export function compileExpression(input: string): CompiledExpression {
859
+ const node = parseExpression(input);
860
+
861
+ return {
862
+ source: String(input ?? '').trim(),
863
+ node,
864
+ fieldRefs: getExpressionFieldRefs(node),
865
+ evaluate: (row: Record<string, unknown>) => evaluateNode(node, row),
866
+ };
867
+ }