@jmespath-community/jmespath 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +228 -12
  2. package/dist/cli.cjs +2816 -0
  3. package/dist/cli.cjs.map +1 -0
  4. package/dist/cli.d.cts +2 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.mjs +2794 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/index.cjs +2699 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.cts +464 -0
  11. package/dist/index.d.ts +464 -0
  12. package/dist/index.esm.js +2707 -0
  13. package/dist/index.esm.js.map +1 -0
  14. package/dist/index.esm.min.js +6 -0
  15. package/dist/index.esm.min.js.map +1 -0
  16. package/dist/index.mjs +2697 -0
  17. package/dist/index.mjs.map +1 -0
  18. package/dist/index.umd.js +2712 -0
  19. package/dist/index.umd.js.map +1 -0
  20. package/dist/index.umd.min.js +6 -0
  21. package/dist/index.umd.min.js.map +1 -0
  22. package/package.json +68 -11
  23. package/dist/jmespath.esm.js +0 -2369
  24. package/dist/jmespath.esm.min.js +0 -2
  25. package/dist/jmespath.esm.min.js.map +0 -1
  26. package/dist/jmespath.umd.js +0 -2398
  27. package/dist/jmespath.umd.min.js +0 -2
  28. package/dist/jmespath.umd.min.js.map +0 -1
  29. package/dist/lib/bin/jp.js +0 -127
  30. package/dist/lib/bin/jp.js.map +0 -1
  31. package/dist/lib/package.json +0 -70
  32. package/dist/lib/src/AST.type.js +0 -3
  33. package/dist/lib/src/AST.type.js.map +0 -1
  34. package/dist/lib/src/JSON.type.js +0 -3
  35. package/dist/lib/src/JSON.type.js.map +0 -1
  36. package/dist/lib/src/Lexer.js +0 -327
  37. package/dist/lib/src/Lexer.js.map +0 -1
  38. package/dist/lib/src/Lexer.type.js +0 -46
  39. package/dist/lib/src/Lexer.type.js.map +0 -1
  40. package/dist/lib/src/Parser.js +0 -468
  41. package/dist/lib/src/Parser.js.map +0 -1
  42. package/dist/lib/src/Parser.type.js +0 -3
  43. package/dist/lib/src/Parser.type.js.map +0 -1
  44. package/dist/lib/src/Runtime.js +0 -924
  45. package/dist/lib/src/Runtime.js.map +0 -1
  46. package/dist/lib/src/Scope.js +0 -29
  47. package/dist/lib/src/Scope.js.map +0 -1
  48. package/dist/lib/src/TreeInterpreter.js +0 -319
  49. package/dist/lib/src/TreeInterpreter.js.map +0 -1
  50. package/dist/lib/src/index.js +0 -65
  51. package/dist/lib/src/index.js.map +0 -1
  52. package/dist/lib/src/utils/index.js +0 -145
  53. package/dist/lib/src/utils/index.js.map +0 -1
  54. package/dist/lib/src/utils/strings.js +0 -92
  55. package/dist/lib/src/utils/strings.js.map +0 -1
  56. package/dist/lib/src/utils/text.js +0 -45
  57. package/dist/lib/src/utils/text.js.map +0 -1
  58. package/dist/types/bin/jp.d.ts +0 -2
  59. package/dist/types/src/AST.type.d.ts +0 -104
  60. package/dist/types/src/JSON.type.d.ts +0 -10
  61. package/dist/types/src/Lexer.d.ts +0 -19
  62. package/dist/types/src/Lexer.type.d.ts +0 -51
  63. package/dist/types/src/Parser.d.ts +0 -33
  64. package/dist/types/src/Parser.type.d.ts +0 -4
  65. package/dist/types/src/Runtime.d.ts +0 -87
  66. package/dist/types/src/Scope.d.ts +0 -8
  67. package/dist/types/src/TreeInterpreter.d.ts +0 -22
  68. package/dist/types/src/index.d.ts +0 -45
  69. package/dist/types/src/utils/index.d.ts +0 -16
  70. package/dist/types/src/utils/strings.d.ts +0 -11
  71. package/dist/types/src/utils/text.d.ts +0 -11
package/dist/cli.mjs ADDED
@@ -0,0 +1,2794 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'fs';
3
+ import { parseArgs } from 'util';
4
+
5
+ // package.json
6
+ var package_default = {
7
+ name: "@jmespath-community/jmespath",
8
+ version: "1.4.0"};
9
+
10
+ // src/utils/ast.ts
11
+ var CHILD_PROPS = ["left", "right", "condition", "child", "operand", "trueExpr", "falseExpr", "expression"];
12
+ function pushChildren(node, stack) {
13
+ const n = node;
14
+ for (const prop of CHILD_PROPS) {
15
+ const val = n[prop];
16
+ if (val && typeof val === "object" && "type" in val) {
17
+ stack.push(val);
18
+ }
19
+ }
20
+ if (Array.isArray(n.children)) {
21
+ for (const item of n.children) {
22
+ if (!item) {
23
+ continue;
24
+ }
25
+ stack.push(item);
26
+ if (item.type === "KeyValuePair" && item.value) {
27
+ stack.push(item.value);
28
+ }
29
+ }
30
+ }
31
+ if (Array.isArray(n.bindings)) {
32
+ for (const item of n.bindings) {
33
+ if (!item) {
34
+ continue;
35
+ }
36
+ stack.push(item);
37
+ if (item.reference) {
38
+ stack.push(item.reference);
39
+ }
40
+ }
41
+ }
42
+ }
43
+ function forEachNode(root, visitor) {
44
+ const stack = [root];
45
+ while (stack.length > 0) {
46
+ const current = stack.pop();
47
+ if (!current) {
48
+ break;
49
+ }
50
+ if (visitor(current) === false) {
51
+ return;
52
+ }
53
+ pushChildren(current, stack);
54
+ }
55
+ }
56
+ function countNodes(root) {
57
+ let count = 0;
58
+ forEachNode(root, () => {
59
+ count += 1;
60
+ return true;
61
+ });
62
+ return count;
63
+ }
64
+ function findDisallowedFunction(root, options) {
65
+ const { allowedFunctions, disallowedFunctions } = options;
66
+ if (!allowedFunctions && !disallowedFunctions) {
67
+ return null;
68
+ }
69
+ let violation = null;
70
+ forEachNode(root, (node) => {
71
+ if (node.type !== "Function") {
72
+ return true;
73
+ }
74
+ const name = node.name;
75
+ if (allowedFunctions && !allowedFunctions.includes(name)) {
76
+ violation = `Function '${name}' is not allowed`;
77
+ return false;
78
+ }
79
+ if (disallowedFunctions && disallowedFunctions.includes(name)) {
80
+ violation = `Function '${name}' is disallowed`;
81
+ return false;
82
+ }
83
+ return true;
84
+ });
85
+ return violation;
86
+ }
87
+
88
+ // src/utils/index.ts
89
+ var isObject = (obj) => {
90
+ return obj !== null && Object.prototype.toString.call(obj) === "[object Object]";
91
+ };
92
+ var strictDeepEqual = (first, second) => {
93
+ if (first === second) {
94
+ return true;
95
+ }
96
+ if (typeof first !== typeof second) {
97
+ return false;
98
+ }
99
+ if (Array.isArray(first) && Array.isArray(second)) {
100
+ if (first.length !== second.length) {
101
+ return false;
102
+ }
103
+ for (let i = 0; i < first.length; i += 1) {
104
+ if (!strictDeepEqual(first[i], second[i])) {
105
+ return false;
106
+ }
107
+ }
108
+ return true;
109
+ }
110
+ if (isObject(first) && isObject(second)) {
111
+ const firstEntries = Object.entries(first);
112
+ const secondKeys = new Set(Object.keys(second));
113
+ if (firstEntries.length !== secondKeys.size) {
114
+ return false;
115
+ }
116
+ for (const [key, value] of firstEntries) {
117
+ if (!strictDeepEqual(value, second[key])) {
118
+ return false;
119
+ }
120
+ secondKeys.delete(key);
121
+ }
122
+ return secondKeys.size === 0;
123
+ }
124
+ return false;
125
+ };
126
+ var isFalse = (obj) => {
127
+ if (obj === null || obj === void 0 || obj === false) {
128
+ return true;
129
+ }
130
+ if (typeof obj === "string") {
131
+ return obj === "";
132
+ }
133
+ if (typeof obj === "object") {
134
+ if (Array.isArray(obj)) {
135
+ return obj.length === 0;
136
+ }
137
+ return Object.keys(obj).length === 0;
138
+ }
139
+ return false;
140
+ };
141
+ var isAlpha = (ch) => {
142
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_";
143
+ };
144
+ var isNum = (ch) => {
145
+ return ch >= "0" && ch <= "9" || ch === "-";
146
+ };
147
+ var isAlphaNum = (ch) => {
148
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "_";
149
+ };
150
+ var ensureInteger = (value) => {
151
+ if (!(typeof value === "number") || Math.floor(value) !== value) {
152
+ throw new Error("invalid-value: expecting an integer.");
153
+ }
154
+ return value;
155
+ };
156
+ var ensurePositiveInteger = (value) => {
157
+ if (!(typeof value === "number") || value < 0 || Math.floor(value) !== value) {
158
+ throw new Error("invalid-value: expecting a non-negative integer.");
159
+ }
160
+ return value;
161
+ };
162
+ var ensureNumbers = (...operands) => {
163
+ for (let i = 0; i < operands.length; i++) {
164
+ if (operands[i] === null || operands[i] === void 0) {
165
+ throw new Error("not-a-number: undefined");
166
+ }
167
+ if (typeof operands[i] !== "number") {
168
+ throw new Error("not-a-number");
169
+ }
170
+ }
171
+ };
172
+ var notZero = (n) => {
173
+ n = +n;
174
+ if (!n) {
175
+ throw new Error("not-a-number: divide by zero");
176
+ }
177
+ return n;
178
+ };
179
+ var add = (left, right) => {
180
+ ensureNumbers(left, right);
181
+ return left + right;
182
+ };
183
+ var sub = (left, right) => {
184
+ ensureNumbers(left, right);
185
+ return left - right;
186
+ };
187
+ var mul = (left, right) => {
188
+ ensureNumbers(left, right);
189
+ return left * right;
190
+ };
191
+ var divide = (left, right) => {
192
+ ensureNumbers(left, right);
193
+ return left / notZero(right);
194
+ };
195
+ var div = (left, right) => {
196
+ ensureNumbers(left, right);
197
+ return Math.floor(left / notZero(right));
198
+ };
199
+ var mod = (left, right) => {
200
+ ensureNumbers(left, right);
201
+ return left % right;
202
+ };
203
+
204
+ // src/Lexer.ts
205
+ var basicTokens = {
206
+ "(": "Lparen" /* TOK_LPAREN */,
207
+ ")": "Rparen" /* TOK_RPAREN */,
208
+ "*": "Star" /* TOK_STAR */,
209
+ ",": "Comma" /* TOK_COMMA */,
210
+ ".": "Dot" /* TOK_DOT */,
211
+ ":": "Colon" /* TOK_COLON */,
212
+ "@": "Current" /* TOK_CURRENT */,
213
+ "]": "Rbracket" /* TOK_RBRACKET */,
214
+ "{": "Lbrace" /* TOK_LBRACE */,
215
+ "}": "Rbrace" /* TOK_RBRACE */,
216
+ "+": "Plus" /* TOK_PLUS */,
217
+ "%": "Modulo" /* TOK_MODULO */,
218
+ "?": "Question" /* TOK_QUESTION */,
219
+ "\u2212": "Minus" /* TOK_MINUS */,
220
+ "\xD7": "Multiply" /* TOK_MULTIPLY */,
221
+ "\xF7": "Divide" /* TOK_DIVIDE */
222
+ };
223
+ var operatorStartToken = {
224
+ "!": true,
225
+ "<": true,
226
+ "=": true,
227
+ ">": true,
228
+ "&": true,
229
+ "|": true,
230
+ "/": true
231
+ };
232
+ var skipChars = {
233
+ " ": true,
234
+ "\n": true,
235
+ "\r": true,
236
+ " ": true
237
+ };
238
+ var StreamLexer = class {
239
+ _current = 0;
240
+ _enable_legacy_literals = false;
241
+ tokenize(stream, options) {
242
+ const tokens = [];
243
+ this._current = 0;
244
+ this._enable_legacy_literals = options?.enable_legacy_literals || false;
245
+ let start;
246
+ let identifier;
247
+ let token;
248
+ while (this._current < stream.length) {
249
+ if (isAlpha(stream[this._current])) {
250
+ start = this._current;
251
+ identifier = this.consumeUnquotedIdentifier(stream);
252
+ tokens.push({
253
+ start,
254
+ type: "UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */,
255
+ value: identifier
256
+ });
257
+ } else if (basicTokens[stream[this._current]] !== void 0) {
258
+ tokens.push({
259
+ start: this._current,
260
+ type: basicTokens[stream[this._current]],
261
+ value: stream[this._current]
262
+ });
263
+ this._current += 1;
264
+ } else if (stream[this._current] === "$") {
265
+ start = this._current;
266
+ if (this._current + 1 < stream.length && isAlpha(stream[this._current + 1])) {
267
+ this._current += 1;
268
+ identifier = this.consumeUnquotedIdentifier(stream);
269
+ tokens.push({
270
+ start,
271
+ type: "Variable" /* TOK_VARIABLE */,
272
+ value: identifier
273
+ });
274
+ } else {
275
+ tokens.push({
276
+ start,
277
+ type: "Root" /* TOK_ROOT */,
278
+ value: stream[this._current]
279
+ });
280
+ this._current += 1;
281
+ }
282
+ } else if (stream[this._current] === "-") {
283
+ if (this._current + 1 < stream.length && isNum(stream[this._current + 1])) {
284
+ const token2 = this.consumeNumber(stream);
285
+ token2 && tokens.push(token2);
286
+ } else {
287
+ const token2 = {
288
+ start: this._current,
289
+ type: "Minus" /* TOK_MINUS */,
290
+ value: "-"
291
+ };
292
+ tokens.push(token2);
293
+ this._current += 1;
294
+ }
295
+ } else if (isNum(stream[this._current])) {
296
+ token = this.consumeNumber(stream);
297
+ tokens.push(token);
298
+ } else if (stream[this._current] === "[") {
299
+ token = this.consumeLBracket(stream);
300
+ tokens.push(token);
301
+ } else if (stream[this._current] === '"') {
302
+ start = this._current;
303
+ identifier = this.consumeQuotedIdentifier(stream);
304
+ tokens.push({
305
+ start,
306
+ type: "QuotedIdentifier" /* TOK_QUOTEDIDENTIFIER */,
307
+ value: identifier
308
+ });
309
+ } else if (stream[this._current] === `'`) {
310
+ start = this._current;
311
+ identifier = this.consumeRawStringLiteral(stream);
312
+ tokens.push({
313
+ start,
314
+ type: "Literal" /* TOK_LITERAL */,
315
+ value: identifier
316
+ });
317
+ } else if (stream[this._current] === "`") {
318
+ start = this._current;
319
+ const literal = this.consumeLiteral(stream);
320
+ tokens.push({
321
+ start,
322
+ type: "Literal" /* TOK_LITERAL */,
323
+ value: literal
324
+ });
325
+ } else if (operatorStartToken[stream[this._current]] !== void 0) {
326
+ token = this.consumeOperator(stream);
327
+ token && tokens.push(token);
328
+ } else if (skipChars[stream[this._current]] !== void 0) {
329
+ this._current += 1;
330
+ } else {
331
+ const error = new Error(`Syntax error: unknown character: ${stream[this._current]}`);
332
+ error.name = "LexerError";
333
+ throw error;
334
+ }
335
+ }
336
+ return tokens;
337
+ }
338
+ consumeUnquotedIdentifier(stream) {
339
+ const start = this._current;
340
+ this._current += 1;
341
+ while (this._current < stream.length && isAlphaNum(stream[this._current])) {
342
+ this._current += 1;
343
+ }
344
+ return stream.slice(start, this._current);
345
+ }
346
+ consumeQuotedIdentifier(stream) {
347
+ const start = this._current;
348
+ this._current += 1;
349
+ const maxLength = stream.length;
350
+ while (stream[this._current] !== '"' && this._current < maxLength) {
351
+ let current = this._current;
352
+ if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === '"')) {
353
+ current += 2;
354
+ } else {
355
+ current += 1;
356
+ }
357
+ this._current = current;
358
+ }
359
+ this._current += 1;
360
+ const [value, ok] = this.parseJSON(stream.slice(start, this._current));
361
+ if (!ok) {
362
+ const error = new Error(`syntax: unexpected end of JSON input`);
363
+ error.name = "LexerError";
364
+ throw error;
365
+ }
366
+ return value;
367
+ }
368
+ consumeRawStringLiteral(stream) {
369
+ const start = this._current;
370
+ this._current += 1;
371
+ const maxLength = stream.length;
372
+ while (stream[this._current] !== `'` && this._current < maxLength) {
373
+ let current = this._current;
374
+ if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === `'`)) {
375
+ current += 2;
376
+ } else {
377
+ current += 1;
378
+ }
379
+ this._current = current;
380
+ }
381
+ this._current += 1;
382
+ const literal = stream.slice(start + 1, this._current - 1);
383
+ return literal.replace(/\\(['\\])/g, "$1");
384
+ }
385
+ consumeNumber(stream) {
386
+ const start = this._current;
387
+ this._current += 1;
388
+ const maxLength = stream.length;
389
+ while (isNum(stream[this._current]) && this._current < maxLength) {
390
+ this._current += 1;
391
+ }
392
+ const value = parseInt(stream.slice(start, this._current), 10);
393
+ return { start, value, type: "Number" /* TOK_NUMBER */ };
394
+ }
395
+ consumeLBracket(stream) {
396
+ const start = this._current;
397
+ this._current += 1;
398
+ if (stream[this._current] === "?") {
399
+ this._current += 1;
400
+ return { start, type: "Filter" /* TOK_FILTER */, value: "[?" };
401
+ }
402
+ if (stream[this._current] === "]") {
403
+ this._current += 1;
404
+ return { start, type: "Flatten" /* TOK_FLATTEN */, value: "[]" };
405
+ }
406
+ return { start, type: "Lbracket" /* TOK_LBRACKET */, value: "[" };
407
+ }
408
+ consumeOrElse(stream, peek, token, orElse) {
409
+ const start = this._current;
410
+ this._current += 1;
411
+ if (this._current < stream.length && stream[this._current] === peek) {
412
+ this._current += 1;
413
+ return {
414
+ start,
415
+ type: orElse,
416
+ value: stream.slice(start, this._current)
417
+ };
418
+ }
419
+ return { start, type: token, value: stream[start] };
420
+ }
421
+ consumeOperator(stream) {
422
+ const start = this._current;
423
+ const startingChar = stream[start];
424
+ switch (startingChar) {
425
+ case "!":
426
+ return this.consumeOrElse(stream, "=", "Not" /* TOK_NOT */, "NE" /* TOK_NE */);
427
+ case "<":
428
+ return this.consumeOrElse(stream, "=", "LT" /* TOK_LT */, "LTE" /* TOK_LTE */);
429
+ case ">":
430
+ return this.consumeOrElse(stream, "=", "GT" /* TOK_GT */, "GTE" /* TOK_GTE */);
431
+ case "=":
432
+ return this.consumeOrElse(stream, "=", "Assign" /* TOK_ASSIGN */, "EQ" /* TOK_EQ */);
433
+ case "&":
434
+ return this.consumeOrElse(stream, "&", "Expref" /* TOK_EXPREF */, "And" /* TOK_AND */);
435
+ case "|":
436
+ return this.consumeOrElse(stream, "|", "Pipe" /* TOK_PIPE */, "Or" /* TOK_OR */);
437
+ case "/":
438
+ return this.consumeOrElse(stream, "/", "Divide" /* TOK_DIVIDE */, "Div" /* TOK_DIV */);
439
+ }
440
+ }
441
+ consumeLiteral(stream) {
442
+ this._current += 1;
443
+ const start = this._current;
444
+ const maxLength = stream.length;
445
+ while (stream[this._current] !== "`" && this._current < maxLength) {
446
+ let current = this._current;
447
+ if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "`")) {
448
+ current += 2;
449
+ } else {
450
+ current += 1;
451
+ }
452
+ this._current = current;
453
+ }
454
+ let literalString = stream.slice(start, this._current).trimStart();
455
+ literalString = literalString.replace("\\`", "`");
456
+ let literal = null;
457
+ let ok = false;
458
+ if (this.looksLikeJSON(literalString)) {
459
+ [literal, ok] = this.parseJSON(literalString);
460
+ }
461
+ if (!ok && this._enable_legacy_literals) {
462
+ [literal, ok] = this.parseJSON(`"${literalString}"`);
463
+ }
464
+ if (!ok) {
465
+ const error = new Error(
466
+ `Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${stream[this._current]}`
467
+ );
468
+ error.name = "LexerError";
469
+ throw error;
470
+ }
471
+ this._current += 1;
472
+ return literal;
473
+ }
474
+ looksLikeJSON(literalString) {
475
+ const startingChars = '[{"';
476
+ const jsonLiterals = ["true", "false", "null"];
477
+ const numberLooking = "-0123456789";
478
+ if (literalString === "") {
479
+ return false;
480
+ }
481
+ if (startingChars.includes(literalString[0])) {
482
+ return true;
483
+ }
484
+ if (jsonLiterals.includes(literalString)) {
485
+ return true;
486
+ }
487
+ if (numberLooking.includes(literalString[0])) {
488
+ const [_, ok] = this.parseJSON(literalString);
489
+ return ok;
490
+ }
491
+ return false;
492
+ }
493
+ parseJSON(text) {
494
+ try {
495
+ const json = JSON.parse(text);
496
+ return [json, true];
497
+ } catch {
498
+ return [null, false];
499
+ }
500
+ }
501
+ };
502
+ var Lexer = new StreamLexer();
503
+ var Lexer_default = Lexer;
504
+
505
+ // src/Parser.ts
506
+ var bindingPower = {
507
+ ["EOF" /* TOK_EOF */]: 0,
508
+ ["Variable" /* TOK_VARIABLE */]: 0,
509
+ ["UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */]: 0,
510
+ ["QuotedIdentifier" /* TOK_QUOTEDIDENTIFIER */]: 0,
511
+ ["Rbracket" /* TOK_RBRACKET */]: 0,
512
+ ["Rparen" /* TOK_RPAREN */]: 0,
513
+ ["Comma" /* TOK_COMMA */]: 0,
514
+ ["Rbrace" /* TOK_RBRACE */]: 0,
515
+ ["Number" /* TOK_NUMBER */]: 0,
516
+ ["Current" /* TOK_CURRENT */]: 0,
517
+ ["Expref" /* TOK_EXPREF */]: 0,
518
+ ["Root" /* TOK_ROOT */]: 0,
519
+ ["Assign" /* TOK_ASSIGN */]: 1,
520
+ ["Pipe" /* TOK_PIPE */]: 1,
521
+ ["Question" /* TOK_QUESTION */]: 2,
522
+ ["Or" /* TOK_OR */]: 3,
523
+ ["And" /* TOK_AND */]: 4,
524
+ ["EQ" /* TOK_EQ */]: 5,
525
+ ["GT" /* TOK_GT */]: 5,
526
+ ["LT" /* TOK_LT */]: 5,
527
+ ["GTE" /* TOK_GTE */]: 5,
528
+ ["LTE" /* TOK_LTE */]: 5,
529
+ ["NE" /* TOK_NE */]: 5,
530
+ ["Minus" /* TOK_MINUS */]: 6,
531
+ ["Plus" /* TOK_PLUS */]: 6,
532
+ ["Div" /* TOK_DIV */]: 7,
533
+ ["Divide" /* TOK_DIVIDE */]: 7,
534
+ ["Modulo" /* TOK_MODULO */]: 7,
535
+ ["Multiply" /* TOK_MULTIPLY */]: 7,
536
+ ["Flatten" /* TOK_FLATTEN */]: 9,
537
+ ["Star" /* TOK_STAR */]: 20,
538
+ ["Filter" /* TOK_FILTER */]: 21,
539
+ ["Dot" /* TOK_DOT */]: 40,
540
+ ["Not" /* TOK_NOT */]: 45,
541
+ ["Lbrace" /* TOK_LBRACE */]: 50,
542
+ ["Lbracket" /* TOK_LBRACKET */]: 55,
543
+ ["Lparen" /* TOK_LPAREN */]: 60
544
+ };
545
+ var TokenParser = class _TokenParser {
546
+ index = 0;
547
+ tokens = [];
548
+ depth = 0;
549
+ maxDepth;
550
+ nodeCount = 0;
551
+ maxNodes;
552
+ parse(expression2, options) {
553
+ this.loadTokens(expression2, options || { enable_legacy_literals: false });
554
+ this.index = 0;
555
+ this.depth = 0;
556
+ this.nodeCount = 0;
557
+ this.maxDepth = options?.maxDepth;
558
+ this.maxNodes = options?.maxNodes;
559
+ const ast = this.expression(0);
560
+ if (this.lookahead(0) !== "EOF" /* TOK_EOF */) {
561
+ const token = this.lookaheadToken(0);
562
+ this.errorToken(token, `Syntax error: unexpected token type: ${token.type}, value: ${token.value}`);
563
+ }
564
+ if (this.maxNodes !== void 0 && countNodes(ast) > this.maxNodes) {
565
+ throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`);
566
+ }
567
+ return ast;
568
+ }
569
+ loadTokens(expression2, options) {
570
+ this.tokens = Lexer_default.tokenize(expression2, options);
571
+ this.tokens.push({ type: "EOF" /* TOK_EOF */, value: "", start: expression2.length });
572
+ }
573
+ expression(rbp) {
574
+ if (this.maxDepth !== void 0 && this.depth >= this.maxDepth) {
575
+ throw new Error(`Expression exceeds maximum allowed depth of ${this.maxDepth}`);
576
+ }
577
+ this.depth += 1;
578
+ this.trackNode();
579
+ try {
580
+ const leftToken = this.lookaheadToken(0);
581
+ this.advance();
582
+ let left = this.nud(leftToken);
583
+ let currentTokenType = this.lookahead(0);
584
+ while (rbp < bindingPower[currentTokenType]) {
585
+ this.trackNode();
586
+ this.advance();
587
+ left = this.led(currentTokenType, left);
588
+ currentTokenType = this.lookahead(0);
589
+ }
590
+ return left;
591
+ } finally {
592
+ this.depth -= 1;
593
+ }
594
+ }
595
+ trackNode() {
596
+ this.nodeCount += 1;
597
+ if (this.maxNodes !== void 0 && this.nodeCount > this.maxNodes) {
598
+ throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`);
599
+ }
600
+ }
601
+ lookahead(offset) {
602
+ return this.tokens[this.index + offset].type;
603
+ }
604
+ lookaheadToken(offset) {
605
+ return this.tokens[this.index + offset];
606
+ }
607
+ advance() {
608
+ this.index += 1;
609
+ }
610
+ nud(token) {
611
+ switch (token.type) {
612
+ case "Variable" /* TOK_VARIABLE */:
613
+ return { type: "Variable", name: token.value };
614
+ case "Literal" /* TOK_LITERAL */:
615
+ return { type: "Literal", value: token.value };
616
+ case "UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */: {
617
+ if (_TokenParser.isKeyword(token, "let") && this.lookahead(0) === "Variable" /* TOK_VARIABLE */) {
618
+ return this.parseLetExpression();
619
+ } else {
620
+ return { type: "Field", name: token.value };
621
+ }
622
+ }
623
+ case "QuotedIdentifier" /* TOK_QUOTEDIDENTIFIER */:
624
+ if (this.lookahead(0) === "Lparen" /* TOK_LPAREN */) {
625
+ throw new Error("Syntax error: quoted identifier not allowed for function names.");
626
+ } else {
627
+ return { type: "Field", name: token.value };
628
+ }
629
+ case "Not" /* TOK_NOT */: {
630
+ const child = this.expression(bindingPower.Not);
631
+ return { type: "NotExpression", child };
632
+ }
633
+ case "Minus" /* TOK_MINUS */: {
634
+ const child = this.expression(bindingPower.Minus);
635
+ return {
636
+ type: "Unary",
637
+ operator: token.type,
638
+ operand: child
639
+ };
640
+ }
641
+ case "Plus" /* TOK_PLUS */: {
642
+ const child = this.expression(bindingPower.Plus);
643
+ return {
644
+ type: "Unary",
645
+ operator: token.type,
646
+ operand: child
647
+ };
648
+ }
649
+ case "Star" /* TOK_STAR */: {
650
+ const left = { type: "Identity" };
651
+ return { type: "ValueProjection", left, right: this.parseProjectionRHS(bindingPower.Star) };
652
+ }
653
+ case "Filter" /* TOK_FILTER */:
654
+ return this.led(token.type, { type: "Identity" });
655
+ case "Lbrace" /* TOK_LBRACE */:
656
+ return this.parseMultiselectHash();
657
+ case "Flatten" /* TOK_FLATTEN */: {
658
+ const left = {
659
+ type: "Flatten",
660
+ child: { type: "Identity" }
661
+ };
662
+ const right = this.parseProjectionRHS(bindingPower.Flatten);
663
+ return { type: "Projection", left, right };
664
+ }
665
+ case "Lbracket" /* TOK_LBRACKET */: {
666
+ if (this.lookahead(0) === "Number" /* TOK_NUMBER */ || this.lookahead(0) === "Colon" /* TOK_COLON */) {
667
+ const right = this.parseIndexExpression();
668
+ return this.projectIfSlice({ type: "Identity" }, right);
669
+ }
670
+ if (this.lookahead(0) === "Star" /* TOK_STAR */ && this.lookahead(1) === "Rbracket" /* TOK_RBRACKET */) {
671
+ this.advance();
672
+ this.advance();
673
+ const right = this.parseProjectionRHS(bindingPower.Star);
674
+ return {
675
+ left: { type: "Identity" },
676
+ right,
677
+ type: "Projection"
678
+ };
679
+ }
680
+ return this.parseMultiselectList();
681
+ }
682
+ case "Current" /* TOK_CURRENT */:
683
+ return { type: "Current" /* TOK_CURRENT */ };
684
+ case "Root" /* TOK_ROOT */:
685
+ return { type: "Root" /* TOK_ROOT */ };
686
+ case "Expref" /* TOK_EXPREF */: {
687
+ const child = this.expression(bindingPower.Expref);
688
+ return { type: "ExpressionReference", child };
689
+ }
690
+ case "Lparen" /* TOK_LPAREN */: {
691
+ const expression2 = this.expression(0);
692
+ this.match("Rparen" /* TOK_RPAREN */);
693
+ return expression2;
694
+ }
695
+ default:
696
+ this.errorToken(token);
697
+ }
698
+ }
699
+ led(tokenName, left) {
700
+ switch (tokenName) {
701
+ case "Question" /* TOK_QUESTION */: {
702
+ const trueExpr = this.expression(0);
703
+ this.match("Colon" /* TOK_COLON */);
704
+ const falseExpr = this.expression(0);
705
+ return {
706
+ type: "Ternary",
707
+ condition: left,
708
+ trueExpr,
709
+ falseExpr
710
+ };
711
+ }
712
+ case "Dot" /* TOK_DOT */: {
713
+ const rbp = bindingPower.Dot;
714
+ if (this.lookahead(0) !== "Star" /* TOK_STAR */) {
715
+ const right2 = this.parseDotRHS(rbp);
716
+ return { type: "Subexpression", left, right: right2 };
717
+ }
718
+ this.advance();
719
+ const right = this.parseProjectionRHS(rbp);
720
+ return { type: "ValueProjection", left, right };
721
+ }
722
+ case "Pipe" /* TOK_PIPE */: {
723
+ const right = this.expression(bindingPower.Pipe);
724
+ return { type: "Pipe", left, right };
725
+ }
726
+ case "Or" /* TOK_OR */: {
727
+ const right = this.expression(bindingPower.Or);
728
+ return { type: "OrExpression", left, right };
729
+ }
730
+ case "And" /* TOK_AND */: {
731
+ const right = this.expression(bindingPower.And);
732
+ return { type: "AndExpression", left, right };
733
+ }
734
+ case "Lparen" /* TOK_LPAREN */: {
735
+ if (left.type !== "Field") {
736
+ throw new Error("Syntax error: expected a Field node");
737
+ }
738
+ const name = left.name;
739
+ const args2 = this.parseCommaSeparatedExpressionsUntilToken("Rparen" /* TOK_RPAREN */);
740
+ const node = { name, type: "Function", children: args2 };
741
+ return node;
742
+ }
743
+ case "Filter" /* TOK_FILTER */: {
744
+ const condition = this.expression(0);
745
+ this.match("Rbracket" /* TOK_RBRACKET */);
746
+ const right = this.lookahead(0) === "Flatten" /* TOK_FLATTEN */ ? { type: "Identity" } : this.parseProjectionRHS(bindingPower.Filter);
747
+ return { type: "FilterProjection", left, right, condition };
748
+ }
749
+ case "Flatten" /* TOK_FLATTEN */: {
750
+ const leftNode = { type: "Flatten", child: left };
751
+ const right = this.parseProjectionRHS(bindingPower.Flatten);
752
+ return { type: "Projection", left: leftNode, right };
753
+ }
754
+ case "Assign" /* TOK_ASSIGN */: {
755
+ const leftNode = left;
756
+ const right = this.expression(0);
757
+ return {
758
+ type: "Binding",
759
+ variable: leftNode.name,
760
+ reference: right
761
+ };
762
+ }
763
+ case "EQ" /* TOK_EQ */:
764
+ case "NE" /* TOK_NE */:
765
+ case "GT" /* TOK_GT */:
766
+ case "GTE" /* TOK_GTE */:
767
+ case "LT" /* TOK_LT */:
768
+ case "LTE" /* TOK_LTE */:
769
+ return this.parseComparator(left, tokenName);
770
+ case "Plus" /* TOK_PLUS */:
771
+ case "Minus" /* TOK_MINUS */:
772
+ case "Multiply" /* TOK_MULTIPLY */:
773
+ case "Star" /* TOK_STAR */:
774
+ case "Divide" /* TOK_DIVIDE */:
775
+ case "Modulo" /* TOK_MODULO */:
776
+ case "Div" /* TOK_DIV */:
777
+ return this.parseArithmetic(left, tokenName);
778
+ case "Lbracket" /* TOK_LBRACKET */: {
779
+ const token = this.lookaheadToken(0);
780
+ if (token.type === "Number" /* TOK_NUMBER */ || token.type === "Colon" /* TOK_COLON */) {
781
+ const right2 = this.parseIndexExpression();
782
+ return this.projectIfSlice(left, right2);
783
+ }
784
+ this.match("Star" /* TOK_STAR */);
785
+ this.match("Rbracket" /* TOK_RBRACKET */);
786
+ const right = this.parseProjectionRHS(bindingPower.Star);
787
+ return { type: "Projection", left, right };
788
+ }
789
+ default:
790
+ return this.errorToken(this.lookaheadToken(0));
791
+ }
792
+ }
793
+ static isKeyword(token, keyword) {
794
+ return token.type === "UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */ && token.value === keyword;
795
+ }
796
+ match(tokenType) {
797
+ if (this.lookahead(0) === tokenType) {
798
+ this.advance();
799
+ return;
800
+ } else {
801
+ const token = this.lookaheadToken(0);
802
+ this.errorToken(token, `Syntax error: expected ${tokenType}, got: ${token.type}`);
803
+ }
804
+ }
805
+ errorToken(token, message = "") {
806
+ const error = new Error(message || `Syntax error: invalid token (${token.type}): "${token.value}"`);
807
+ error.name = "ParserError";
808
+ throw error;
809
+ }
810
+ parseIndexExpression() {
811
+ if (this.lookahead(0) === "Colon" /* TOK_COLON */ || this.lookahead(1) === "Colon" /* TOK_COLON */) {
812
+ return this.parseSliceExpression();
813
+ }
814
+ const value = Number(this.lookaheadToken(0).value);
815
+ this.advance();
816
+ this.match("Rbracket" /* TOK_RBRACKET */);
817
+ return { type: "Index", value };
818
+ }
819
+ projectIfSlice(left, right) {
820
+ const indexExpr = {
821
+ type: "IndexExpression",
822
+ left,
823
+ right
824
+ };
825
+ if (right.type === "Slice") {
826
+ const rhs = this.parseProjectionRHS(bindingPower.Star);
827
+ if (rhs.type === "Identity") {
828
+ return indexExpr;
829
+ }
830
+ return {
831
+ left: indexExpr,
832
+ right: rhs,
833
+ type: "Projection"
834
+ };
835
+ }
836
+ return indexExpr;
837
+ }
838
+ parseSliceExpression() {
839
+ const parts = [null, null, null];
840
+ let index = 0;
841
+ let current = this.lookaheadToken(0);
842
+ while (current.type != "Rbracket" /* TOK_RBRACKET */ && index < 3) {
843
+ if (current.type === "Colon" /* TOK_COLON */) {
844
+ index++;
845
+ if (index === 3) {
846
+ this.errorToken(this.lookaheadToken(0), "Syntax error, too many colons in slice expression");
847
+ }
848
+ this.advance();
849
+ } else if (current.type === "Number" /* TOK_NUMBER */) {
850
+ const part = this.lookaheadToken(0).value;
851
+ parts[index] = part;
852
+ this.advance();
853
+ } else {
854
+ const next = this.lookaheadToken(0);
855
+ this.errorToken(next, `Syntax error, unexpected token: ${next.value}(${next.type})`);
856
+ }
857
+ current = this.lookaheadToken(0);
858
+ }
859
+ this.match("Rbracket" /* TOK_RBRACKET */);
860
+ const [start, stop, step] = parts;
861
+ return { type: "Slice", start, stop, step };
862
+ }
863
+ parseLetExpression() {
864
+ const separated = this.parseCommaSeparatedExpressionsUntilKeyword("in");
865
+ const expression2 = this.expression(0);
866
+ const bindings = separated.map((binding) => binding);
867
+ return {
868
+ type: "LetExpression",
869
+ bindings,
870
+ expression: expression2
871
+ };
872
+ }
873
+ parseCommaSeparatedExpressionsUntilKeyword(keyword) {
874
+ return this.parseCommaSeparatedExpressionsUntil(
875
+ () => {
876
+ return _TokenParser.isKeyword(this.lookaheadToken(0), keyword);
877
+ },
878
+ () => {
879
+ this.advance();
880
+ }
881
+ );
882
+ }
883
+ parseCommaSeparatedExpressionsUntilToken(token) {
884
+ return this.parseCommaSeparatedExpressionsUntil(
885
+ () => {
886
+ return this.lookahead(0) === token;
887
+ },
888
+ () => {
889
+ return this.match(token);
890
+ }
891
+ );
892
+ }
893
+ parseCommaSeparatedExpressionsUntil(isEndToken, matchEndToken) {
894
+ const args2 = [];
895
+ let expression2;
896
+ while (!isEndToken()) {
897
+ expression2 = this.expression(0);
898
+ if (this.lookahead(0) === "Comma" /* TOK_COMMA */) {
899
+ this.match("Comma" /* TOK_COMMA */);
900
+ }
901
+ args2.push(expression2);
902
+ }
903
+ matchEndToken();
904
+ return args2;
905
+ }
906
+ parseComparator(left, comparator) {
907
+ const right = this.expression(bindingPower[comparator]);
908
+ return { type: "Comparator", name: comparator, left, right };
909
+ }
910
+ parseArithmetic(left, operator) {
911
+ const right = this.expression(bindingPower[operator]);
912
+ return { type: "Arithmetic", operator, left, right };
913
+ }
914
+ parseDotRHS(rbp) {
915
+ const lookahead = this.lookahead(0);
916
+ const exprTokens = ["UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */, "QuotedIdentifier" /* TOK_QUOTEDIDENTIFIER */, "Star" /* TOK_STAR */];
917
+ if (exprTokens.includes(lookahead)) {
918
+ return this.expression(rbp);
919
+ }
920
+ if (lookahead === "Lbracket" /* TOK_LBRACKET */) {
921
+ this.match("Lbracket" /* TOK_LBRACKET */);
922
+ return this.parseMultiselectList();
923
+ }
924
+ if (lookahead === "Lbrace" /* TOK_LBRACE */) {
925
+ this.match("Lbrace" /* TOK_LBRACE */);
926
+ return this.parseMultiselectHash();
927
+ }
928
+ const token = this.lookaheadToken(0);
929
+ this.errorToken(token, `Syntax error, unexpected token: ${token.value}(${token.type})`);
930
+ }
931
+ parseProjectionRHS(rbp) {
932
+ if (bindingPower[this.lookahead(0)] < 10) {
933
+ return { type: "Identity" };
934
+ }
935
+ if (this.lookahead(0) === "Lbracket" /* TOK_LBRACKET */) {
936
+ return this.expression(rbp);
937
+ }
938
+ if (this.lookahead(0) === "Filter" /* TOK_FILTER */) {
939
+ return this.expression(rbp);
940
+ }
941
+ if (this.lookahead(0) === "Dot" /* TOK_DOT */) {
942
+ this.match("Dot" /* TOK_DOT */);
943
+ return this.parseDotRHS(rbp);
944
+ }
945
+ const token = this.lookaheadToken(0);
946
+ this.errorToken(token, `Syntax error, unexpected token: ${token.value}(${token.type})`);
947
+ }
948
+ parseMultiselectList() {
949
+ const expressions = [];
950
+ while (this.lookahead(0) !== "Rbracket" /* TOK_RBRACKET */) {
951
+ const expression2 = this.expression(0);
952
+ expressions.push(expression2);
953
+ if (this.lookahead(0) === "Comma" /* TOK_COMMA */) {
954
+ this.match("Comma" /* TOK_COMMA */);
955
+ if (this.lookahead(0) === "Rbracket" /* TOK_RBRACKET */) {
956
+ throw new Error("Syntax error: unexpected token Rbracket");
957
+ }
958
+ }
959
+ }
960
+ this.match("Rbracket" /* TOK_RBRACKET */);
961
+ return { type: "MultiSelectList", children: expressions };
962
+ }
963
+ parseMultiselectHash() {
964
+ const pairs = [];
965
+ const identifierTypes = ["UnquotedIdentifier" /* TOK_UNQUOTEDIDENTIFIER */, "QuotedIdentifier" /* TOK_QUOTEDIDENTIFIER */];
966
+ let keyToken;
967
+ let keyName;
968
+ let value;
969
+ for (; ; ) {
970
+ keyToken = this.lookaheadToken(0);
971
+ if (!identifierTypes.includes(keyToken.type)) {
972
+ throw new Error(`Syntax error: expecting an identifier token, got: ${keyToken.type}`);
973
+ }
974
+ keyName = keyToken.value;
975
+ this.advance();
976
+ this.match("Colon" /* TOK_COLON */);
977
+ value = this.expression(0);
978
+ pairs.push({ value, type: "KeyValuePair", name: keyName });
979
+ if (this.lookahead(0) === "Comma" /* TOK_COMMA */) {
980
+ this.match("Comma" /* TOK_COMMA */);
981
+ } else if (this.lookahead(0) === "Rbrace" /* TOK_RBRACE */) {
982
+ this.match("Rbrace" /* TOK_RBRACE */);
983
+ break;
984
+ }
985
+ }
986
+ return { type: "MultiSelectHash", children: pairs };
987
+ }
988
+ };
989
+ var Parser = new TokenParser();
990
+ var Parser_default = Parser;
991
+
992
+ // src/utils/strings.ts
993
+ var findFirst = (subject, sub2, start, end) => {
994
+ if (!subject || !sub2) {
995
+ return null;
996
+ }
997
+ const s = Math.max(ensureInteger(start ?? 0), 0);
998
+ const e = Math.min(ensureInteger(end ?? subject.length), subject.length);
999
+ const offset = subject.slice(s, e).indexOf(sub2);
1000
+ return offset === -1 ? null : offset + s;
1001
+ };
1002
+ var findLast = (subject, sub2, start, end) => {
1003
+ if (!subject || !sub2) {
1004
+ return null;
1005
+ }
1006
+ const s = Math.max(ensureInteger(start ?? 0), 0);
1007
+ const e = Math.min(ensureInteger(end ?? subject.length), subject.length);
1008
+ const offset = subject.slice(s, e).lastIndexOf(sub2);
1009
+ return offset === -1 ? null : offset + s;
1010
+ };
1011
+ var lower = (subject) => subject.toLowerCase();
1012
+ var ensurePadFuncParams = (name, width, padding = " ") => {
1013
+ if (padding.length > 1) {
1014
+ throw new Error(`invalid value, ${name} expects its 'pad' parameter to be a valid string with a single codepoint`);
1015
+ }
1016
+ ensurePositiveInteger(width);
1017
+ return padding;
1018
+ };
1019
+ var padLeft = (subject, width, padding) => {
1020
+ padding = ensurePadFuncParams("pad_left", width, padding);
1021
+ return subject && subject.padStart(width, padding) || "";
1022
+ };
1023
+ var padRight = (subject, width, padding) => {
1024
+ padding = ensurePadFuncParams("pad_right", width, padding);
1025
+ return subject && subject.padEnd(width, padding) || "";
1026
+ };
1027
+ var replace = (subject, string, by, count) => {
1028
+ if (count === 0) {
1029
+ return subject;
1030
+ }
1031
+ if (!count) {
1032
+ return subject.split(string).join(by);
1033
+ }
1034
+ ensurePositiveInteger(count);
1035
+ while (count-- > 0 && subject.includes(string)) {
1036
+ subject = subject.replace(string, by);
1037
+ }
1038
+ return subject;
1039
+ };
1040
+ var split = (subject, search2, count) => {
1041
+ if (subject.length == 0 && search2.length === 0) {
1042
+ return [];
1043
+ }
1044
+ if (count === null || count === void 0) {
1045
+ return subject.split(search2);
1046
+ }
1047
+ ensurePositiveInteger(count);
1048
+ if (count === 0) {
1049
+ return [subject];
1050
+ }
1051
+ const split2 = subject.split(search2);
1052
+ return [...split2.slice(0, count), split2.slice(count).join(search2)];
1053
+ };
1054
+ var trim = (subject, chars) => {
1055
+ return trimLeft(trimRight(subject, chars), chars);
1056
+ };
1057
+ var trimLeft = (subject, chars) => {
1058
+ return trimImpl(subject, (list) => new RegExp(`^[${list}]*(.*?)`), chars);
1059
+ };
1060
+ var trimRight = (subject, chars) => {
1061
+ return trimImpl(subject, (list) => new RegExp(`(.*?)[${list}]*$`), chars);
1062
+ };
1063
+ var trimImpl = (subject, regExper, chars) => {
1064
+ const pattern = chars ? chars.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&") : "\\s\x85";
1065
+ return subject.replace(regExper(pattern), "$1");
1066
+ };
1067
+ var upper = (subject) => subject.toUpperCase();
1068
+
1069
+ // src/utils/text.ts
1070
+ var Text = class _Text {
1071
+ _text;
1072
+ constructor(text) {
1073
+ this._text = text;
1074
+ }
1075
+ get string() {
1076
+ return this._text;
1077
+ }
1078
+ get length() {
1079
+ let count = 0;
1080
+ for (const _ of this._text) {
1081
+ count += 1;
1082
+ }
1083
+ return count;
1084
+ }
1085
+ compareTo(other) {
1086
+ return _Text.compare(this, new _Text(other));
1087
+ }
1088
+ static get comparer() {
1089
+ const stringComparer = (left, right) => {
1090
+ return new _Text(left).compareTo(right);
1091
+ };
1092
+ return stringComparer;
1093
+ }
1094
+ static compare(left, right) {
1095
+ const leftCp = left.codePoints;
1096
+ const rightCp = right.codePoints;
1097
+ for (let index = 0; index < Math.min(leftCp.length, rightCp.length); index++) {
1098
+ if (leftCp[index] === rightCp[index]) {
1099
+ continue;
1100
+ }
1101
+ return leftCp[index] - rightCp[index] > 0 ? 1 : -1;
1102
+ }
1103
+ return leftCp.length - rightCp.length > 0 ? 1 : -1;
1104
+ }
1105
+ reverse() {
1106
+ return String.fromCodePoint(...this.codePoints.reverse());
1107
+ }
1108
+ get codePoints() {
1109
+ const array = [...this._text].map((s) => s.codePointAt(0));
1110
+ return array;
1111
+ }
1112
+ };
1113
+
1114
+ // src/Runtime.ts
1115
+ var createMathFunction = (mathFn) => ([value]) => mathFn(value);
1116
+ var createStringFunction = (stringFn) => ([subject]) => stringFn(subject);
1117
+ var createObjectFunction = (objFn) => ([obj]) => objFn(obj);
1118
+ var ARRAY_SUBTYPES = {
1119
+ [8 /* TYPE_ARRAY_NUMBER */]: 0 /* TYPE_NUMBER */,
1120
+ [10 /* TYPE_ARRAY_OBJECT */]: 4 /* TYPE_OBJECT */,
1121
+ [9 /* TYPE_ARRAY_STRING */]: 2 /* TYPE_STRING */,
1122
+ [11 /* TYPE_ARRAY_ARRAY */]: 3 /* TYPE_ARRAY */
1123
+ };
1124
+ var Runtime = class {
1125
+ _interpreter;
1126
+ _functionTable;
1127
+ _customFunctions = /* @__PURE__ */ new Set();
1128
+ TYPE_NAME_TABLE = Object.freeze({
1129
+ [0 /* TYPE_NUMBER */]: "number",
1130
+ [1 /* TYPE_ANY */]: "any",
1131
+ [2 /* TYPE_STRING */]: "string",
1132
+ [3 /* TYPE_ARRAY */]: "array",
1133
+ [4 /* TYPE_OBJECT */]: "object",
1134
+ [5 /* TYPE_BOOLEAN */]: "boolean",
1135
+ [6 /* TYPE_EXPREF */]: "expression",
1136
+ [7 /* TYPE_NULL */]: "null",
1137
+ [8 /* TYPE_ARRAY_NUMBER */]: "Array<number>",
1138
+ [10 /* TYPE_ARRAY_OBJECT */]: "Array<object>",
1139
+ [9 /* TYPE_ARRAY_STRING */]: "Array<string>",
1140
+ [11 /* TYPE_ARRAY_ARRAY */]: "Array<Array<any>>"
1141
+ });
1142
+ constructor(interpreter) {
1143
+ this._interpreter = interpreter;
1144
+ this._functionTable = this.buildFunctionTable();
1145
+ }
1146
+ buildFunctionTable() {
1147
+ return {
1148
+ // Math functions
1149
+ abs: { _func: createMathFunction(Math.abs), _signature: [{ types: [0 /* TYPE_NUMBER */] }] },
1150
+ ceil: { _func: createMathFunction(Math.ceil), _signature: [{ types: [0 /* TYPE_NUMBER */] }] },
1151
+ floor: { _func: createMathFunction(Math.floor), _signature: [{ types: [0 /* TYPE_NUMBER */] }] },
1152
+ // String functions
1153
+ lower: { _func: createStringFunction(lower), _signature: [{ types: [2 /* TYPE_STRING */] }] },
1154
+ upper: { _func: createStringFunction(upper), _signature: [{ types: [2 /* TYPE_STRING */] }] },
1155
+ // Object functions
1156
+ keys: { _func: createObjectFunction(Object.keys), _signature: [{ types: [4 /* TYPE_OBJECT */] }] },
1157
+ values: { _func: createObjectFunction(Object.values), _signature: [{ types: [4 /* TYPE_OBJECT */] }] },
1158
+ // Complex functions that need custom implementations
1159
+ avg: { _func: this.functionAvg, _signature: [{ types: [8 /* TYPE_ARRAY_NUMBER */] }] },
1160
+ contains: {
1161
+ _func: this.functionContains,
1162
+ _signature: [
1163
+ { types: [2 /* TYPE_STRING */, 3 /* TYPE_ARRAY */] },
1164
+ { types: [1 /* TYPE_ANY */] }
1165
+ ]
1166
+ },
1167
+ ends_with: {
1168
+ _func: this.functionEndsWith,
1169
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [2 /* TYPE_STRING */] }]
1170
+ },
1171
+ find_first: {
1172
+ _func: this.functionFindFirst,
1173
+ _signature: [
1174
+ { types: [2 /* TYPE_STRING */] },
1175
+ { types: [2 /* TYPE_STRING */] },
1176
+ { types: [0 /* TYPE_NUMBER */], optional: true },
1177
+ { types: [0 /* TYPE_NUMBER */], optional: true }
1178
+ ]
1179
+ },
1180
+ find_last: {
1181
+ _func: this.functionFindLast,
1182
+ _signature: [
1183
+ { types: [2 /* TYPE_STRING */] },
1184
+ { types: [2 /* TYPE_STRING */] },
1185
+ { types: [0 /* TYPE_NUMBER */], optional: true },
1186
+ { types: [0 /* TYPE_NUMBER */], optional: true }
1187
+ ]
1188
+ },
1189
+ from_items: { _func: this.functionFromItems, _signature: [{ types: [11 /* TYPE_ARRAY_ARRAY */] }] },
1190
+ group_by: {
1191
+ _func: this.functionGroupBy,
1192
+ _signature: [{ types: [3 /* TYPE_ARRAY */] }, { types: [6 /* TYPE_EXPREF */] }]
1193
+ },
1194
+ items: { _func: this.functionItems, _signature: [{ types: [4 /* TYPE_OBJECT */] }] },
1195
+ join: {
1196
+ _func: this.functionJoin,
1197
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [9 /* TYPE_ARRAY_STRING */] }]
1198
+ },
1199
+ length: {
1200
+ _func: this.functionLength,
1201
+ _signature: [{ types: [2 /* TYPE_STRING */, 3 /* TYPE_ARRAY */, 4 /* TYPE_OBJECT */] }]
1202
+ },
1203
+ map: {
1204
+ _func: this.functionMap,
1205
+ _signature: [{ types: [6 /* TYPE_EXPREF */] }, { types: [3 /* TYPE_ARRAY */] }]
1206
+ },
1207
+ max: {
1208
+ _func: this.functionMax,
1209
+ _signature: [{ types: [8 /* TYPE_ARRAY_NUMBER */, 9 /* TYPE_ARRAY_STRING */] }]
1210
+ },
1211
+ max_by: {
1212
+ _func: this.functionMaxBy,
1213
+ _signature: [{ types: [3 /* TYPE_ARRAY */] }, { types: [6 /* TYPE_EXPREF */] }]
1214
+ },
1215
+ merge: { _func: this.functionMerge, _signature: [{ types: [4 /* TYPE_OBJECT */], variadic: true }] },
1216
+ min: {
1217
+ _func: this.functionMin,
1218
+ _signature: [{ types: [8 /* TYPE_ARRAY_NUMBER */, 9 /* TYPE_ARRAY_STRING */] }]
1219
+ },
1220
+ min_by: {
1221
+ _func: this.functionMinBy,
1222
+ _signature: [{ types: [3 /* TYPE_ARRAY */] }, { types: [6 /* TYPE_EXPREF */] }]
1223
+ },
1224
+ not_null: { _func: this.functionNotNull, _signature: [{ types: [1 /* TYPE_ANY */], variadic: true }] },
1225
+ pad_left: {
1226
+ _func: this.functionPadLeft,
1227
+ _signature: [
1228
+ { types: [2 /* TYPE_STRING */] },
1229
+ { types: [0 /* TYPE_NUMBER */] },
1230
+ { types: [2 /* TYPE_STRING */], optional: true }
1231
+ ]
1232
+ },
1233
+ pad_right: {
1234
+ _func: this.functionPadRight,
1235
+ _signature: [
1236
+ { types: [2 /* TYPE_STRING */] },
1237
+ { types: [0 /* TYPE_NUMBER */] },
1238
+ { types: [2 /* TYPE_STRING */], optional: true }
1239
+ ]
1240
+ },
1241
+ replace: {
1242
+ _func: this.functionReplace,
1243
+ _signature: [
1244
+ { types: [2 /* TYPE_STRING */] },
1245
+ { types: [2 /* TYPE_STRING */] },
1246
+ { types: [2 /* TYPE_STRING */] },
1247
+ { types: [0 /* TYPE_NUMBER */], optional: true }
1248
+ ]
1249
+ },
1250
+ reverse: {
1251
+ _func: this.functionReverse,
1252
+ _signature: [{ types: [2 /* TYPE_STRING */, 3 /* TYPE_ARRAY */] }]
1253
+ },
1254
+ sort: {
1255
+ _func: this.functionSort,
1256
+ _signature: [{ types: [9 /* TYPE_ARRAY_STRING */, 8 /* TYPE_ARRAY_NUMBER */] }]
1257
+ },
1258
+ sort_by: {
1259
+ _func: this.functionSortBy,
1260
+ _signature: [{ types: [3 /* TYPE_ARRAY */] }, { types: [6 /* TYPE_EXPREF */] }]
1261
+ },
1262
+ split: {
1263
+ _func: this.functionSplit,
1264
+ _signature: [
1265
+ { types: [2 /* TYPE_STRING */] },
1266
+ { types: [2 /* TYPE_STRING */] },
1267
+ { types: [0 /* TYPE_NUMBER */], optional: true }
1268
+ ]
1269
+ },
1270
+ starts_with: {
1271
+ _func: this.functionStartsWith,
1272
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [2 /* TYPE_STRING */] }]
1273
+ },
1274
+ sum: { _func: this.functionSum, _signature: [{ types: [8 /* TYPE_ARRAY_NUMBER */] }] },
1275
+ to_array: { _func: this.functionToArray, _signature: [{ types: [1 /* TYPE_ANY */] }] },
1276
+ to_number: { _func: this.functionToNumber, _signature: [{ types: [1 /* TYPE_ANY */] }] },
1277
+ to_string: { _func: this.functionToString, _signature: [{ types: [1 /* TYPE_ANY */] }] },
1278
+ trim: {
1279
+ _func: this.functionTrim,
1280
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [2 /* TYPE_STRING */], optional: true }]
1281
+ },
1282
+ trim_left: {
1283
+ _func: this.functionTrimLeft,
1284
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [2 /* TYPE_STRING */], optional: true }]
1285
+ },
1286
+ trim_right: {
1287
+ _func: this.functionTrimRight,
1288
+ _signature: [{ types: [2 /* TYPE_STRING */] }, { types: [2 /* TYPE_STRING */], optional: true }]
1289
+ },
1290
+ type: { _func: this.functionType, _signature: [{ types: [1 /* TYPE_ANY */] }] },
1291
+ zip: { _func: this.functionZip, _signature: [{ types: [3 /* TYPE_ARRAY */], variadic: true }] }
1292
+ };
1293
+ }
1294
+ /**
1295
+ * Enhanced registerFunction with backward compatibility and new options
1296
+ * @deprecated Use register() method for enhanced functionality
1297
+ */
1298
+ registerFunction(name, customFunction, signature, options) {
1299
+ const result = this._registerInternal(name, customFunction, signature, options);
1300
+ if (!result.success) {
1301
+ throw new Error(result.message);
1302
+ }
1303
+ }
1304
+ /**
1305
+ * Internal registration method that bypasses TypeScript type checking
1306
+ */
1307
+ _registerInternal(name, customFunction, signature, options = {}) {
1308
+ if (!name || typeof name !== "string" || name.trim() === "") {
1309
+ return {
1310
+ success: false,
1311
+ reason: "invalid-name",
1312
+ message: "Function name must be a non-empty string"
1313
+ };
1314
+ }
1315
+ try {
1316
+ this.validateInputSignatures(name, signature);
1317
+ } catch (error) {
1318
+ return {
1319
+ success: false,
1320
+ reason: "invalid-signature",
1321
+ message: error instanceof Error ? error.message : "Invalid function signature"
1322
+ };
1323
+ }
1324
+ const { override = false, warn = false } = options;
1325
+ const exists = name in this._functionTable;
1326
+ if (exists && !override) {
1327
+ return {
1328
+ success: false,
1329
+ reason: "already-exists",
1330
+ message: `Function already defined: ${name}(). Use { override: true } to replace it.`
1331
+ };
1332
+ }
1333
+ if (exists && override && warn) {
1334
+ console.warn(`Warning: Overriding existing function: ${name}()`);
1335
+ }
1336
+ this._functionTable[name] = {
1337
+ _func: customFunction.bind(this),
1338
+ _signature: signature
1339
+ };
1340
+ this._customFunctions.add(name);
1341
+ const message = exists ? `Function ${name}() overridden successfully` : `Function ${name}() registered successfully`;
1342
+ return { success: true, message };
1343
+ }
1344
+ /**
1345
+ * Register a new function with enhanced options and type safety
1346
+ */
1347
+ register(name, customFunction, signature, options = {}) {
1348
+ return this._registerInternal(name, customFunction, signature, options);
1349
+ }
1350
+ /**
1351
+ * Unregister a custom function (built-in functions cannot be unregistered)
1352
+ */
1353
+ unregister(name) {
1354
+ if (!this._customFunctions.has(name)) {
1355
+ return false;
1356
+ }
1357
+ delete this._functionTable[name];
1358
+ this._customFunctions.delete(name);
1359
+ return true;
1360
+ }
1361
+ /**
1362
+ * Check if a function is registered
1363
+ */
1364
+ isRegistered(name) {
1365
+ return name in this._functionTable;
1366
+ }
1367
+ /**
1368
+ * Get list of all registered function names
1369
+ */
1370
+ getRegistered() {
1371
+ return Object.keys(this._functionTable);
1372
+ }
1373
+ /**
1374
+ * Get list of custom (non-built-in) function names
1375
+ */
1376
+ getCustomFunctions() {
1377
+ return Array.from(this._customFunctions);
1378
+ }
1379
+ /**
1380
+ * Clear all custom functions (built-in functions remain)
1381
+ */
1382
+ clearCustomFunctions() {
1383
+ for (const name of this._customFunctions) {
1384
+ delete this._functionTable[name];
1385
+ }
1386
+ this._customFunctions.clear();
1387
+ }
1388
+ callFunction(name, resolvedArgs) {
1389
+ const functionEntry = this._functionTable[name];
1390
+ if (functionEntry === void 0) {
1391
+ throw new Error(`Unknown function: ${name}()`);
1392
+ }
1393
+ this.validateArgs(name, resolvedArgs, functionEntry._signature);
1394
+ return functionEntry._func.call(this, resolvedArgs);
1395
+ }
1396
+ validateInputSignatures(name, signature) {
1397
+ for (let i = 0; i < signature.length; i += 1) {
1398
+ if ("variadic" in signature[i] && i !== signature.length - 1) {
1399
+ throw new Error(`Invalid arity: ${name}() 'variadic' argument ${i + 1} must occur last`);
1400
+ }
1401
+ }
1402
+ }
1403
+ validateArgs(name, args2, signature) {
1404
+ this.validateInputSignatures(name, signature);
1405
+ this.validateArity(name, args2, signature);
1406
+ this.validateTypes(name, args2, signature);
1407
+ }
1408
+ validateArity(name, args2, signature) {
1409
+ const numberOfRequiredArgs = signature.filter((argSignature) => !(argSignature.optional ?? false)).length;
1410
+ const lastArgIsVariadic = signature[signature.length - 1]?.variadic ?? false;
1411
+ const tooFewArgs = args2.length < numberOfRequiredArgs;
1412
+ const tooManyArgs = args2.length > signature.length;
1413
+ if (lastArgIsVariadic && tooFewArgs || !lastArgIsVariadic && (tooFewArgs || tooManyArgs)) {
1414
+ const tooFewModifier = tooFewArgs && (!lastArgIsVariadic && numberOfRequiredArgs > 1 || lastArgIsVariadic) ? "at least " : "";
1415
+ const pluralized = signature.length > 1;
1416
+ throw new Error(
1417
+ `Invalid arity: ${name}() takes ${tooFewModifier}${numberOfRequiredArgs} argument${pluralized && "s" || ""} but received ${args2.length}`
1418
+ );
1419
+ }
1420
+ }
1421
+ validateTypes(name, args2, signature) {
1422
+ for (let i = 0; i < signature.length; i += 1) {
1423
+ const currentSpec = signature[i].types;
1424
+ const actualType = this.getTypeName(args2[i]);
1425
+ if (actualType === void 0) {
1426
+ continue;
1427
+ }
1428
+ const typeMatched = currentSpec.some((expectedType) => this.typeMatches(actualType, expectedType, args2[i]));
1429
+ if (!typeMatched) {
1430
+ const expected = currentSpec.map((typeId) => this.TYPE_NAME_TABLE[typeId]).join(" | ");
1431
+ throw new Error(
1432
+ `Invalid type: ${name}() expected argument ${i + 1} to be type (${expected}) but received type ${this.TYPE_NAME_TABLE[actualType]} instead.`
1433
+ );
1434
+ }
1435
+ }
1436
+ }
1437
+ typeMatches(actual, expected, argValue) {
1438
+ if (expected === 1 /* TYPE_ANY */) {
1439
+ return true;
1440
+ }
1441
+ const subtype = ARRAY_SUBTYPES[expected];
1442
+ if (subtype !== void 0) {
1443
+ if (actual !== 3 /* TYPE_ARRAY */) {
1444
+ return false;
1445
+ }
1446
+ const array = argValue;
1447
+ return array.every((item) => {
1448
+ const typeName = this.getTypeName(item);
1449
+ return typeName === void 0 || this.typeMatches(typeName, subtype, item);
1450
+ });
1451
+ }
1452
+ return actual === expected;
1453
+ }
1454
+ getTypeName(obj) {
1455
+ if (obj === null) {
1456
+ return 7 /* TYPE_NULL */;
1457
+ }
1458
+ if (typeof obj === "string") {
1459
+ return 2 /* TYPE_STRING */;
1460
+ }
1461
+ if (typeof obj === "number") {
1462
+ return 0 /* TYPE_NUMBER */;
1463
+ }
1464
+ if (typeof obj === "boolean") {
1465
+ return 5 /* TYPE_BOOLEAN */;
1466
+ }
1467
+ if (Array.isArray(obj)) {
1468
+ return 3 /* TYPE_ARRAY */;
1469
+ }
1470
+ if (typeof obj === "object") {
1471
+ if (obj.expref) {
1472
+ return 6 /* TYPE_EXPREF */;
1473
+ }
1474
+ return 4 /* TYPE_OBJECT */;
1475
+ }
1476
+ return;
1477
+ }
1478
+ createKeyFunction(exprefNode, allowedTypes) {
1479
+ const interpreter = this._interpreter;
1480
+ const keyFunc = (x) => {
1481
+ const current = interpreter.visit(exprefNode, x);
1482
+ if (!allowedTypes.includes(this.getTypeName(current))) {
1483
+ const msg = `Invalid type: expected one of (${allowedTypes.map((t) => this.TYPE_NAME_TABLE[t]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(current)]}`;
1484
+ throw new Error(msg);
1485
+ }
1486
+ return current;
1487
+ };
1488
+ return keyFunc;
1489
+ }
1490
+ functionAvg = ([inputArray]) => {
1491
+ if (!inputArray || inputArray.length == 0) {
1492
+ return null;
1493
+ }
1494
+ let sum = 0;
1495
+ for (let i = 0; i < inputArray.length; i += 1) {
1496
+ sum += inputArray[i];
1497
+ }
1498
+ return sum / inputArray.length;
1499
+ };
1500
+ functionContains = ([
1501
+ searchable,
1502
+ searchValue
1503
+ ]) => {
1504
+ if (Array.isArray(searchable)) {
1505
+ const array = searchable;
1506
+ return array.includes(searchValue);
1507
+ }
1508
+ if (typeof searchable === "string") {
1509
+ const text = searchable;
1510
+ if (typeof searchValue === "string") {
1511
+ return text.includes(searchValue);
1512
+ }
1513
+ }
1514
+ return null;
1515
+ };
1516
+ functionEndsWith = ([searchStr, suffix]) => {
1517
+ return searchStr.endsWith(suffix);
1518
+ };
1519
+ functionFindFirst = this.createFindFunction(findFirst);
1520
+ functionFindLast = this.createFindFunction(findLast);
1521
+ createFindFunction(findFn) {
1522
+ return (resolvedArgs) => {
1523
+ const subject = resolvedArgs[0];
1524
+ const search2 = resolvedArgs[1];
1525
+ const start = resolvedArgs.length > 2 ? resolvedArgs[2] : void 0;
1526
+ const end = resolvedArgs.length > 3 ? resolvedArgs[3] : void 0;
1527
+ return findFn(subject, search2, start, end);
1528
+ };
1529
+ }
1530
+ functionFromItems = ([array]) => {
1531
+ for (const pair of array) {
1532
+ if (pair.length !== 2 || typeof pair[0] !== "string") {
1533
+ throw new Error("invalid value, each array must contain two elements, a pair of string and value");
1534
+ }
1535
+ }
1536
+ return Object.fromEntries(array);
1537
+ };
1538
+ functionGroupBy = ([array, exprefNode]) => {
1539
+ const keyFunction = this.createKeyFunction(exprefNode, [2 /* TYPE_STRING */]);
1540
+ const groups = {};
1541
+ for (const item of array) {
1542
+ const key = keyFunction(item);
1543
+ if (!groups[key]) {
1544
+ groups[key] = [];
1545
+ }
1546
+ groups[key].push(item);
1547
+ }
1548
+ return groups;
1549
+ };
1550
+ functionItems = ([inputValue]) => {
1551
+ return Object.entries(inputValue);
1552
+ };
1553
+ functionJoin = (resolvedArgs) => {
1554
+ const [joinChar, listJoin] = resolvedArgs;
1555
+ return listJoin.join(joinChar);
1556
+ };
1557
+ functionLength = ([inputValue]) => {
1558
+ if (typeof inputValue === "string") {
1559
+ return new Text(inputValue).length;
1560
+ }
1561
+ if (Array.isArray(inputValue)) {
1562
+ return inputValue.length;
1563
+ }
1564
+ return Object.keys(inputValue).length;
1565
+ };
1566
+ functionMap = ([exprefNode, elements]) => {
1567
+ if (!this._interpreter) {
1568
+ return [];
1569
+ }
1570
+ const mapped = [];
1571
+ const interpreter = this._interpreter;
1572
+ for (let i = 0; i < elements.length; i += 1) {
1573
+ mapped.push(interpreter.visit(exprefNode, elements[i]));
1574
+ }
1575
+ return mapped;
1576
+ };
1577
+ functionMax = ([inputValue]) => {
1578
+ if (!inputValue.length) {
1579
+ return null;
1580
+ }
1581
+ const typeName = this.getTypeName(inputValue[0]);
1582
+ if (typeName === 0 /* TYPE_NUMBER */) {
1583
+ return Math.max(...inputValue);
1584
+ }
1585
+ const elements = inputValue;
1586
+ let maxElement = elements[0];
1587
+ for (let i = 1; i < elements.length; i += 1) {
1588
+ if (maxElement.localeCompare(elements[i]) < 0) {
1589
+ maxElement = elements[i];
1590
+ }
1591
+ }
1592
+ return maxElement;
1593
+ };
1594
+ functionMaxBy = (resolvedArgs) => {
1595
+ const exprefNode = resolvedArgs[1];
1596
+ const resolvedArray = resolvedArgs[0];
1597
+ const keyFunction = this.createKeyFunction(exprefNode, [0 /* TYPE_NUMBER */, 2 /* TYPE_STRING */]);
1598
+ let maxNumber = -Infinity;
1599
+ let maxRecord;
1600
+ let current;
1601
+ for (let i = 0; i < resolvedArray.length; i += 1) {
1602
+ current = keyFunction && keyFunction(resolvedArray[i]);
1603
+ if (current !== void 0 && current > maxNumber) {
1604
+ maxNumber = current;
1605
+ maxRecord = resolvedArray[i];
1606
+ }
1607
+ }
1608
+ return maxRecord || null;
1609
+ };
1610
+ functionMerge = (resolvedArgs) => {
1611
+ return Object.assign({}, ...resolvedArgs);
1612
+ };
1613
+ functionMin = ([inputValue]) => {
1614
+ if (!inputValue.length) {
1615
+ return null;
1616
+ }
1617
+ const typeName = this.getTypeName(inputValue[0]);
1618
+ if (typeName === 0 /* TYPE_NUMBER */) {
1619
+ return Math.min(...inputValue);
1620
+ }
1621
+ const elements = inputValue;
1622
+ let minElement = elements[0];
1623
+ for (let i = 1; i < elements.length; i += 1) {
1624
+ if (elements[i].localeCompare(minElement) < 0) {
1625
+ minElement = elements[i];
1626
+ }
1627
+ }
1628
+ return minElement;
1629
+ };
1630
+ functionMinBy = (resolvedArgs) => {
1631
+ const exprefNode = resolvedArgs[1];
1632
+ const resolvedArray = resolvedArgs[0];
1633
+ const keyFunction = this.createKeyFunction(exprefNode, [0 /* TYPE_NUMBER */, 2 /* TYPE_STRING */]);
1634
+ let minNumber = Infinity;
1635
+ let minRecord;
1636
+ let current;
1637
+ for (let i = 0; i < resolvedArray.length; i += 1) {
1638
+ current = keyFunction && keyFunction(resolvedArray[i]);
1639
+ if (current !== void 0 && current < minNumber) {
1640
+ minNumber = current;
1641
+ minRecord = resolvedArray[i];
1642
+ }
1643
+ }
1644
+ return minRecord || null;
1645
+ };
1646
+ functionNotNull = (resolvedArgs) => {
1647
+ return resolvedArgs.find((arg) => arg !== null) ?? null;
1648
+ };
1649
+ functionPadLeft = this.createPadFunction(padLeft);
1650
+ functionPadRight = this.createPadFunction(padRight);
1651
+ createPadFunction(padFn) {
1652
+ return (resolvedArgs) => {
1653
+ const subject = resolvedArgs[0];
1654
+ const width = resolvedArgs[1];
1655
+ const padding = resolvedArgs.length > 2 ? resolvedArgs[2] : void 0;
1656
+ return padFn(subject, width, padding);
1657
+ };
1658
+ }
1659
+ functionReplace = (resolvedArgs) => {
1660
+ const subject = resolvedArgs[0];
1661
+ const string = resolvedArgs[1];
1662
+ const by = resolvedArgs[2];
1663
+ return replace(subject, string, by, resolvedArgs.length > 3 ? resolvedArgs[3] : void 0);
1664
+ };
1665
+ functionSplit = (resolvedArgs) => {
1666
+ const subject = resolvedArgs[0];
1667
+ const search2 = resolvedArgs[1];
1668
+ return split(subject, search2, resolvedArgs.length > 2 ? resolvedArgs[2] : void 0);
1669
+ };
1670
+ functionReverse = ([inputValue]) => {
1671
+ const typeName = this.getTypeName(inputValue);
1672
+ if (typeName === 2 /* TYPE_STRING */) {
1673
+ return new Text(inputValue).reverse();
1674
+ }
1675
+ const reversedArray = [...inputValue];
1676
+ reversedArray.reverse();
1677
+ return reversedArray;
1678
+ };
1679
+ functionSort = ([inputValue]) => {
1680
+ if (inputValue.length <= 1) {
1681
+ return inputValue;
1682
+ }
1683
+ if (typeof inputValue[0] === "string") {
1684
+ return [...inputValue].sort(Text.comparer);
1685
+ }
1686
+ return [...inputValue].sort();
1687
+ };
1688
+ functionSortBy = (resolvedArgs) => {
1689
+ const sortedArray = [...resolvedArgs[0]];
1690
+ if (sortedArray.length <= 1) {
1691
+ return sortedArray;
1692
+ }
1693
+ const interpreter = this._interpreter;
1694
+ const exprefNode = resolvedArgs[1];
1695
+ const requiredType = this.getTypeName(interpreter.visit(exprefNode, sortedArray[0]));
1696
+ if (requiredType !== void 0 && ![0 /* TYPE_NUMBER */, 2 /* TYPE_STRING */].includes(requiredType)) {
1697
+ throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[requiredType]})`);
1698
+ }
1699
+ function throwInvalidTypeError(rt, item) {
1700
+ throw new Error(
1701
+ `Invalid type: expected (${rt.TYPE_NAME_TABLE[requiredType]}), received ${rt.TYPE_NAME_TABLE[rt.getTypeName(item)]}`
1702
+ );
1703
+ }
1704
+ return sortedArray.sort((a, b) => {
1705
+ const exprA = interpreter.visit(exprefNode, a);
1706
+ const exprB = interpreter.visit(exprefNode, b);
1707
+ if (this.getTypeName(exprA) !== requiredType) {
1708
+ throwInvalidTypeError(this, exprA);
1709
+ } else if (this.getTypeName(exprB) !== requiredType) {
1710
+ throwInvalidTypeError(this, exprB);
1711
+ }
1712
+ if (requiredType === 2 /* TYPE_STRING */) {
1713
+ return Text.comparer(exprA, exprB);
1714
+ }
1715
+ return exprA - exprB;
1716
+ });
1717
+ };
1718
+ functionStartsWith = ([searchable, searchStr]) => {
1719
+ return searchable.startsWith(searchStr);
1720
+ };
1721
+ functionSum = ([inputValue]) => {
1722
+ return inputValue.reduce((x, y) => x + y, 0);
1723
+ };
1724
+ functionToArray = ([inputValue]) => {
1725
+ return Array.isArray(inputValue) ? inputValue : [inputValue];
1726
+ };
1727
+ functionToNumber = ([inputValue]) => {
1728
+ const typeName = this.getTypeName(inputValue);
1729
+ let convertedValue;
1730
+ if (typeName === 0 /* TYPE_NUMBER */) {
1731
+ return inputValue;
1732
+ }
1733
+ if (typeName === 2 /* TYPE_STRING */) {
1734
+ convertedValue = +inputValue;
1735
+ if (!isNaN(convertedValue)) {
1736
+ return convertedValue;
1737
+ }
1738
+ }
1739
+ return null;
1740
+ };
1741
+ functionToString = ([inputValue]) => {
1742
+ return typeof inputValue === "string" ? inputValue : JSON.stringify(inputValue);
1743
+ };
1744
+ functionTrim = this.createTrimFunction(trim);
1745
+ functionTrimLeft = this.createTrimFunction(trimLeft);
1746
+ functionTrimRight = this.createTrimFunction(trimRight);
1747
+ createTrimFunction(trimFn) {
1748
+ return (resolvedArgs) => {
1749
+ const subject = resolvedArgs[0];
1750
+ const chars = resolvedArgs.length > 1 ? resolvedArgs[1] : void 0;
1751
+ return trimFn(subject, chars);
1752
+ };
1753
+ }
1754
+ functionType = ([inputValue]) => {
1755
+ const type = this.getTypeName(inputValue);
1756
+ const name = type !== void 0 ? this.TYPE_NAME_TABLE[type] : void 0;
1757
+ if (!name) {
1758
+ throw new Error("invalid-type");
1759
+ }
1760
+ return name;
1761
+ };
1762
+ functionZip = (array) => {
1763
+ const length = Math.min(...array.map((arr) => arr.length));
1764
+ return Array.from({ length }, (_, index) => array.map((arr) => arr[index]));
1765
+ };
1766
+ };
1767
+
1768
+ // src/Scope.ts
1769
+ var ScopeChain = class _ScopeChain {
1770
+ inner = void 0;
1771
+ data = {};
1772
+ get currentScopeData() {
1773
+ return this.data;
1774
+ }
1775
+ withScope(data) {
1776
+ const outer = new _ScopeChain();
1777
+ outer.inner = this;
1778
+ outer.data = data;
1779
+ return outer;
1780
+ }
1781
+ getValue(identifier) {
1782
+ if (Object.prototype.hasOwnProperty.call(this.data, identifier)) {
1783
+ return this.data[identifier];
1784
+ }
1785
+ if (this.inner) {
1786
+ return this.inner.getValue(identifier);
1787
+ }
1788
+ return null;
1789
+ }
1790
+ };
1791
+
1792
+ // src/TreeInterpreter.ts
1793
+ var emptyScopeChain = new ScopeChain();
1794
+ var TreeInterpreter = class _TreeInterpreter {
1795
+ runtime;
1796
+ _rootValue = null;
1797
+ _scope;
1798
+ _options;
1799
+ _depth = 0;
1800
+ _deadline = 0;
1801
+ constructor(options) {
1802
+ this.runtime = new Runtime(this);
1803
+ this._scope = new ScopeChain();
1804
+ if (options) {
1805
+ this._options = options;
1806
+ this._deadline = options.timeoutMs !== void 0 ? Date.now() + options.timeoutMs : 0;
1807
+ }
1808
+ }
1809
+ withScope(scope) {
1810
+ const interpreter = new _TreeInterpreter(this._options);
1811
+ interpreter.runtime._functionTable = this.runtime._functionTable;
1812
+ interpreter._rootValue = this._rootValue;
1813
+ interpreter._scope = this._scope.withScope(scope);
1814
+ interpreter._depth = this._depth;
1815
+ interpreter._deadline = this._deadline;
1816
+ return interpreter;
1817
+ }
1818
+ search(node, value, options) {
1819
+ if (options?.maxNodes !== void 0 && countNodes(node) > options.maxNodes) {
1820
+ throw new Error(`Expression exceeds maximum allowed node count of ${options.maxNodes}`);
1821
+ }
1822
+ this._rootValue = value;
1823
+ this._scope = emptyScopeChain;
1824
+ this._options = options;
1825
+ this._depth = 0;
1826
+ this._deadline = options?.timeoutMs !== void 0 ? Date.now() + options.timeoutMs : 0;
1827
+ const result = this.visit(node, value);
1828
+ this.checkOutputSize(result);
1829
+ return result;
1830
+ }
1831
+ checkOutputSize(val) {
1832
+ const max = this._options?.maxOutputSize;
1833
+ if (max === void 0 || val == null) {
1834
+ return;
1835
+ }
1836
+ const size = Array.isArray(val) || typeof val === "string" ? val.length : typeof val === "object" ? Object.keys(val).length : 0;
1837
+ if (size > max) {
1838
+ throw new Error(`Output size exceeds maximum allowed size of ${max}`);
1839
+ }
1840
+ }
1841
+ collect(target, item) {
1842
+ target.push(item);
1843
+ if (this._options?.maxOutputSize !== void 0 && target.length > this._options.maxOutputSize) {
1844
+ throw new Error(`Output size exceeds maximum allowed size of ${this._options.maxOutputSize}`);
1845
+ }
1846
+ }
1847
+ evaluateProjectionItems(items, right) {
1848
+ const collected = [];
1849
+ if (right.type === "Field") {
1850
+ const key = right.name;
1851
+ for (let i = 0; i < items.length; i++) {
1852
+ if (this._deadline > 0 && Date.now() >= this._deadline) {
1853
+ throw new Error(`Query execution timed out after ${this._options?.timeoutMs}ms`);
1854
+ }
1855
+ const elem = items[i];
1856
+ if (!elem || typeof elem !== "object" || Array.isArray(elem)) {
1857
+ continue;
1858
+ }
1859
+ const val = elem[key];
1860
+ if (val !== void 0 && val !== null) {
1861
+ this.collect(collected, val);
1862
+ }
1863
+ }
1864
+ return collected;
1865
+ }
1866
+ if (right.type === "Identity") {
1867
+ for (let i = 0; i < items.length; i++) {
1868
+ const elem = items[i];
1869
+ if (elem !== null) {
1870
+ this.collect(collected, elem);
1871
+ }
1872
+ }
1873
+ return collected;
1874
+ }
1875
+ for (const elem of items) {
1876
+ const current = this.visit(right, elem);
1877
+ if (current !== null) {
1878
+ this.collect(collected, current);
1879
+ }
1880
+ }
1881
+ return collected;
1882
+ }
1883
+ visit(node, value) {
1884
+ if (this._options) {
1885
+ if (this._options.maxDepth !== void 0 && this._depth >= this._options.maxDepth) {
1886
+ throw new Error(`Evaluation exceeds maximum allowed depth of ${this._options.maxDepth}`);
1887
+ }
1888
+ if (this._deadline > 0 && Date.now() >= this._deadline) {
1889
+ throw new Error(`Query execution timed out after ${this._options.timeoutMs}ms`);
1890
+ }
1891
+ }
1892
+ this._depth += 1;
1893
+ try {
1894
+ return this.evaluateNode(node, value);
1895
+ } finally {
1896
+ this._depth -= 1;
1897
+ }
1898
+ }
1899
+ evaluateNode(node, value) {
1900
+ switch (node.type) {
1901
+ case "Ternary": {
1902
+ const condition = this.visit(node.condition, value);
1903
+ if (!isFalse(condition)) {
1904
+ return this.visit(node.trueExpr, value);
1905
+ }
1906
+ return this.visit(node.falseExpr, value);
1907
+ }
1908
+ case "Field":
1909
+ const identifier = node.name;
1910
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1911
+ return null;
1912
+ }
1913
+ return value[identifier] ?? null;
1914
+ case "LetExpression": {
1915
+ const scope = {};
1916
+ for (const binding of node.bindings) {
1917
+ Object.assign(scope, this.visit(binding, value));
1918
+ }
1919
+ return this.withScope(scope).visit(node.expression, value);
1920
+ }
1921
+ case "Binding": {
1922
+ const { variable, reference } = node;
1923
+ const result = this.visit(reference, value);
1924
+ return { [variable]: result };
1925
+ }
1926
+ case "Variable": {
1927
+ const variable = node.name;
1928
+ if (!this._scope.getValue(variable) && !Object.prototype.hasOwnProperty.call(this._scope.currentScopeData, variable)) {
1929
+ throw new Error(`Error referencing undefined variable ${variable}`);
1930
+ }
1931
+ return this._scope.getValue(variable);
1932
+ }
1933
+ case "IndexExpression":
1934
+ return this.visit(node.right, this.visit(node.left, value));
1935
+ case "Subexpression": {
1936
+ const result = this.visit(node.left, value);
1937
+ return result != null ? this.visit(node.right, result) ?? null : null;
1938
+ }
1939
+ case "Index": {
1940
+ if (!Array.isArray(value)) {
1941
+ return null;
1942
+ }
1943
+ const index = node.value < 0 ? value.length + node.value : node.value;
1944
+ return value[index] ?? null;
1945
+ }
1946
+ case "Slice": {
1947
+ if (!Array.isArray(value) && typeof value !== "string") {
1948
+ return null;
1949
+ }
1950
+ const { start, stop, step } = this.computeSliceParams(value.length, node);
1951
+ const target = typeof value === "string" ? [...value] : value;
1952
+ const sliced = this.slice(target, start, stop, step);
1953
+ const res = typeof value === "string" ? sliced.join("") : sliced;
1954
+ this.checkOutputSize(res);
1955
+ return res;
1956
+ }
1957
+ case "Projection": {
1958
+ const { left, right } = node;
1959
+ const allowString = left.type === "IndexExpression" && left.right.type === "Slice";
1960
+ const base = this.visit(left, value);
1961
+ if (allowString && typeof base === "string") {
1962
+ return this.visit(right, base);
1963
+ }
1964
+ return Array.isArray(base) ? this.evaluateProjectionItems(base, right) : null;
1965
+ }
1966
+ case "ValueProjection": {
1967
+ const base = this.visit(node.left, value);
1968
+ if (base === null || typeof base !== "object" || Array.isArray(base)) {
1969
+ return null;
1970
+ }
1971
+ return this.evaluateProjectionItems(Object.values(base), node.right);
1972
+ }
1973
+ case "FilterProjection": {
1974
+ const { left, right, condition } = node;
1975
+ const base = this.visit(left, value);
1976
+ if (!Array.isArray(base)) {
1977
+ return null;
1978
+ }
1979
+ const results = [];
1980
+ if (right.type === "Field") {
1981
+ const key = right.name;
1982
+ for (let i = 0; i < base.length; i++) {
1983
+ const elem = base[i];
1984
+ if (isFalse(this.visit(condition, elem))) {
1985
+ continue;
1986
+ }
1987
+ if (!elem || typeof elem !== "object" || Array.isArray(elem)) {
1988
+ continue;
1989
+ }
1990
+ const val = elem[key];
1991
+ if (val !== void 0 && val !== null) {
1992
+ this.collect(results, val);
1993
+ }
1994
+ }
1995
+ return results;
1996
+ }
1997
+ if (right.type === "Identity") {
1998
+ for (let i = 0; i < base.length; i++) {
1999
+ const elem = base[i];
2000
+ if (isFalse(this.visit(condition, elem))) {
2001
+ continue;
2002
+ }
2003
+ if (elem !== null) {
2004
+ this.collect(results, elem);
2005
+ }
2006
+ }
2007
+ return results;
2008
+ }
2009
+ for (const elem of base) {
2010
+ if (isFalse(this.visit(condition, elem))) {
2011
+ continue;
2012
+ }
2013
+ const result = this.visit(right, elem);
2014
+ if (result !== null) {
2015
+ this.collect(results, result);
2016
+ }
2017
+ }
2018
+ return results;
2019
+ }
2020
+ case "Arithmetic": {
2021
+ const first = this.visit(node.left, value);
2022
+ const second = this.visit(node.right, value);
2023
+ switch (node.operator) {
2024
+ case "Plus" /* TOK_PLUS */:
2025
+ return add(first, second);
2026
+ case "Minus" /* TOK_MINUS */:
2027
+ return sub(first, second);
2028
+ case "Multiply" /* TOK_MULTIPLY */:
2029
+ case "Star" /* TOK_STAR */:
2030
+ return mul(first, second);
2031
+ case "Divide" /* TOK_DIVIDE */:
2032
+ return divide(first, second);
2033
+ case "Modulo" /* TOK_MODULO */:
2034
+ return mod(first, second);
2035
+ case "Div" /* TOK_DIV */:
2036
+ return div(first, second);
2037
+ default:
2038
+ throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`);
2039
+ }
2040
+ }
2041
+ case "Unary": {
2042
+ const operand = this.visit(node.operand, value);
2043
+ switch (node.operator) {
2044
+ case "Plus" /* TOK_PLUS */:
2045
+ ensureNumbers(operand);
2046
+ return operand;
2047
+ case "Minus" /* TOK_MINUS */:
2048
+ ensureNumbers(operand);
2049
+ return -operand;
2050
+ default:
2051
+ throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`);
2052
+ }
2053
+ }
2054
+ case "Comparator": {
2055
+ const first = this.visit(node.left, value);
2056
+ const second = this.visit(node.right, value);
2057
+ switch (node.name) {
2058
+ case "EQ":
2059
+ return strictDeepEqual(first, second);
2060
+ case "NE":
2061
+ return !strictDeepEqual(first, second);
2062
+ }
2063
+ if (typeof first !== "number" || typeof second !== "number") {
2064
+ return null;
2065
+ }
2066
+ switch (node.name) {
2067
+ case "GT":
2068
+ return first > second;
2069
+ case "GTE":
2070
+ return first >= second;
2071
+ case "LT":
2072
+ return first < second;
2073
+ case "LTE":
2074
+ return first <= second;
2075
+ }
2076
+ }
2077
+ case "Flatten": {
2078
+ const original = this.visit(node.child, value);
2079
+ const res = Array.isArray(original) ? original.flat() : null;
2080
+ this.checkOutputSize(res);
2081
+ return res;
2082
+ }
2083
+ case "Root":
2084
+ return this._rootValue;
2085
+ case "MultiSelectList": {
2086
+ const collected = [];
2087
+ for (const child of node.children) {
2088
+ collected.push(this.visit(child, value));
2089
+ }
2090
+ this.checkOutputSize(collected);
2091
+ return collected;
2092
+ }
2093
+ case "MultiSelectHash": {
2094
+ const collected = {};
2095
+ for (const child of node.children) {
2096
+ collected[child.name] = this.visit(child.value, value);
2097
+ }
2098
+ this.checkOutputSize(collected);
2099
+ return collected;
2100
+ }
2101
+ case "OrExpression": {
2102
+ const result = this.visit(node.left, value);
2103
+ if (isFalse(result)) {
2104
+ return this.visit(node.right, value);
2105
+ }
2106
+ return result;
2107
+ }
2108
+ case "AndExpression": {
2109
+ const result = this.visit(node.left, value);
2110
+ if (isFalse(result)) {
2111
+ return result;
2112
+ }
2113
+ return this.visit(node.right, value);
2114
+ }
2115
+ case "NotExpression":
2116
+ return isFalse(this.visit(node.child, value));
2117
+ case "Literal":
2118
+ return node.value;
2119
+ case "Pipe":
2120
+ return this.visit(node.right, this.visit(node.left, value));
2121
+ case "Function": {
2122
+ if (this._options?.allowedFunctions && !this._options.allowedFunctions.includes(node.name)) {
2123
+ throw new Error(`Function '${node.name}' is not allowed`);
2124
+ }
2125
+ if (this._options?.disallowedFunctions && this._options.disallowedFunctions.includes(node.name)) {
2126
+ throw new Error(`Function '${node.name}' is disallowed`);
2127
+ }
2128
+ const args2 = [];
2129
+ for (const child of node.children) {
2130
+ args2.push(this.visit(child, value));
2131
+ }
2132
+ const res = this.runtime.callFunction(node.name, args2);
2133
+ this.checkOutputSize(res);
2134
+ return res;
2135
+ }
2136
+ case "ExpressionReference":
2137
+ return {
2138
+ expref: true,
2139
+ ...node.child
2140
+ };
2141
+ case "Current":
2142
+ case "Identity":
2143
+ return value;
2144
+ }
2145
+ }
2146
+ computeSliceParams(arrayLength, sliceNode) {
2147
+ let { start, stop, step } = sliceNode;
2148
+ if (step === null) {
2149
+ step = 1;
2150
+ } else if (step === 0) {
2151
+ const error = new Error("Invalid value: slice step cannot be 0");
2152
+ error.name = "RuntimeError";
2153
+ throw error;
2154
+ }
2155
+ start = start === null ? step < 0 ? arrayLength - 1 : 0 : this.capSliceRange(arrayLength, start, step);
2156
+ stop = stop === null ? step < 0 ? -1 : arrayLength : this.capSliceRange(arrayLength, stop, step);
2157
+ return { start, stop, step };
2158
+ }
2159
+ capSliceRange(arrayLength, actualValue, step) {
2160
+ let nextActualValue = actualValue;
2161
+ if (nextActualValue < 0) {
2162
+ nextActualValue += arrayLength;
2163
+ if (nextActualValue < 0) {
2164
+ nextActualValue = step < 0 ? -1 : 0;
2165
+ }
2166
+ } else if (nextActualValue >= arrayLength) {
2167
+ nextActualValue = step < 0 ? arrayLength - 1 : arrayLength;
2168
+ }
2169
+ return nextActualValue;
2170
+ }
2171
+ slice(collection, start, end, step) {
2172
+ if (step === 1) {
2173
+ return collection.slice(start, end);
2174
+ }
2175
+ const len = Math.ceil(Math.abs(start - end) / Math.abs(step));
2176
+ const result = new Array(len);
2177
+ let idx = 0;
2178
+ if (step > 0) {
2179
+ for (let i = start; i < end; i += step) {
2180
+ result[idx++] = collection[i];
2181
+ }
2182
+ } else {
2183
+ for (let i = start; i > end; i += step) {
2184
+ result[idx++] = collection[i];
2185
+ }
2186
+ }
2187
+ return result;
2188
+ }
2189
+ };
2190
+ var TreeInterpreterInstance = new TreeInterpreter();
2191
+ var TreeInterpreter_default = TreeInterpreterInstance;
2192
+
2193
+ // src/Stream.ts
2194
+ async function* toAsyncIterable(source) {
2195
+ if (source == null) {
2196
+ return;
2197
+ }
2198
+ if (typeof source !== "object" && typeof source !== "function") {
2199
+ throw new TypeError("Invalid stream source: expected AsyncIterable, Iterable, or ReadableStream");
2200
+ }
2201
+ if (Symbol.asyncIterator in source) {
2202
+ for await (const chunk of source) {
2203
+ yield chunk;
2204
+ }
2205
+ return;
2206
+ }
2207
+ if (typeof source.getReader === "function") {
2208
+ const reader = source.getReader();
2209
+ try {
2210
+ while (true) {
2211
+ const { done, value } = await reader.read();
2212
+ if (done) {
2213
+ break;
2214
+ }
2215
+ yield value;
2216
+ }
2217
+ } finally {
2218
+ reader.releaseLock();
2219
+ }
2220
+ return;
2221
+ }
2222
+ if (Symbol.iterator in source) {
2223
+ for (const chunk of source) {
2224
+ yield chunk;
2225
+ }
2226
+ return;
2227
+ }
2228
+ throw new TypeError("Invalid stream source: expected AsyncIterable, Iterable, or ReadableStream");
2229
+ }
2230
+ function parseItem(str, parseJson) {
2231
+ if (parseJson === true) {
2232
+ return JSON.parse(str);
2233
+ }
2234
+ if (parseJson === "auto") {
2235
+ try {
2236
+ return JSON.parse(str);
2237
+ } catch {
2238
+ return str;
2239
+ }
2240
+ }
2241
+ return str;
2242
+ }
2243
+ async function* normalizeSource(source, options) {
2244
+ const parseJson = options?.parseJson ?? "auto";
2245
+ const flatten = options?.flattenChunks ?? true;
2246
+ let buffer = "";
2247
+ const textDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
2248
+ for await (const chunk of toAsyncIterable(source)) {
2249
+ if (chunk instanceof Uint8Array && textDecoder) {
2250
+ buffer += textDecoder.decode(chunk, { stream: true });
2251
+ if (buffer.includes("\n")) {
2252
+ const lines = buffer.split("\n");
2253
+ buffer = lines.pop() ?? "";
2254
+ for (const line of lines) {
2255
+ const trimmed = line.trim();
2256
+ if (trimmed) {
2257
+ yield parseItem(trimmed, parseJson);
2258
+ }
2259
+ }
2260
+ }
2261
+ } else if (typeof chunk === "string") {
2262
+ if (parseJson === false) {
2263
+ yield chunk;
2264
+ } else {
2265
+ buffer += chunk;
2266
+ if (buffer.includes("\n")) {
2267
+ const lines = buffer.split("\n");
2268
+ buffer = lines.pop() ?? "";
2269
+ for (const line of lines) {
2270
+ const trimmed = line.trim();
2271
+ if (trimmed) {
2272
+ yield parseItem(trimmed, parseJson);
2273
+ }
2274
+ }
2275
+ }
2276
+ }
2277
+ } else if (flatten && Array.isArray(chunk)) {
2278
+ if (buffer.trim()) {
2279
+ yield parseItem(buffer.trim(), parseJson);
2280
+ buffer = "";
2281
+ }
2282
+ for (let i = 0; i < chunk.length; i++) {
2283
+ yield chunk[i];
2284
+ }
2285
+ } else {
2286
+ if (buffer.trim()) {
2287
+ yield parseItem(buffer.trim(), parseJson);
2288
+ buffer = "";
2289
+ }
2290
+ yield chunk;
2291
+ }
2292
+ }
2293
+ if (textDecoder && buffer) {
2294
+ buffer += textDecoder.decode();
2295
+ }
2296
+ if (buffer.trim()) {
2297
+ yield parseItem(buffer.trim(), parseJson);
2298
+ }
2299
+ }
2300
+ function isStreamableNode(node) {
2301
+ switch (node.type) {
2302
+ case "Projection":
2303
+ if (node.left.type === "Identity" || node.left.type === "Current") {
2304
+ return true;
2305
+ }
2306
+ if (node.left.type === "IndexExpression" && node.left.right.type === "Slice") {
2307
+ const slice = node.left.right;
2308
+ return (slice.start === null || slice.start >= 0) && (slice.stop === null || slice.stop >= 0) && (slice.step === null || slice.step > 0);
2309
+ }
2310
+ return false;
2311
+ case "FilterProjection":
2312
+ return node.left.type === "Identity" || node.left.type === "Current";
2313
+ case "IndexExpression":
2314
+ if (node.right.type === "Slice" && (node.left.type === "Identity" || node.left.type === "Current")) {
2315
+ const slice = node.right;
2316
+ return (slice.start === null || slice.start >= 0) && (slice.stop === null || slice.stop >= 0) && (slice.step === null || slice.step > 0);
2317
+ }
2318
+ return true;
2319
+ case "Field":
2320
+ case "Identity":
2321
+ case "Current":
2322
+ case "Subexpression":
2323
+ case "MultiSelectHash":
2324
+ case "MultiSelectList":
2325
+ case "Ternary":
2326
+ case "Comparator":
2327
+ case "Arithmetic":
2328
+ case "NotExpression":
2329
+ return true;
2330
+ case "Pipe":
2331
+ return isStreamableNode(node.left) && isStreamableNode(node.right);
2332
+ default:
2333
+ return false;
2334
+ }
2335
+ }
2336
+ async function* evaluateStreamNode(source, node, interpreter, options) {
2337
+ const deadline = options?.timeoutMs !== void 0 ? Date.now() + options.timeoutMs : 0;
2338
+ function checkDeadline() {
2339
+ if (deadline > 0 && Date.now() >= deadline) {
2340
+ throw new Error(`Query execution timed out after ${options?.timeoutMs}ms`);
2341
+ }
2342
+ }
2343
+ switch (node.type) {
2344
+ case "Projection": {
2345
+ const { left, right } = node;
2346
+ let streamSource = source;
2347
+ if (left.type === "IndexExpression" && left.right.type === "Slice") {
2348
+ streamSource = evaluateStreamNode(source, left, interpreter, options);
2349
+ }
2350
+ if (right.type === "Identity" || right.type === "Current") {
2351
+ for await (const item of streamSource) {
2352
+ checkDeadline();
2353
+ if (item !== null && item !== void 0) {
2354
+ yield item;
2355
+ }
2356
+ }
2357
+ return;
2358
+ }
2359
+ if (right.type === "Field") {
2360
+ const key = right.name;
2361
+ for await (const item of streamSource) {
2362
+ checkDeadline();
2363
+ if (item && typeof item === "object" && !Array.isArray(item)) {
2364
+ const val = item[key];
2365
+ if (val !== void 0 && val !== null) {
2366
+ yield val;
2367
+ }
2368
+ }
2369
+ }
2370
+ return;
2371
+ }
2372
+ for await (const item of streamSource) {
2373
+ checkDeadline();
2374
+ const res = interpreter.visit(right, item);
2375
+ if (res !== null && res !== void 0) {
2376
+ yield res;
2377
+ }
2378
+ }
2379
+ return;
2380
+ }
2381
+ case "IndexExpression": {
2382
+ if (node.right.type === "Slice" && (node.left.type === "Identity" || node.left.type === "Current")) {
2383
+ const slice = node.right;
2384
+ const start = slice.start ?? 0;
2385
+ const stop = slice.stop ?? Infinity;
2386
+ const step = slice.step ?? 1;
2387
+ if (start >= 0 && stop >= 0 && step > 0) {
2388
+ let index = 0;
2389
+ for await (const item of source) {
2390
+ checkDeadline();
2391
+ if (index >= stop) {
2392
+ break;
2393
+ }
2394
+ if (index >= start && (index - start) % step === 0) {
2395
+ yield item;
2396
+ }
2397
+ index++;
2398
+ if (index >= stop) {
2399
+ break;
2400
+ }
2401
+ }
2402
+ return;
2403
+ }
2404
+ const collected = [];
2405
+ for await (const item of source) {
2406
+ checkDeadline();
2407
+ collected.push(item);
2408
+ if (options?.maxOutputSize !== void 0 && collected.length > options.maxOutputSize) {
2409
+ throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`);
2410
+ }
2411
+ }
2412
+ const result = interpreter.search(node, collected, options);
2413
+ if (Array.isArray(result)) {
2414
+ for (const item of result) {
2415
+ yield item;
2416
+ }
2417
+ }
2418
+ return;
2419
+ }
2420
+ for await (const item of source) {
2421
+ checkDeadline();
2422
+ const res = interpreter.visit(node, item);
2423
+ if (res !== null && res !== void 0) {
2424
+ yield res;
2425
+ }
2426
+ }
2427
+ return;
2428
+ }
2429
+ case "FilterProjection": {
2430
+ const { condition, right } = node;
2431
+ if (right.type === "Identity" || right.type === "Current") {
2432
+ for await (const item of source) {
2433
+ checkDeadline();
2434
+ if (!isFalse(interpreter.visit(condition, item))) {
2435
+ yield item;
2436
+ }
2437
+ }
2438
+ return;
2439
+ }
2440
+ if (right.type === "Field") {
2441
+ const key = right.name;
2442
+ for await (const item of source) {
2443
+ checkDeadline();
2444
+ if (!isFalse(interpreter.visit(condition, item))) {
2445
+ if (item && typeof item === "object" && !Array.isArray(item)) {
2446
+ const val = item[key];
2447
+ if (val !== void 0 && val !== null) {
2448
+ yield val;
2449
+ }
2450
+ }
2451
+ }
2452
+ }
2453
+ return;
2454
+ }
2455
+ for await (const item of source) {
2456
+ checkDeadline();
2457
+ if (!isFalse(interpreter.visit(condition, item))) {
2458
+ const res = interpreter.visit(right, item);
2459
+ if (res !== null && res !== void 0) {
2460
+ yield res;
2461
+ }
2462
+ }
2463
+ }
2464
+ return;
2465
+ }
2466
+ case "Pipe": {
2467
+ const leftStream = evaluateStreamNode(source, node.left, interpreter, options);
2468
+ if (isStreamableNode(node.right)) {
2469
+ for await (const res of evaluateStreamNode(leftStream, node.right, interpreter, options)) {
2470
+ yield res;
2471
+ }
2472
+ } else {
2473
+ const collected = [];
2474
+ for await (const item of leftStream) {
2475
+ checkDeadline();
2476
+ collected.push(item);
2477
+ if (options?.maxOutputSize !== void 0 && collected.length > options.maxOutputSize) {
2478
+ throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`);
2479
+ }
2480
+ }
2481
+ const result = interpreter.search(node.right, collected, options);
2482
+ if (result !== null && result !== void 0) {
2483
+ yield result;
2484
+ }
2485
+ }
2486
+ return;
2487
+ }
2488
+ case "Identity":
2489
+ case "Current": {
2490
+ for await (const item of source) {
2491
+ checkDeadline();
2492
+ yield item;
2493
+ }
2494
+ return;
2495
+ }
2496
+ case "Field": {
2497
+ const key = node.name;
2498
+ for await (const item of source) {
2499
+ checkDeadline();
2500
+ if (item && typeof item === "object" && !Array.isArray(item)) {
2501
+ const val = item[key];
2502
+ if (val !== void 0 && val !== null) {
2503
+ yield val;
2504
+ }
2505
+ }
2506
+ }
2507
+ return;
2508
+ }
2509
+ default: {
2510
+ if (isStreamableNode(node)) {
2511
+ for await (const item of source) {
2512
+ checkDeadline();
2513
+ const res = interpreter.visit(node, item);
2514
+ if (res !== null && res !== void 0) {
2515
+ yield res;
2516
+ }
2517
+ }
2518
+ return;
2519
+ }
2520
+ const collected = [];
2521
+ for await (const item of source) {
2522
+ checkDeadline();
2523
+ collected.push(item);
2524
+ if (options?.maxOutputSize !== void 0 && collected.length > options.maxOutputSize) {
2525
+ throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`);
2526
+ }
2527
+ }
2528
+ const result = interpreter.search(node, collected, options);
2529
+ if (result !== null && result !== void 0) {
2530
+ yield result;
2531
+ }
2532
+ return;
2533
+ }
2534
+ }
2535
+ }
2536
+ function isExpressionNode(val) {
2537
+ return typeof val === "object" && val !== null && "type" in val && typeof val.type === "string" && !(Symbol.iterator in val) && !(Symbol.asyncIterator in val);
2538
+ }
2539
+ async function* searchStream(sourceOrExpression, expressionOrSource, options) {
2540
+ let expression2;
2541
+ let source;
2542
+ if (typeof sourceOrExpression === "string" || isExpressionNode(sourceOrExpression)) {
2543
+ expression2 = sourceOrExpression;
2544
+ source = expressionOrSource;
2545
+ } else {
2546
+ source = sourceOrExpression;
2547
+ expression2 = expressionOrSource;
2548
+ }
2549
+ if (typeof expression2 !== "string" && !isExpressionNode(expression2)) {
2550
+ throw new TypeError("Expression must be a string or AST ExpressionNode");
2551
+ }
2552
+ const ast = typeof expression2 === "string" ? Parser_default.parse(expression2, options) : expression2;
2553
+ if (options) {
2554
+ const fnError = findDisallowedFunction(ast, options);
2555
+ if (fnError) {
2556
+ throw new Error(fnError);
2557
+ }
2558
+ }
2559
+ const interpreter = new TreeInterpreter(options);
2560
+ interpreter.runtime._functionTable = TreeInterpreterInstance.runtime._functionTable;
2561
+ const items = normalizeSource(source, options);
2562
+ const results = evaluateStreamNode(items, ast, interpreter, options);
2563
+ const limit = options?.limit;
2564
+ const maxOutputSize = options?.maxOutputSize;
2565
+ let count = 0;
2566
+ for await (const result of results) {
2567
+ yield result;
2568
+ count++;
2569
+ if (limit !== void 0 && count >= limit) {
2570
+ break;
2571
+ }
2572
+ if (maxOutputSize !== void 0 && count > maxOutputSize) {
2573
+ throw new Error(`Output size exceeds maximum allowed size of ${maxOutputSize}`);
2574
+ }
2575
+ }
2576
+ }
2577
+
2578
+ // src/index.ts
2579
+ var TYPE_ANY = 1 /* TYPE_ANY */;
2580
+ var TYPE_ARRAY = 3 /* TYPE_ARRAY */;
2581
+ var TYPE_ARRAY_ARRAY = 11 /* TYPE_ARRAY_ARRAY */;
2582
+ var TYPE_ARRAY_NUMBER = 8 /* TYPE_ARRAY_NUMBER */;
2583
+ var TYPE_ARRAY_OBJECT = 10 /* TYPE_ARRAY_OBJECT */;
2584
+ var TYPE_ARRAY_STRING = 9 /* TYPE_ARRAY_STRING */;
2585
+ var TYPE_BOOLEAN = 5 /* TYPE_BOOLEAN */;
2586
+ var TYPE_EXPREF = 6 /* TYPE_EXPREF */;
2587
+ var TYPE_NULL = 7 /* TYPE_NULL */;
2588
+ var TYPE_NUMBER = 0 /* TYPE_NUMBER */;
2589
+ var TYPE_OBJECT = 4 /* TYPE_OBJECT */;
2590
+ var TYPE_STRING = 2 /* TYPE_STRING */;
2591
+ function compile(expression2, options) {
2592
+ return Parser_default.parse(expression2, options);
2593
+ }
2594
+ function compileQuery(expression2, options) {
2595
+ const nodeTree = Parser_default.parse(expression2, options);
2596
+ const fn = function(data) {
2597
+ return TreeInterpreter_default.search(nodeTree, data, options);
2598
+ };
2599
+ fn.search = (data) => TreeInterpreter_default.search(nodeTree, data, options);
2600
+ fn.searchStream = (source, streamOptions) => searchStream(source, nodeTree, { ...options, ...streamOptions });
2601
+ fn.ast = nodeTree;
2602
+ return fn;
2603
+ }
2604
+ function validate(expression2, options) {
2605
+ if (typeof expression2 !== "string") {
2606
+ return { valid: false, error: "Expression must be a string" };
2607
+ }
2608
+ try {
2609
+ const ast = Parser_default.parse(expression2, options);
2610
+ if (options) {
2611
+ const fnError = findDisallowedFunction(ast, options);
2612
+ if (fnError) {
2613
+ return { valid: false, error: fnError };
2614
+ }
2615
+ }
2616
+ return { valid: true, ast };
2617
+ } catch (err) {
2618
+ return {
2619
+ valid: false,
2620
+ error: err instanceof Error ? err.message : String(err)
2621
+ };
2622
+ }
2623
+ }
2624
+ function tokenize(expression2, options) {
2625
+ return Lexer_default.tokenize(expression2, options);
2626
+ }
2627
+ var registerFunction = (functionName, customFunction, signature, options) => {
2628
+ TreeInterpreter_default.runtime.registerFunction(functionName, customFunction, signature, options);
2629
+ };
2630
+ var register = (name, customFunction, signature, options) => {
2631
+ return TreeInterpreter_default.runtime.register(name, customFunction, signature, options);
2632
+ };
2633
+ var unregisterFunction = (name) => {
2634
+ return TreeInterpreter_default.runtime.unregister(name);
2635
+ };
2636
+ var isRegistered = (name) => {
2637
+ return TreeInterpreter_default.runtime.isRegistered(name);
2638
+ };
2639
+ var getRegisteredFunctions = () => {
2640
+ return TreeInterpreter_default.runtime.getRegistered();
2641
+ };
2642
+ var getCustomFunctions = () => {
2643
+ return TreeInterpreter_default.runtime.getCustomFunctions();
2644
+ };
2645
+ var clearCustomFunctions = () => {
2646
+ TreeInterpreter_default.runtime.clearCustomFunctions();
2647
+ };
2648
+ var MAX_CACHE_SIZE = 1e3;
2649
+ var astCache = /* @__PURE__ */ new Map();
2650
+ function search(data, expression2, options) {
2651
+ let nodeTree;
2652
+ if (!options) {
2653
+ nodeTree = astCache.get(expression2);
2654
+ if (!nodeTree) {
2655
+ nodeTree = Parser_default.parse(expression2);
2656
+ if (astCache.size >= MAX_CACHE_SIZE) {
2657
+ const firstKey = astCache.keys().next().value;
2658
+ if (firstKey !== void 0) {
2659
+ astCache.delete(firstKey);
2660
+ }
2661
+ }
2662
+ astCache.set(expression2, nodeTree);
2663
+ }
2664
+ } else {
2665
+ nodeTree = Parser_default.parse(expression2, options);
2666
+ }
2667
+ return TreeInterpreter_default.search(nodeTree, data, options);
2668
+ }
2669
+ function Scope() {
2670
+ return new ScopeChain();
2671
+ }
2672
+ var TreeInterpreter2 = TreeInterpreter_default;
2673
+ var jmespath = {
2674
+ compile,
2675
+ compileQuery,
2676
+ searchStream,
2677
+ validate,
2678
+ registerFunction,
2679
+ register,
2680
+ unregisterFunction,
2681
+ isRegistered,
2682
+ getRegisteredFunctions,
2683
+ getCustomFunctions,
2684
+ clearCustomFunctions,
2685
+ search,
2686
+ tokenize,
2687
+ TreeInterpreter: TreeInterpreter2,
2688
+ TYPE_ANY,
2689
+ TYPE_ARRAY_NUMBER,
2690
+ TYPE_ARRAY_STRING,
2691
+ TYPE_ARRAY,
2692
+ TYPE_BOOLEAN,
2693
+ TYPE_EXPREF,
2694
+ TYPE_NULL,
2695
+ TYPE_NUMBER,
2696
+ TYPE_OBJECT,
2697
+ TYPE_STRING,
2698
+ TYPE_ARRAY_ARRAY,
2699
+ TYPE_ARRAY_OBJECT,
2700
+ Scope
2701
+ };
2702
+ var index_default = jmespath;
2703
+
2704
+ // src/cli.ts
2705
+ var args = getArgs();
2706
+ if (args.values.help) {
2707
+ printHelp();
2708
+ process.exit(0);
2709
+ }
2710
+ if (!args.values["expr-file"] && args.positionals.length < 1) {
2711
+ console.log("Must provide a jmespath expression.");
2712
+ process.exit(1);
2713
+ }
2714
+ var expression = "";
2715
+ if (args.values["expr-file"]) {
2716
+ expression = fs.readFileSync(args.values["expr-file"], { encoding: "utf8", flag: "r" });
2717
+ } else {
2718
+ expression = args.positionals[0];
2719
+ }
2720
+ var inputJSON = "";
2721
+ if (args?.values?.filename) {
2722
+ inputJSON = fs.readFileSync(args.values.filename, { encoding: "utf8", flag: "r" });
2723
+ printResult(inputJSON, expression, args.values.compact);
2724
+ } else {
2725
+ process.stdin.setEncoding("utf-8");
2726
+ process.stdin.on("readable", function() {
2727
+ const chunk = process.stdin.read();
2728
+ if (chunk !== null) {
2729
+ inputJSON += chunk;
2730
+ }
2731
+ });
2732
+ process.stdin.on("end", function() {
2733
+ printResult(inputJSON, expression, args.values.compact);
2734
+ });
2735
+ }
2736
+ function getArgs() {
2737
+ const config = {
2738
+ options: {
2739
+ compact: {
2740
+ type: "boolean",
2741
+ short: "c",
2742
+ default: false
2743
+ },
2744
+ help: {
2745
+ type: "boolean",
2746
+ short: "h",
2747
+ default: false
2748
+ },
2749
+ filename: {
2750
+ type: "string",
2751
+ short: "f"
2752
+ },
2753
+ "expr-file": {
2754
+ type: "string",
2755
+ short: "e"
2756
+ }
2757
+ },
2758
+ allowPositionals: true
2759
+ };
2760
+ return parseArgs(config);
2761
+ }
2762
+ function printHelp() {
2763
+ console.log(`
2764
+ NAME:
2765
+ jp - jp [<options>] <expression>
2766
+
2767
+ USAGE:
2768
+ jp [global options] command [command options] [arguments...]
2769
+
2770
+ VERSION:
2771
+ ${package_default.name}@${package_default.version}
2772
+
2773
+ OPTIONS:
2774
+ --compact, -c Produce compact JSON output that omits nonessential whitespace.
2775
+ --filename value, -f value Read input JSON from a file instead of stdin.
2776
+ --expr-file value, -e value Read JMESPath expression from the specified file.
2777
+ --help, -h Show help
2778
+ `);
2779
+ }
2780
+ function printResult(inputJSON2, expression2, compact = false) {
2781
+ let parsedInput = null;
2782
+ try {
2783
+ parsedInput = JSON.parse(inputJSON2);
2784
+ } catch (e) {
2785
+ throw e;
2786
+ }
2787
+ try {
2788
+ console.log(JSON.stringify(index_default.search(parsedInput, expression2, void 0), null, compact ? 0 : 2));
2789
+ } catch (e) {
2790
+ throw e;
2791
+ }
2792
+ }
2793
+ //# sourceMappingURL=cli.mjs.map
2794
+ //# sourceMappingURL=cli.mjs.map