@nocobase/plugin-workflow-json-query 1.9.7

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 (50) hide show
  1. package/LICENSE.txt +172 -0
  2. package/README.md +1 -0
  3. package/client.d.ts +2 -0
  4. package/client.js +1 -0
  5. package/dist/client/index.d.ts +23 -0
  6. package/dist/client/index.js +10 -0
  7. package/dist/client/instruction.d.ts +167 -0
  8. package/dist/externalVersion.js +19 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +42 -0
  11. package/dist/locale/en-US.json +13 -0
  12. package/dist/locale/index.d.ts +10 -0
  13. package/dist/locale/index.js +42 -0
  14. package/dist/locale/zh-CN.json +14 -0
  15. package/dist/node_modules/jmespath/LICENSE +13 -0
  16. package/dist/node_modules/jmespath/artifacts/jmespath.min.js +2 -0
  17. package/dist/node_modules/jmespath/bower.json +24 -0
  18. package/dist/node_modules/jmespath/jmespath.js +1 -0
  19. package/dist/node_modules/jmespath/jp.js +23 -0
  20. package/dist/node_modules/jmespath/package.json +1 -0
  21. package/dist/node_modules/jsonata/LICENSE +19 -0
  22. package/dist/node_modules/jsonata/jsonata-es5.js +9875 -0
  23. package/dist/node_modules/jsonata/jsonata-es5.min.js +1 -0
  24. package/dist/node_modules/jsonata/jsonata.d.ts +72 -0
  25. package/dist/node_modules/jsonata/jsonata.js +1 -0
  26. package/dist/node_modules/jsonata/jsonata.min.js +1 -0
  27. package/dist/node_modules/jsonata/package.json +1 -0
  28. package/dist/node_modules/jsonpath-plus/LICENSE +22 -0
  29. package/dist/node_modules/jsonpath-plus/bin/jsonpath-cli.js +36 -0
  30. package/dist/node_modules/jsonpath-plus/dist/index-browser-esm.js +2158 -0
  31. package/dist/node_modules/jsonpath-plus/dist/index-browser-esm.min.js +2 -0
  32. package/dist/node_modules/jsonpath-plus/dist/index-browser-umd.cjs +2166 -0
  33. package/dist/node_modules/jsonpath-plus/dist/index-browser-umd.min.cjs +2 -0
  34. package/dist/node_modules/jsonpath-plus/dist/index-node-cjs.cjs +1 -0
  35. package/dist/node_modules/jsonpath-plus/dist/index-node-esm.js +2068 -0
  36. package/dist/node_modules/jsonpath-plus/package.json +1 -0
  37. package/dist/node_modules/jsonpath-plus/src/Safe-Script.js +200 -0
  38. package/dist/node_modules/jsonpath-plus/src/jsonpath-browser.js +102 -0
  39. package/dist/node_modules/jsonpath-plus/src/jsonpath-node.js +8 -0
  40. package/dist/node_modules/jsonpath-plus/src/jsonpath.d.ts +226 -0
  41. package/dist/node_modules/jsonpath-plus/src/jsonpath.js +784 -0
  42. package/dist/server/JSONQueryInstruction.d.ts +42 -0
  43. package/dist/server/JSONQueryInstruction.js +99 -0
  44. package/dist/server/Plugin.d.ts +24 -0
  45. package/dist/server/Plugin.js +62 -0
  46. package/dist/server/index.d.ts +17 -0
  47. package/dist/server/index.js +42 -0
  48. package/package.json +31 -0
  49. package/server.d.ts +2 -0
  50. package/server.js +1 -0
@@ -0,0 +1,2068 @@
1
+ import vm from 'vm';
2
+
3
+ /**
4
+ * @implements {IHooks}
5
+ */
6
+ class Hooks {
7
+ /**
8
+ * @callback HookCallback
9
+ * @this {*|Jsep} this
10
+ * @param {Jsep} env
11
+ * @returns: void
12
+ */
13
+ /**
14
+ * Adds the given callback to the list of callbacks for the given hook.
15
+ *
16
+ * The callback will be invoked when the hook it is registered for is run.
17
+ *
18
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
19
+ *
20
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
21
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
22
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
23
+ * @public
24
+ */
25
+ add(name, callback, first) {
26
+ if (typeof arguments[0] != 'string') {
27
+ // Multiple hook callbacks, keyed by name
28
+ for (let name in arguments[0]) {
29
+ this.add(name, arguments[0][name], arguments[1]);
30
+ }
31
+ } else {
32
+ (Array.isArray(name) ? name : [name]).forEach(function (name) {
33
+ this[name] = this[name] || [];
34
+ if (callback) {
35
+ this[name][first ? 'unshift' : 'push'](callback);
36
+ }
37
+ }, this);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Runs a hook invoking all registered callbacks with the given environment variables.
43
+ *
44
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
45
+ *
46
+ * @param {string} name The name of the hook.
47
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
48
+ * @public
49
+ */
50
+ run(name, env) {
51
+ this[name] = this[name] || [];
52
+ this[name].forEach(function (callback) {
53
+ callback.call(env && env.context ? env.context : env, env);
54
+ });
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @implements {IPlugins}
60
+ */
61
+ class Plugins {
62
+ constructor(jsep) {
63
+ this.jsep = jsep;
64
+ this.registered = {};
65
+ }
66
+
67
+ /**
68
+ * @callback PluginSetup
69
+ * @this {Jsep} jsep
70
+ * @returns: void
71
+ */
72
+ /**
73
+ * Adds the given plugin(s) to the registry
74
+ *
75
+ * @param {object} plugins
76
+ * @param {string} plugins.name The name of the plugin
77
+ * @param {PluginSetup} plugins.init The init function
78
+ * @public
79
+ */
80
+ register(...plugins) {
81
+ plugins.forEach(plugin => {
82
+ if (typeof plugin !== 'object' || !plugin.name || !plugin.init) {
83
+ throw new Error('Invalid JSEP plugin format');
84
+ }
85
+ if (this.registered[plugin.name]) {
86
+ // already registered. Ignore.
87
+ return;
88
+ }
89
+ plugin.init(this.jsep);
90
+ this.registered[plugin.name] = plugin;
91
+ });
92
+ }
93
+ }
94
+
95
+ // JavaScript Expression Parser (JSEP) 1.4.0
96
+
97
+ class Jsep {
98
+ /**
99
+ * @returns {string}
100
+ */
101
+ static get version() {
102
+ // To be filled in by the template
103
+ return '1.4.0';
104
+ }
105
+
106
+ /**
107
+ * @returns {string}
108
+ */
109
+ static toString() {
110
+ return 'JavaScript Expression Parser (JSEP) v' + Jsep.version;
111
+ }
112
+ // ==================== CONFIG ================================
113
+ /**
114
+ * @method addUnaryOp
115
+ * @param {string} op_name The name of the unary op to add
116
+ * @returns {Jsep}
117
+ */
118
+ static addUnaryOp(op_name) {
119
+ Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
120
+ Jsep.unary_ops[op_name] = 1;
121
+ return Jsep;
122
+ }
123
+
124
+ /**
125
+ * @method jsep.addBinaryOp
126
+ * @param {string} op_name The name of the binary op to add
127
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
128
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
129
+ * @returns {Jsep}
130
+ */
131
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
132
+ Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
133
+ Jsep.binary_ops[op_name] = precedence;
134
+ if (isRightAssociative) {
135
+ Jsep.right_associative.add(op_name);
136
+ } else {
137
+ Jsep.right_associative.delete(op_name);
138
+ }
139
+ return Jsep;
140
+ }
141
+
142
+ /**
143
+ * @method addIdentifierChar
144
+ * @param {string} char The additional character to treat as a valid part of an identifier
145
+ * @returns {Jsep}
146
+ */
147
+ static addIdentifierChar(char) {
148
+ Jsep.additional_identifier_chars.add(char);
149
+ return Jsep;
150
+ }
151
+
152
+ /**
153
+ * @method addLiteral
154
+ * @param {string} literal_name The name of the literal to add
155
+ * @param {*} literal_value The value of the literal
156
+ * @returns {Jsep}
157
+ */
158
+ static addLiteral(literal_name, literal_value) {
159
+ Jsep.literals[literal_name] = literal_value;
160
+ return Jsep;
161
+ }
162
+
163
+ /**
164
+ * @method removeUnaryOp
165
+ * @param {string} op_name The name of the unary op to remove
166
+ * @returns {Jsep}
167
+ */
168
+ static removeUnaryOp(op_name) {
169
+ delete Jsep.unary_ops[op_name];
170
+ if (op_name.length === Jsep.max_unop_len) {
171
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
172
+ }
173
+ return Jsep;
174
+ }
175
+
176
+ /**
177
+ * @method removeAllUnaryOps
178
+ * @returns {Jsep}
179
+ */
180
+ static removeAllUnaryOps() {
181
+ Jsep.unary_ops = {};
182
+ Jsep.max_unop_len = 0;
183
+ return Jsep;
184
+ }
185
+
186
+ /**
187
+ * @method removeIdentifierChar
188
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
189
+ * @returns {Jsep}
190
+ */
191
+ static removeIdentifierChar(char) {
192
+ Jsep.additional_identifier_chars.delete(char);
193
+ return Jsep;
194
+ }
195
+
196
+ /**
197
+ * @method removeBinaryOp
198
+ * @param {string} op_name The name of the binary op to remove
199
+ * @returns {Jsep}
200
+ */
201
+ static removeBinaryOp(op_name) {
202
+ delete Jsep.binary_ops[op_name];
203
+ if (op_name.length === Jsep.max_binop_len) {
204
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
205
+ }
206
+ Jsep.right_associative.delete(op_name);
207
+ return Jsep;
208
+ }
209
+
210
+ /**
211
+ * @method removeAllBinaryOps
212
+ * @returns {Jsep}
213
+ */
214
+ static removeAllBinaryOps() {
215
+ Jsep.binary_ops = {};
216
+ Jsep.max_binop_len = 0;
217
+ return Jsep;
218
+ }
219
+
220
+ /**
221
+ * @method removeLiteral
222
+ * @param {string} literal_name The name of the literal to remove
223
+ * @returns {Jsep}
224
+ */
225
+ static removeLiteral(literal_name) {
226
+ delete Jsep.literals[literal_name];
227
+ return Jsep;
228
+ }
229
+
230
+ /**
231
+ * @method removeAllLiterals
232
+ * @returns {Jsep}
233
+ */
234
+ static removeAllLiterals() {
235
+ Jsep.literals = {};
236
+ return Jsep;
237
+ }
238
+ // ==================== END CONFIG ============================
239
+
240
+ /**
241
+ * @returns {string}
242
+ */
243
+ get char() {
244
+ return this.expr.charAt(this.index);
245
+ }
246
+
247
+ /**
248
+ * @returns {number}
249
+ */
250
+ get code() {
251
+ return this.expr.charCodeAt(this.index);
252
+ }
253
+ /**
254
+ * @param {string} expr a string with the passed in express
255
+ * @returns Jsep
256
+ */
257
+ constructor(expr) {
258
+ // `index` stores the character number we are currently at
259
+ // All of the gobbles below will modify `index` as we move along
260
+ this.expr = expr;
261
+ this.index = 0;
262
+ }
263
+
264
+ /**
265
+ * static top-level parser
266
+ * @returns {jsep.Expression}
267
+ */
268
+ static parse(expr) {
269
+ return new Jsep(expr).parse();
270
+ }
271
+
272
+ /**
273
+ * Get the longest key length of any object
274
+ * @param {object} obj
275
+ * @returns {number}
276
+ */
277
+ static getMaxKeyLen(obj) {
278
+ return Math.max(0, ...Object.keys(obj).map(k => k.length));
279
+ }
280
+
281
+ /**
282
+ * `ch` is a character code in the next three functions
283
+ * @param {number} ch
284
+ * @returns {boolean}
285
+ */
286
+ static isDecimalDigit(ch) {
287
+ return ch >= 48 && ch <= 57; // 0...9
288
+ }
289
+
290
+ /**
291
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
292
+ * @param {string} op_val
293
+ * @returns {number}
294
+ */
295
+ static binaryPrecedence(op_val) {
296
+ return Jsep.binary_ops[op_val] || 0;
297
+ }
298
+
299
+ /**
300
+ * Looks for start of identifier
301
+ * @param {number} ch
302
+ * @returns {boolean}
303
+ */
304
+ static isIdentifierStart(ch) {
305
+ return ch >= 65 && ch <= 90 ||
306
+ // A...Z
307
+ ch >= 97 && ch <= 122 ||
308
+ // a...z
309
+ ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] ||
310
+ // any non-ASCII that is not an operator
311
+ Jsep.additional_identifier_chars.has(String.fromCharCode(ch)); // additional characters
312
+ }
313
+
314
+ /**
315
+ * @param {number} ch
316
+ * @returns {boolean}
317
+ */
318
+ static isIdentifierPart(ch) {
319
+ return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
320
+ }
321
+
322
+ /**
323
+ * throw error at index of the expression
324
+ * @param {string} message
325
+ * @throws
326
+ */
327
+ throwError(message) {
328
+ const error = new Error(message + ' at character ' + this.index);
329
+ error.index = this.index;
330
+ error.description = message;
331
+ throw error;
332
+ }
333
+
334
+ /**
335
+ * Run a given hook
336
+ * @param {string} name
337
+ * @param {jsep.Expression|false} [node]
338
+ * @returns {?jsep.Expression}
339
+ */
340
+ runHook(name, node) {
341
+ if (Jsep.hooks[name]) {
342
+ const env = {
343
+ context: this,
344
+ node
345
+ };
346
+ Jsep.hooks.run(name, env);
347
+ return env.node;
348
+ }
349
+ return node;
350
+ }
351
+
352
+ /**
353
+ * Runs a given hook until one returns a node
354
+ * @param {string} name
355
+ * @returns {?jsep.Expression}
356
+ */
357
+ searchHook(name) {
358
+ if (Jsep.hooks[name]) {
359
+ const env = {
360
+ context: this
361
+ };
362
+ Jsep.hooks[name].find(function (callback) {
363
+ callback.call(env.context, env);
364
+ return env.node;
365
+ });
366
+ return env.node;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Push `index` up to the next non-space character
372
+ */
373
+ gobbleSpaces() {
374
+ let ch = this.code;
375
+ // Whitespace
376
+ while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
377
+ ch = this.expr.charCodeAt(++this.index);
378
+ }
379
+ this.runHook('gobble-spaces');
380
+ }
381
+
382
+ /**
383
+ * Top-level method to parse all expressions and returns compound or single node
384
+ * @returns {jsep.Expression}
385
+ */
386
+ parse() {
387
+ this.runHook('before-all');
388
+ const nodes = this.gobbleExpressions();
389
+
390
+ // If there's only one expression just try returning the expression
391
+ const node = nodes.length === 1 ? nodes[0] : {
392
+ type: Jsep.COMPOUND,
393
+ body: nodes
394
+ };
395
+ return this.runHook('after-all', node);
396
+ }
397
+
398
+ /**
399
+ * top-level parser (but can be reused within as well)
400
+ * @param {number} [untilICode]
401
+ * @returns {jsep.Expression[]}
402
+ */
403
+ gobbleExpressions(untilICode) {
404
+ let nodes = [],
405
+ ch_i,
406
+ node;
407
+ while (this.index < this.expr.length) {
408
+ ch_i = this.code;
409
+
410
+ // Expressions can be separated by semicolons, commas, or just inferred without any
411
+ // separators
412
+ if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
413
+ this.index++; // ignore separators
414
+ } else {
415
+ // Try to gobble each expression individually
416
+ if (node = this.gobbleExpression()) {
417
+ nodes.push(node);
418
+ // If we weren't able to find a binary expression and are out of room, then
419
+ // the expression passed in probably has too much
420
+ } else if (this.index < this.expr.length) {
421
+ if (ch_i === untilICode) {
422
+ break;
423
+ }
424
+ this.throwError('Unexpected "' + this.char + '"');
425
+ }
426
+ }
427
+ }
428
+ return nodes;
429
+ }
430
+
431
+ /**
432
+ * The main parsing function.
433
+ * @returns {?jsep.Expression}
434
+ */
435
+ gobbleExpression() {
436
+ const node = this.searchHook('gobble-expression') || this.gobbleBinaryExpression();
437
+ this.gobbleSpaces();
438
+ return this.runHook('after-expression', node);
439
+ }
440
+
441
+ /**
442
+ * Search for the operation portion of the string (e.g. `+`, `===`)
443
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
444
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
445
+ * then, return that binary operation
446
+ * @returns {string|boolean}
447
+ */
448
+ gobbleBinaryOp() {
449
+ this.gobbleSpaces();
450
+ let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
451
+ let tc_len = to_check.length;
452
+ while (tc_len > 0) {
453
+ // Don't accept a binary op when it is an identifier.
454
+ // Binary ops that start with a identifier-valid character must be followed
455
+ // by a non identifier-part valid character
456
+ if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
457
+ this.index += tc_len;
458
+ return to_check;
459
+ }
460
+ to_check = to_check.substr(0, --tc_len);
461
+ }
462
+ return false;
463
+ }
464
+
465
+ /**
466
+ * This function is responsible for gobbling an individual expression,
467
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
468
+ * @returns {?jsep.BinaryExpression}
469
+ */
470
+ gobbleBinaryExpression() {
471
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
472
+
473
+ // First, try to get the leftmost thing
474
+ // Then, check to see if there's a binary operator operating on that leftmost thing
475
+ // Don't gobbleBinaryOp without a left-hand-side
476
+ left = this.gobbleToken();
477
+ if (!left) {
478
+ return left;
479
+ }
480
+ biop = this.gobbleBinaryOp();
481
+
482
+ // If there wasn't a binary operator, just return the leftmost node
483
+ if (!biop) {
484
+ return left;
485
+ }
486
+
487
+ // Otherwise, we need to start a stack to properly place the binary operations in their
488
+ // precedence structure
489
+ biop_info = {
490
+ value: biop,
491
+ prec: Jsep.binaryPrecedence(biop),
492
+ right_a: Jsep.right_associative.has(biop)
493
+ };
494
+ right = this.gobbleToken();
495
+ if (!right) {
496
+ this.throwError("Expected expression after " + biop);
497
+ }
498
+ stack = [left, biop_info, right];
499
+
500
+ // Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
501
+ while (biop = this.gobbleBinaryOp()) {
502
+ prec = Jsep.binaryPrecedence(biop);
503
+ if (prec === 0) {
504
+ this.index -= biop.length;
505
+ break;
506
+ }
507
+ biop_info = {
508
+ value: biop,
509
+ prec,
510
+ right_a: Jsep.right_associative.has(biop)
511
+ };
512
+ cur_biop = biop;
513
+
514
+ // Reduce: make a binary expression from the three topmost entries.
515
+ const comparePrev = prev => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
516
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
517
+ right = stack.pop();
518
+ biop = stack.pop().value;
519
+ left = stack.pop();
520
+ node = {
521
+ type: Jsep.BINARY_EXP,
522
+ operator: biop,
523
+ left,
524
+ right
525
+ };
526
+ stack.push(node);
527
+ }
528
+ node = this.gobbleToken();
529
+ if (!node) {
530
+ this.throwError("Expected expression after " + cur_biop);
531
+ }
532
+ stack.push(biop_info, node);
533
+ }
534
+ i = stack.length - 1;
535
+ node = stack[i];
536
+ while (i > 1) {
537
+ node = {
538
+ type: Jsep.BINARY_EXP,
539
+ operator: stack[i - 1].value,
540
+ left: stack[i - 2],
541
+ right: node
542
+ };
543
+ i -= 2;
544
+ }
545
+ return node;
546
+ }
547
+
548
+ /**
549
+ * An individual part of a binary expression:
550
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
551
+ * @returns {boolean|jsep.Expression}
552
+ */
553
+ gobbleToken() {
554
+ let ch, to_check, tc_len, node;
555
+ this.gobbleSpaces();
556
+ node = this.searchHook('gobble-token');
557
+ if (node) {
558
+ return this.runHook('after-token', node);
559
+ }
560
+ ch = this.code;
561
+ if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
562
+ // Char code 46 is a dot `.` which can start off a numeric literal
563
+ return this.gobbleNumericLiteral();
564
+ }
565
+ if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
566
+ // Single or double quotes
567
+ node = this.gobbleStringLiteral();
568
+ } else if (ch === Jsep.OBRACK_CODE) {
569
+ node = this.gobbleArray();
570
+ } else {
571
+ to_check = this.expr.substr(this.index, Jsep.max_unop_len);
572
+ tc_len = to_check.length;
573
+ while (tc_len > 0) {
574
+ // Don't accept an unary op when it is an identifier.
575
+ // Unary ops that start with a identifier-valid character must be followed
576
+ // by a non identifier-part valid character
577
+ if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
578
+ this.index += tc_len;
579
+ const argument = this.gobbleToken();
580
+ if (!argument) {
581
+ this.throwError('missing unaryOp argument');
582
+ }
583
+ return this.runHook('after-token', {
584
+ type: Jsep.UNARY_EXP,
585
+ operator: to_check,
586
+ argument,
587
+ prefix: true
588
+ });
589
+ }
590
+ to_check = to_check.substr(0, --tc_len);
591
+ }
592
+ if (Jsep.isIdentifierStart(ch)) {
593
+ node = this.gobbleIdentifier();
594
+ if (Jsep.literals.hasOwnProperty(node.name)) {
595
+ node = {
596
+ type: Jsep.LITERAL,
597
+ value: Jsep.literals[node.name],
598
+ raw: node.name
599
+ };
600
+ } else if (node.name === Jsep.this_str) {
601
+ node = {
602
+ type: Jsep.THIS_EXP
603
+ };
604
+ }
605
+ } else if (ch === Jsep.OPAREN_CODE) {
606
+ // open parenthesis
607
+ node = this.gobbleGroup();
608
+ }
609
+ }
610
+ if (!node) {
611
+ return this.runHook('after-token', false);
612
+ }
613
+ node = this.gobbleTokenProperty(node);
614
+ return this.runHook('after-token', node);
615
+ }
616
+
617
+ /**
618
+ * Gobble properties of of identifiers/strings/arrays/groups.
619
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
620
+ * It also gobbles function calls:
621
+ * e.g. `Math.acos(obj.angle)`
622
+ * @param {jsep.Expression} node
623
+ * @returns {jsep.Expression}
624
+ */
625
+ gobbleTokenProperty(node) {
626
+ this.gobbleSpaces();
627
+ let ch = this.code;
628
+ while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
629
+ let optional;
630
+ if (ch === Jsep.QUMARK_CODE) {
631
+ if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
632
+ break;
633
+ }
634
+ optional = true;
635
+ this.index += 2;
636
+ this.gobbleSpaces();
637
+ ch = this.code;
638
+ }
639
+ this.index++;
640
+ if (ch === Jsep.OBRACK_CODE) {
641
+ node = {
642
+ type: Jsep.MEMBER_EXP,
643
+ computed: true,
644
+ object: node,
645
+ property: this.gobbleExpression()
646
+ };
647
+ if (!node.property) {
648
+ this.throwError('Unexpected "' + this.char + '"');
649
+ }
650
+ this.gobbleSpaces();
651
+ ch = this.code;
652
+ if (ch !== Jsep.CBRACK_CODE) {
653
+ this.throwError('Unclosed [');
654
+ }
655
+ this.index++;
656
+ } else if (ch === Jsep.OPAREN_CODE) {
657
+ // A function call is being made; gobble all the arguments
658
+ node = {
659
+ type: Jsep.CALL_EXP,
660
+ 'arguments': this.gobbleArguments(Jsep.CPAREN_CODE),
661
+ callee: node
662
+ };
663
+ } else if (ch === Jsep.PERIOD_CODE || optional) {
664
+ if (optional) {
665
+ this.index--;
666
+ }
667
+ this.gobbleSpaces();
668
+ node = {
669
+ type: Jsep.MEMBER_EXP,
670
+ computed: false,
671
+ object: node,
672
+ property: this.gobbleIdentifier()
673
+ };
674
+ }
675
+ if (optional) {
676
+ node.optional = true;
677
+ } // else leave undefined for compatibility with esprima
678
+
679
+ this.gobbleSpaces();
680
+ ch = this.code;
681
+ }
682
+ return node;
683
+ }
684
+
685
+ /**
686
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
687
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
688
+ * @returns {jsep.Literal}
689
+ */
690
+ gobbleNumericLiteral() {
691
+ let number = '',
692
+ ch,
693
+ chCode;
694
+ while (Jsep.isDecimalDigit(this.code)) {
695
+ number += this.expr.charAt(this.index++);
696
+ }
697
+ if (this.code === Jsep.PERIOD_CODE) {
698
+ // can start with a decimal marker
699
+ number += this.expr.charAt(this.index++);
700
+ while (Jsep.isDecimalDigit(this.code)) {
701
+ number += this.expr.charAt(this.index++);
702
+ }
703
+ }
704
+ ch = this.char;
705
+ if (ch === 'e' || ch === 'E') {
706
+ // exponent marker
707
+ number += this.expr.charAt(this.index++);
708
+ ch = this.char;
709
+ if (ch === '+' || ch === '-') {
710
+ // exponent sign
711
+ number += this.expr.charAt(this.index++);
712
+ }
713
+ while (Jsep.isDecimalDigit(this.code)) {
714
+ // exponent itself
715
+ number += this.expr.charAt(this.index++);
716
+ }
717
+ if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
718
+ this.throwError('Expected exponent (' + number + this.char + ')');
719
+ }
720
+ }
721
+ chCode = this.code;
722
+
723
+ // Check to make sure this isn't a variable name that start with a number (123abc)
724
+ if (Jsep.isIdentifierStart(chCode)) {
725
+ this.throwError('Variable names cannot start with a number (' + number + this.char + ')');
726
+ } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
727
+ this.throwError('Unexpected period');
728
+ }
729
+ return {
730
+ type: Jsep.LITERAL,
731
+ value: parseFloat(number),
732
+ raw: number
733
+ };
734
+ }
735
+
736
+ /**
737
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
738
+ * e.g. `"hello world"`, `'this is\nJSEP'`
739
+ * @returns {jsep.Literal}
740
+ */
741
+ gobbleStringLiteral() {
742
+ let str = '';
743
+ const startIndex = this.index;
744
+ const quote = this.expr.charAt(this.index++);
745
+ let closed = false;
746
+ while (this.index < this.expr.length) {
747
+ let ch = this.expr.charAt(this.index++);
748
+ if (ch === quote) {
749
+ closed = true;
750
+ break;
751
+ } else if (ch === '\\') {
752
+ // Check for all of the common escape codes
753
+ ch = this.expr.charAt(this.index++);
754
+ switch (ch) {
755
+ case 'n':
756
+ str += '\n';
757
+ break;
758
+ case 'r':
759
+ str += '\r';
760
+ break;
761
+ case 't':
762
+ str += '\t';
763
+ break;
764
+ case 'b':
765
+ str += '\b';
766
+ break;
767
+ case 'f':
768
+ str += '\f';
769
+ break;
770
+ case 'v':
771
+ str += '\x0B';
772
+ break;
773
+ default:
774
+ str += ch;
775
+ }
776
+ } else {
777
+ str += ch;
778
+ }
779
+ }
780
+ if (!closed) {
781
+ this.throwError('Unclosed quote after "' + str + '"');
782
+ }
783
+ return {
784
+ type: Jsep.LITERAL,
785
+ value: str,
786
+ raw: this.expr.substring(startIndex, this.index)
787
+ };
788
+ }
789
+
790
+ /**
791
+ * Gobbles only identifiers
792
+ * e.g.: `foo`, `_value`, `$x1`
793
+ * Also, this function checks if that identifier is a literal:
794
+ * (e.g. `true`, `false`, `null`) or `this`
795
+ * @returns {jsep.Identifier}
796
+ */
797
+ gobbleIdentifier() {
798
+ let ch = this.code,
799
+ start = this.index;
800
+ if (Jsep.isIdentifierStart(ch)) {
801
+ this.index++;
802
+ } else {
803
+ this.throwError('Unexpected ' + this.char);
804
+ }
805
+ while (this.index < this.expr.length) {
806
+ ch = this.code;
807
+ if (Jsep.isIdentifierPart(ch)) {
808
+ this.index++;
809
+ } else {
810
+ break;
811
+ }
812
+ }
813
+ return {
814
+ type: Jsep.IDENTIFIER,
815
+ name: this.expr.slice(start, this.index)
816
+ };
817
+ }
818
+
819
+ /**
820
+ * Gobbles a list of arguments within the context of a function call
821
+ * or array literal. This function also assumes that the opening character
822
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
823
+ * until the terminator character `)` or `]` is encountered.
824
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
825
+ * @param {number} termination
826
+ * @returns {jsep.Expression[]}
827
+ */
828
+ gobbleArguments(termination) {
829
+ const args = [];
830
+ let closed = false;
831
+ let separator_count = 0;
832
+ while (this.index < this.expr.length) {
833
+ this.gobbleSpaces();
834
+ let ch_i = this.code;
835
+ if (ch_i === termination) {
836
+ // done parsing
837
+ closed = true;
838
+ this.index++;
839
+ if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
840
+ this.throwError('Unexpected token ' + String.fromCharCode(termination));
841
+ }
842
+ break;
843
+ } else if (ch_i === Jsep.COMMA_CODE) {
844
+ // between expressions
845
+ this.index++;
846
+ separator_count++;
847
+ if (separator_count !== args.length) {
848
+ // missing argument
849
+ if (termination === Jsep.CPAREN_CODE) {
850
+ this.throwError('Unexpected token ,');
851
+ } else if (termination === Jsep.CBRACK_CODE) {
852
+ for (let arg = args.length; arg < separator_count; arg++) {
853
+ args.push(null);
854
+ }
855
+ }
856
+ }
857
+ } else if (args.length !== separator_count && separator_count !== 0) {
858
+ // NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments
859
+ this.throwError('Expected comma');
860
+ } else {
861
+ const node = this.gobbleExpression();
862
+ if (!node || node.type === Jsep.COMPOUND) {
863
+ this.throwError('Expected comma');
864
+ }
865
+ args.push(node);
866
+ }
867
+ }
868
+ if (!closed) {
869
+ this.throwError('Expected ' + String.fromCharCode(termination));
870
+ }
871
+ return args;
872
+ }
873
+
874
+ /**
875
+ * Responsible for parsing a group of things within parentheses `()`
876
+ * that have no identifier in front (so not a function call)
877
+ * This function assumes that it needs to gobble the opening parenthesis
878
+ * and then tries to gobble everything within that parenthesis, assuming
879
+ * that the next thing it should see is the close parenthesis. If not,
880
+ * then the expression probably doesn't have a `)`
881
+ * @returns {boolean|jsep.Expression}
882
+ */
883
+ gobbleGroup() {
884
+ this.index++;
885
+ let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
886
+ if (this.code === Jsep.CPAREN_CODE) {
887
+ this.index++;
888
+ if (nodes.length === 1) {
889
+ return nodes[0];
890
+ } else if (!nodes.length) {
891
+ return false;
892
+ } else {
893
+ return {
894
+ type: Jsep.SEQUENCE_EXP,
895
+ expressions: nodes
896
+ };
897
+ }
898
+ } else {
899
+ this.throwError('Unclosed (');
900
+ }
901
+ }
902
+
903
+ /**
904
+ * Responsible for parsing Array literals `[1, 2, 3]`
905
+ * This function assumes that it needs to gobble the opening bracket
906
+ * and then tries to gobble the expressions as arguments.
907
+ * @returns {jsep.ArrayExpression}
908
+ */
909
+ gobbleArray() {
910
+ this.index++;
911
+ return {
912
+ type: Jsep.ARRAY_EXP,
913
+ elements: this.gobbleArguments(Jsep.CBRACK_CODE)
914
+ };
915
+ }
916
+ }
917
+
918
+ // Static fields:
919
+ const hooks = new Hooks();
920
+ Object.assign(Jsep, {
921
+ hooks,
922
+ plugins: new Plugins(Jsep),
923
+ // Node Types
924
+ // ----------
925
+ // This is the full set of types that any JSEP node can be.
926
+ // Store them here to save space when minified
927
+ COMPOUND: 'Compound',
928
+ SEQUENCE_EXP: 'SequenceExpression',
929
+ IDENTIFIER: 'Identifier',
930
+ MEMBER_EXP: 'MemberExpression',
931
+ LITERAL: 'Literal',
932
+ THIS_EXP: 'ThisExpression',
933
+ CALL_EXP: 'CallExpression',
934
+ UNARY_EXP: 'UnaryExpression',
935
+ BINARY_EXP: 'BinaryExpression',
936
+ ARRAY_EXP: 'ArrayExpression',
937
+ TAB_CODE: 9,
938
+ LF_CODE: 10,
939
+ CR_CODE: 13,
940
+ SPACE_CODE: 32,
941
+ PERIOD_CODE: 46,
942
+ // '.'
943
+ COMMA_CODE: 44,
944
+ // ','
945
+ SQUOTE_CODE: 39,
946
+ // single quote
947
+ DQUOTE_CODE: 34,
948
+ // double quotes
949
+ OPAREN_CODE: 40,
950
+ // (
951
+ CPAREN_CODE: 41,
952
+ // )
953
+ OBRACK_CODE: 91,
954
+ // [
955
+ CBRACK_CODE: 93,
956
+ // ]
957
+ QUMARK_CODE: 63,
958
+ // ?
959
+ SEMCOL_CODE: 59,
960
+ // ;
961
+ COLON_CODE: 58,
962
+ // :
963
+
964
+ // Operations
965
+ // ----------
966
+ // Use a quickly-accessible map to store all of the unary operators
967
+ // Values are set to `1` (it really doesn't matter)
968
+ unary_ops: {
969
+ '-': 1,
970
+ '!': 1,
971
+ '~': 1,
972
+ '+': 1
973
+ },
974
+ // Also use a map for the binary operations but set their values to their
975
+ // binary precedence for quick reference (higher number = higher precedence)
976
+ // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
977
+ binary_ops: {
978
+ '||': 1,
979
+ '??': 1,
980
+ '&&': 2,
981
+ '|': 3,
982
+ '^': 4,
983
+ '&': 5,
984
+ '==': 6,
985
+ '!=': 6,
986
+ '===': 6,
987
+ '!==': 6,
988
+ '<': 7,
989
+ '>': 7,
990
+ '<=': 7,
991
+ '>=': 7,
992
+ '<<': 8,
993
+ '>>': 8,
994
+ '>>>': 8,
995
+ '+': 9,
996
+ '-': 9,
997
+ '*': 10,
998
+ '/': 10,
999
+ '%': 10,
1000
+ '**': 11
1001
+ },
1002
+ // sets specific binary_ops as right-associative
1003
+ right_associative: new Set(['**']),
1004
+ // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
1005
+ additional_identifier_chars: new Set(['$', '_']),
1006
+ // Literals
1007
+ // ----------
1008
+ // Store the values to return for the various literals we may encounter
1009
+ literals: {
1010
+ 'true': true,
1011
+ 'false': false,
1012
+ 'null': null
1013
+ },
1014
+ // Except for `this`, which is special. This could be changed to something like `'self'` as well
1015
+ this_str: 'this'
1016
+ });
1017
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
1018
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
1019
+
1020
+ // Backward Compatibility:
1021
+ const jsep = expr => new Jsep(expr).parse();
1022
+ const stdClassProps = Object.getOwnPropertyNames(class Test {});
1023
+ Object.getOwnPropertyNames(Jsep).filter(prop => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach(m => {
1024
+ jsep[m] = Jsep[m];
1025
+ });
1026
+ jsep.Jsep = Jsep; // allows for const { Jsep } = require('jsep');
1027
+
1028
+ const CONDITIONAL_EXP = 'ConditionalExpression';
1029
+ var ternary = {
1030
+ name: 'ternary',
1031
+ init(jsep) {
1032
+ // Ternary expression: test ? consequent : alternate
1033
+ jsep.hooks.add('after-expression', function gobbleTernary(env) {
1034
+ if (env.node && this.code === jsep.QUMARK_CODE) {
1035
+ this.index++;
1036
+ const test = env.node;
1037
+ const consequent = this.gobbleExpression();
1038
+ if (!consequent) {
1039
+ this.throwError('Expected expression');
1040
+ }
1041
+ this.gobbleSpaces();
1042
+ if (this.code === jsep.COLON_CODE) {
1043
+ this.index++;
1044
+ const alternate = this.gobbleExpression();
1045
+ if (!alternate) {
1046
+ this.throwError('Expected expression');
1047
+ }
1048
+ env.node = {
1049
+ type: CONDITIONAL_EXP,
1050
+ test,
1051
+ consequent,
1052
+ alternate
1053
+ };
1054
+
1055
+ // check for operators of higher priority than ternary (i.e. assignment)
1056
+ // jsep sets || at 1, and assignment at 0.9, and conditional should be between them
1057
+ if (test.operator && jsep.binary_ops[test.operator] <= 0.9) {
1058
+ let newTest = test;
1059
+ while (newTest.right.operator && jsep.binary_ops[newTest.right.operator] <= 0.9) {
1060
+ newTest = newTest.right;
1061
+ }
1062
+ env.node.test = newTest.right;
1063
+ newTest.right = env.node;
1064
+ env.node = test;
1065
+ }
1066
+ } else {
1067
+ this.throwError('Expected :');
1068
+ }
1069
+ }
1070
+ });
1071
+ }
1072
+ };
1073
+
1074
+ // Add default plugins:
1075
+
1076
+ jsep.plugins.register(ternary);
1077
+
1078
+ const FSLASH_CODE = 47; // '/'
1079
+ const BSLASH_CODE = 92; // '\\'
1080
+
1081
+ var index = {
1082
+ name: 'regex',
1083
+ init(jsep) {
1084
+ // Regex literal: /abc123/ig
1085
+ jsep.hooks.add('gobble-token', function gobbleRegexLiteral(env) {
1086
+ if (this.code === FSLASH_CODE) {
1087
+ const patternIndex = ++this.index;
1088
+ let inCharSet = false;
1089
+ while (this.index < this.expr.length) {
1090
+ if (this.code === FSLASH_CODE && !inCharSet) {
1091
+ const pattern = this.expr.slice(patternIndex, this.index);
1092
+ let flags = '';
1093
+ while (++this.index < this.expr.length) {
1094
+ const code = this.code;
1095
+ if (code >= 97 && code <= 122 // a...z
1096
+ || code >= 65 && code <= 90 // A...Z
1097
+ || code >= 48 && code <= 57) {
1098
+ // 0-9
1099
+ flags += this.char;
1100
+ } else {
1101
+ break;
1102
+ }
1103
+ }
1104
+ let value;
1105
+ try {
1106
+ value = new RegExp(pattern, flags);
1107
+ } catch (e) {
1108
+ this.throwError(e.message);
1109
+ }
1110
+ env.node = {
1111
+ type: jsep.LITERAL,
1112
+ value,
1113
+ raw: this.expr.slice(patternIndex - 1, this.index)
1114
+ };
1115
+
1116
+ // allow . [] and () after regex: /regex/.test(a)
1117
+ env.node = this.gobbleTokenProperty(env.node);
1118
+ return env.node;
1119
+ }
1120
+ if (this.code === jsep.OBRACK_CODE) {
1121
+ inCharSet = true;
1122
+ } else if (inCharSet && this.code === jsep.CBRACK_CODE) {
1123
+ inCharSet = false;
1124
+ }
1125
+ this.index += this.code === BSLASH_CODE ? 2 : 1;
1126
+ }
1127
+ this.throwError('Unclosed Regex');
1128
+ }
1129
+ });
1130
+ }
1131
+ };
1132
+
1133
+ const PLUS_CODE = 43; // +
1134
+ const MINUS_CODE = 45; // -
1135
+
1136
+ const plugin = {
1137
+ name: 'assignment',
1138
+ assignmentOperators: new Set(['=', '*=', '**=', '/=', '%=', '+=', '-=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '||=', '&&=', '??=']),
1139
+ updateOperators: [PLUS_CODE, MINUS_CODE],
1140
+ assignmentPrecedence: 0.9,
1141
+ init(jsep) {
1142
+ const updateNodeTypes = [jsep.IDENTIFIER, jsep.MEMBER_EXP];
1143
+ plugin.assignmentOperators.forEach(op => jsep.addBinaryOp(op, plugin.assignmentPrecedence, true));
1144
+ jsep.hooks.add('gobble-token', function gobbleUpdatePrefix(env) {
1145
+ const code = this.code;
1146
+ if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {
1147
+ this.index += 2;
1148
+ env.node = {
1149
+ type: 'UpdateExpression',
1150
+ operator: code === PLUS_CODE ? '++' : '--',
1151
+ argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
1152
+ prefix: true
1153
+ };
1154
+ if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
1155
+ this.throwError(`Unexpected ${env.node.operator}`);
1156
+ }
1157
+ }
1158
+ });
1159
+ jsep.hooks.add('after-token', function gobbleUpdatePostfix(env) {
1160
+ if (env.node) {
1161
+ const code = this.code;
1162
+ if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {
1163
+ if (!updateNodeTypes.includes(env.node.type)) {
1164
+ this.throwError(`Unexpected ${env.node.operator}`);
1165
+ }
1166
+ this.index += 2;
1167
+ env.node = {
1168
+ type: 'UpdateExpression',
1169
+ operator: code === PLUS_CODE ? '++' : '--',
1170
+ argument: env.node,
1171
+ prefix: false
1172
+ };
1173
+ }
1174
+ }
1175
+ });
1176
+ jsep.hooks.add('after-expression', function gobbleAssignment(env) {
1177
+ if (env.node) {
1178
+ // Note: Binaries can be chained in a single expression to respect
1179
+ // operator precedence (i.e. a = b = 1 + 2 + 3)
1180
+ // Update all binary assignment nodes in the tree
1181
+ updateBinariesToAssignments(env.node);
1182
+ }
1183
+ });
1184
+ function updateBinariesToAssignments(node) {
1185
+ if (plugin.assignmentOperators.has(node.operator)) {
1186
+ node.type = 'AssignmentExpression';
1187
+ updateBinariesToAssignments(node.left);
1188
+ updateBinariesToAssignments(node.right);
1189
+ } else if (!node.operator) {
1190
+ Object.values(node).forEach(val => {
1191
+ if (val && typeof val === 'object') {
1192
+ updateBinariesToAssignments(val);
1193
+ }
1194
+ });
1195
+ }
1196
+ }
1197
+ }
1198
+ };
1199
+
1200
+ /* eslint-disable no-bitwise -- Convenient */
1201
+
1202
+ // register plugins
1203
+ jsep.plugins.register(index, plugin);
1204
+ jsep.addUnaryOp('typeof');
1205
+ jsep.addLiteral('null', null);
1206
+ jsep.addLiteral('undefined', undefined);
1207
+ const BLOCKED_PROTO_PROPERTIES = new Set(['constructor', '__proto__', '__defineGetter__', '__defineSetter__']);
1208
+ const SafeEval = {
1209
+ /**
1210
+ * @param {jsep.Expression} ast
1211
+ * @param {Record<string, any>} subs
1212
+ */
1213
+ evalAst(ast, subs) {
1214
+ switch (ast.type) {
1215
+ case 'BinaryExpression':
1216
+ case 'LogicalExpression':
1217
+ return SafeEval.evalBinaryExpression(ast, subs);
1218
+ case 'Compound':
1219
+ return SafeEval.evalCompound(ast, subs);
1220
+ case 'ConditionalExpression':
1221
+ return SafeEval.evalConditionalExpression(ast, subs);
1222
+ case 'Identifier':
1223
+ return SafeEval.evalIdentifier(ast, subs);
1224
+ case 'Literal':
1225
+ return SafeEval.evalLiteral(ast, subs);
1226
+ case 'MemberExpression':
1227
+ return SafeEval.evalMemberExpression(ast, subs);
1228
+ case 'UnaryExpression':
1229
+ return SafeEval.evalUnaryExpression(ast, subs);
1230
+ case 'ArrayExpression':
1231
+ return SafeEval.evalArrayExpression(ast, subs);
1232
+ case 'CallExpression':
1233
+ return SafeEval.evalCallExpression(ast, subs);
1234
+ case 'AssignmentExpression':
1235
+ return SafeEval.evalAssignmentExpression(ast, subs);
1236
+ default:
1237
+ throw SyntaxError('Unexpected expression', ast);
1238
+ }
1239
+ },
1240
+ evalBinaryExpression(ast, subs) {
1241
+ const result = {
1242
+ '||': (a, b) => a || b(),
1243
+ '&&': (a, b) => a && b(),
1244
+ '|': (a, b) => a | b(),
1245
+ '^': (a, b) => a ^ b(),
1246
+ '&': (a, b) => a & b(),
1247
+ // eslint-disable-next-line eqeqeq -- API
1248
+ '==': (a, b) => a == b(),
1249
+ // eslint-disable-next-line eqeqeq -- API
1250
+ '!=': (a, b) => a != b(),
1251
+ '===': (a, b) => a === b(),
1252
+ '!==': (a, b) => a !== b(),
1253
+ '<': (a, b) => a < b(),
1254
+ '>': (a, b) => a > b(),
1255
+ '<=': (a, b) => a <= b(),
1256
+ '>=': (a, b) => a >= b(),
1257
+ '<<': (a, b) => a << b(),
1258
+ '>>': (a, b) => a >> b(),
1259
+ '>>>': (a, b) => a >>> b(),
1260
+ '+': (a, b) => a + b(),
1261
+ '-': (a, b) => a - b(),
1262
+ '*': (a, b) => a * b(),
1263
+ '/': (a, b) => a / b(),
1264
+ '%': (a, b) => a % b()
1265
+ }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
1266
+ return result;
1267
+ },
1268
+ evalCompound(ast, subs) {
1269
+ let last;
1270
+ for (let i = 0; i < ast.body.length; i++) {
1271
+ if (ast.body[i].type === 'Identifier' && ['var', 'let', 'const'].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === 'AssignmentExpression') {
1272
+ // var x=2; is detected as
1273
+ // [{Identifier var}, {AssignmentExpression x=2}]
1274
+ // eslint-disable-next-line @stylistic/max-len -- Long
1275
+ // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
1276
+ i += 1;
1277
+ }
1278
+ const expr = ast.body[i];
1279
+ last = SafeEval.evalAst(expr, subs);
1280
+ }
1281
+ return last;
1282
+ },
1283
+ evalConditionalExpression(ast, subs) {
1284
+ if (SafeEval.evalAst(ast.test, subs)) {
1285
+ return SafeEval.evalAst(ast.consequent, subs);
1286
+ }
1287
+ return SafeEval.evalAst(ast.alternate, subs);
1288
+ },
1289
+ evalIdentifier(ast, subs) {
1290
+ if (Object.hasOwn(subs, ast.name)) {
1291
+ return subs[ast.name];
1292
+ }
1293
+ throw ReferenceError(`${ast.name} is not defined`);
1294
+ },
1295
+ evalLiteral(ast) {
1296
+ return ast.value;
1297
+ },
1298
+ evalMemberExpression(ast, subs) {
1299
+ const prop = String(
1300
+ // NOTE: `String(value)` throws error when
1301
+ // value has overwritten the toString method to return non-string
1302
+ // i.e. `value = {toString: () => []}`
1303
+ ast.computed ? SafeEval.evalAst(ast.property) // `object[property]`
1304
+ : ast.property.name // `object.property` property is Identifier
1305
+ );
1306
+ const obj = SafeEval.evalAst(ast.object, subs);
1307
+ if (obj === undefined || obj === null) {
1308
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
1309
+ }
1310
+ if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
1311
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
1312
+ }
1313
+ const result = obj[prop];
1314
+ if (typeof result === 'function') {
1315
+ return result.bind(obj); // arrow functions aren't affected by bind.
1316
+ }
1317
+ return result;
1318
+ },
1319
+ evalUnaryExpression(ast, subs) {
1320
+ const result = {
1321
+ '-': a => -SafeEval.evalAst(a, subs),
1322
+ '!': a => !SafeEval.evalAst(a, subs),
1323
+ '~': a => ~SafeEval.evalAst(a, subs),
1324
+ // eslint-disable-next-line no-implicit-coercion -- API
1325
+ '+': a => +SafeEval.evalAst(a, subs),
1326
+ typeof: a => typeof SafeEval.evalAst(a, subs)
1327
+ }[ast.operator](ast.argument);
1328
+ return result;
1329
+ },
1330
+ evalArrayExpression(ast, subs) {
1331
+ return ast.elements.map(el => SafeEval.evalAst(el, subs));
1332
+ },
1333
+ evalCallExpression(ast, subs) {
1334
+ const args = ast.arguments.map(arg => SafeEval.evalAst(arg, subs));
1335
+ const func = SafeEval.evalAst(ast.callee, subs);
1336
+ // if (func === Function) {
1337
+ // throw new Error('Function constructor is disabled');
1338
+ // }
1339
+ return func(...args);
1340
+ },
1341
+ evalAssignmentExpression(ast, subs) {
1342
+ if (ast.left.type !== 'Identifier') {
1343
+ throw SyntaxError('Invalid left-hand side in assignment');
1344
+ }
1345
+ const id = ast.left.name;
1346
+ const value = SafeEval.evalAst(ast.right, subs);
1347
+ subs[id] = value;
1348
+ return subs[id];
1349
+ }
1350
+ };
1351
+
1352
+ /**
1353
+ * A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.
1354
+ */
1355
+ class SafeScript {
1356
+ /**
1357
+ * @param {string} expr Expression to evaluate
1358
+ */
1359
+ constructor(expr) {
1360
+ this.code = expr;
1361
+ this.ast = jsep(this.code);
1362
+ }
1363
+
1364
+ /**
1365
+ * @param {object} context Object whose items will be added
1366
+ * to evaluation
1367
+ * @returns {EvaluatedResult} Result of evaluated code
1368
+ */
1369
+ runInNewContext(context) {
1370
+ // `Object.create(null)` creates a prototypeless object
1371
+ const keyMap = Object.assign(Object.create(null), context);
1372
+ return SafeEval.evalAst(this.ast, keyMap);
1373
+ }
1374
+ }
1375
+
1376
+ /* eslint-disable camelcase -- Convenient for escaping */
1377
+
1378
+
1379
+ /**
1380
+ * @typedef {null|boolean|number|string|object|GenericArray} JSONObject
1381
+ */
1382
+
1383
+ /**
1384
+ * @typedef {any} AnyItem
1385
+ */
1386
+
1387
+ /**
1388
+ * @typedef {any} AnyResult
1389
+ */
1390
+
1391
+ /**
1392
+ * Copies array and then pushes item into it.
1393
+ * @param {GenericArray} arr Array to copy and into which to push
1394
+ * @param {AnyItem} item Array item to add (to end)
1395
+ * @returns {GenericArray} Copy of the original array
1396
+ */
1397
+ function push(arr, item) {
1398
+ arr = arr.slice();
1399
+ arr.push(item);
1400
+ return arr;
1401
+ }
1402
+ /**
1403
+ * Copies array and then unshifts item into it.
1404
+ * @param {AnyItem} item Array item to add (to beginning)
1405
+ * @param {GenericArray} arr Array to copy and into which to unshift
1406
+ * @returns {GenericArray} Copy of the original array
1407
+ */
1408
+ function unshift(item, arr) {
1409
+ arr = arr.slice();
1410
+ arr.unshift(item);
1411
+ return arr;
1412
+ }
1413
+
1414
+ /**
1415
+ * Caught when JSONPath is used without `new` but rethrown if with `new`
1416
+ * @extends Error
1417
+ */
1418
+ class NewError extends Error {
1419
+ /**
1420
+ * @param {AnyResult} value The evaluated scalar value
1421
+ */
1422
+ constructor(value) {
1423
+ super('JSONPath should not be called with "new" (it prevents return ' + 'of (unwrapped) scalar values)');
1424
+ this.avoidNew = true;
1425
+ this.value = value;
1426
+ this.name = 'NewError';
1427
+ }
1428
+ }
1429
+
1430
+ /**
1431
+ * @typedef {object} ReturnObject
1432
+ * @property {string} path
1433
+ * @property {JSONObject} value
1434
+ * @property {object|GenericArray} parent
1435
+ * @property {string} parentProperty
1436
+ */
1437
+
1438
+ /**
1439
+ * @callback JSONPathCallback
1440
+ * @param {string|object} preferredOutput
1441
+ * @param {"value"|"property"} type
1442
+ * @param {ReturnObject} fullRetObj
1443
+ * @returns {void}
1444
+ */
1445
+
1446
+ /**
1447
+ * @callback OtherTypeCallback
1448
+ * @param {JSONObject} val
1449
+ * @param {string} path
1450
+ * @param {object|GenericArray} parent
1451
+ * @param {string} parentPropName
1452
+ * @returns {boolean}
1453
+ */
1454
+
1455
+ /**
1456
+ * @typedef {any} ContextItem
1457
+ */
1458
+
1459
+ /**
1460
+ * @typedef {any} EvaluatedResult
1461
+ */
1462
+
1463
+ /**
1464
+ * @callback EvalCallback
1465
+ * @param {string} code
1466
+ * @param {ContextItem} context
1467
+ * @returns {EvaluatedResult}
1468
+ */
1469
+
1470
+ /**
1471
+ * @typedef {typeof SafeScript} EvalClass
1472
+ */
1473
+
1474
+ /**
1475
+ * @typedef {object} JSONPathOptions
1476
+ * @property {JSON} json
1477
+ * @property {string|string[]} path
1478
+ * @property {"value"|"path"|"pointer"|"parent"|"parentProperty"|
1479
+ * "all"} [resultType="value"]
1480
+ * @property {boolean} [flatten=false]
1481
+ * @property {boolean} [wrap=true]
1482
+ * @property {object} [sandbox={}]
1483
+ * @property {EvalCallback|EvalClass|'safe'|'native'|
1484
+ * boolean} [eval = 'safe']
1485
+ * @property {object|GenericArray|null} [parent=null]
1486
+ * @property {string|null} [parentProperty=null]
1487
+ * @property {JSONPathCallback} [callback]
1488
+ * @property {OtherTypeCallback} [otherTypeCallback] Defaults to
1489
+ * function which throws on encountering `@other`
1490
+ * @property {boolean} [autostart=true]
1491
+ */
1492
+
1493
+ /**
1494
+ * @param {string|JSONPathOptions} opts If a string, will be treated as `expr`
1495
+ * @param {string} [expr] JSON path to evaluate
1496
+ * @param {JSON} [obj] JSON object to evaluate against
1497
+ * @param {JSONPathCallback} [callback] Passed 3 arguments: 1) desired payload
1498
+ * per `resultType`, 2) `"value"|"property"`, 3) Full returned object with
1499
+ * all payloads
1500
+ * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the end
1501
+ * of one's query, this will be invoked with the value of the item, its
1502
+ * path, its parent, and its parent's property name, and it should return
1503
+ * a boolean indicating whether the supplied value belongs to the "other"
1504
+ * type or not (or it may handle transformations and return `false`).
1505
+ * @returns {JSONPath}
1506
+ * @class
1507
+ */
1508
+ function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
1509
+ // eslint-disable-next-line no-restricted-syntax -- Allow for pseudo-class
1510
+ if (!(this instanceof JSONPath)) {
1511
+ try {
1512
+ return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
1513
+ } catch (e) {
1514
+ if (!e.avoidNew) {
1515
+ throw e;
1516
+ }
1517
+ return e.value;
1518
+ }
1519
+ }
1520
+ if (typeof opts === 'string') {
1521
+ otherTypeCallback = callback;
1522
+ callback = obj;
1523
+ obj = expr;
1524
+ expr = opts;
1525
+ opts = null;
1526
+ }
1527
+ const optObj = opts && typeof opts === 'object';
1528
+ opts = opts || {};
1529
+ this.json = opts.json || obj;
1530
+ this.path = opts.path || expr;
1531
+ this.resultType = opts.resultType || 'value';
1532
+ this.flatten = opts.flatten || false;
1533
+ this.wrap = Object.hasOwn(opts, 'wrap') ? opts.wrap : true;
1534
+ this.sandbox = opts.sandbox || {};
1535
+ this.eval = opts.eval === undefined ? 'safe' : opts.eval;
1536
+ this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === 'undefined' ? false : opts.ignoreEvalErrors;
1537
+ this.parent = opts.parent || null;
1538
+ this.parentProperty = opts.parentProperty || null;
1539
+ this.callback = opts.callback || callback || null;
1540
+ this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () {
1541
+ throw new TypeError('You must supply an otherTypeCallback callback option ' + 'with the @other() operator.');
1542
+ };
1543
+ if (opts.autostart !== false) {
1544
+ const args = {
1545
+ path: optObj ? opts.path : expr
1546
+ };
1547
+ if (!optObj) {
1548
+ args.json = obj;
1549
+ } else if ('json' in opts) {
1550
+ args.json = opts.json;
1551
+ }
1552
+ const ret = this.evaluate(args);
1553
+ if (!ret || typeof ret !== 'object') {
1554
+ throw new NewError(ret);
1555
+ }
1556
+ return ret;
1557
+ }
1558
+ }
1559
+
1560
+ // PUBLIC METHODS
1561
+ JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) {
1562
+ let currParent = this.parent,
1563
+ currParentProperty = this.parentProperty;
1564
+ let {
1565
+ flatten,
1566
+ wrap
1567
+ } = this;
1568
+ this.currResultType = this.resultType;
1569
+ this.currEval = this.eval;
1570
+ this.currSandbox = this.sandbox;
1571
+ callback = callback || this.callback;
1572
+ this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
1573
+ json = json || this.json;
1574
+ expr = expr || this.path;
1575
+ if (expr && typeof expr === 'object' && !Array.isArray(expr)) {
1576
+ if (!expr.path && expr.path !== '') {
1577
+ throw new TypeError('You must supply a "path" property when providing an object ' + 'argument to JSONPath.evaluate().');
1578
+ }
1579
+ if (!Object.hasOwn(expr, 'json')) {
1580
+ throw new TypeError('You must supply a "json" property when providing an object ' + 'argument to JSONPath.evaluate().');
1581
+ }
1582
+ ({
1583
+ json
1584
+ } = expr);
1585
+ flatten = Object.hasOwn(expr, 'flatten') ? expr.flatten : flatten;
1586
+ this.currResultType = Object.hasOwn(expr, 'resultType') ? expr.resultType : this.currResultType;
1587
+ this.currSandbox = Object.hasOwn(expr, 'sandbox') ? expr.sandbox : this.currSandbox;
1588
+ wrap = Object.hasOwn(expr, 'wrap') ? expr.wrap : wrap;
1589
+ this.currEval = Object.hasOwn(expr, 'eval') ? expr.eval : this.currEval;
1590
+ callback = Object.hasOwn(expr, 'callback') ? expr.callback : callback;
1591
+ this.currOtherTypeCallback = Object.hasOwn(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback;
1592
+ currParent = Object.hasOwn(expr, 'parent') ? expr.parent : currParent;
1593
+ currParentProperty = Object.hasOwn(expr, 'parentProperty') ? expr.parentProperty : currParentProperty;
1594
+ expr = expr.path;
1595
+ }
1596
+ currParent = currParent || null;
1597
+ currParentProperty = currParentProperty || null;
1598
+ if (Array.isArray(expr)) {
1599
+ expr = JSONPath.toPathString(expr);
1600
+ }
1601
+ if (!expr && expr !== '' || !json) {
1602
+ return undefined;
1603
+ }
1604
+ const exprList = JSONPath.toPathArray(expr);
1605
+ if (exprList[0] === '$' && exprList.length > 1) {
1606
+ exprList.shift();
1607
+ }
1608
+ this._hasParentSelector = null;
1609
+ const result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) {
1610
+ return ea && !ea.isParentSelector;
1611
+ });
1612
+ if (!result.length) {
1613
+ return wrap ? [] : undefined;
1614
+ }
1615
+ if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
1616
+ return this._getPreferredOutput(result[0]);
1617
+ }
1618
+ return result.reduce((rslt, ea) => {
1619
+ const valOrPath = this._getPreferredOutput(ea);
1620
+ if (flatten && Array.isArray(valOrPath)) {
1621
+ rslt = rslt.concat(valOrPath);
1622
+ } else {
1623
+ rslt.push(valOrPath);
1624
+ }
1625
+ return rslt;
1626
+ }, []);
1627
+ };
1628
+
1629
+ // PRIVATE METHODS
1630
+
1631
+ JSONPath.prototype._getPreferredOutput = function (ea) {
1632
+ const resultType = this.currResultType;
1633
+ switch (resultType) {
1634
+ case 'all':
1635
+ {
1636
+ const path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
1637
+ ea.pointer = JSONPath.toPointer(path);
1638
+ ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path);
1639
+ return ea;
1640
+ }
1641
+ case 'value':
1642
+ case 'parent':
1643
+ case 'parentProperty':
1644
+ return ea[resultType];
1645
+ case 'path':
1646
+ return JSONPath.toPathString(ea[resultType]);
1647
+ case 'pointer':
1648
+ return JSONPath.toPointer(ea.path);
1649
+ default:
1650
+ throw new TypeError('Unknown result type');
1651
+ }
1652
+ };
1653
+ JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) {
1654
+ if (callback) {
1655
+ const preferredOutput = this._getPreferredOutput(fullRetObj);
1656
+ fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
1657
+ // eslint-disable-next-line n/callback-return -- No need to return
1658
+ callback(preferredOutput, type, fullRetObj);
1659
+ }
1660
+ };
1661
+
1662
+ /**
1663
+ *
1664
+ * @param {string} expr
1665
+ * @param {JSONObject} val
1666
+ * @param {string} path
1667
+ * @param {object|GenericArray} parent
1668
+ * @param {string} parentPropName
1669
+ * @param {JSONPathCallback} callback
1670
+ * @param {boolean} hasArrExpr
1671
+ * @param {boolean} literalPriority
1672
+ * @returns {ReturnObject|ReturnObject[]}
1673
+ */
1674
+ JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) {
1675
+ // No expr to follow? return path and value as the result of
1676
+ // this trace branch
1677
+ let retObj;
1678
+ if (!expr.length) {
1679
+ retObj = {
1680
+ path,
1681
+ value: val,
1682
+ parent,
1683
+ parentProperty: parentPropName,
1684
+ hasArrExpr
1685
+ };
1686
+ this._handleCallback(retObj, callback, 'value');
1687
+ return retObj;
1688
+ }
1689
+ const loc = expr[0],
1690
+ x = expr.slice(1);
1691
+
1692
+ // We need to gather the return value of recursive trace calls in order to
1693
+ // do the parent sel computation.
1694
+ const ret = [];
1695
+ /**
1696
+ *
1697
+ * @param {ReturnObject|ReturnObject[]} elems
1698
+ * @returns {void}
1699
+ */
1700
+ function addRet(elems) {
1701
+ if (Array.isArray(elems)) {
1702
+ // This was causing excessive stack size in Node (with or
1703
+ // without Babel) against our performance test:
1704
+ // `ret.push(...elems);`
1705
+ elems.forEach(t => {
1706
+ ret.push(t);
1707
+ });
1708
+ } else {
1709
+ ret.push(elems);
1710
+ }
1711
+ }
1712
+ if ((typeof loc !== 'string' || literalPriority) && val && Object.hasOwn(val, loc)) {
1713
+ // simple case--directly follow property
1714
+ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr));
1715
+ // eslint-disable-next-line unicorn/prefer-switch -- Part of larger `if`
1716
+ } else if (loc === '*') {
1717
+ // all child properties
1718
+ this._walk(val, m => {
1719
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true, true));
1720
+ });
1721
+ } else if (loc === '..') {
1722
+ // all descendent parent properties
1723
+ // Check remaining expression with val's immediate children
1724
+ addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr));
1725
+ this._walk(val, m => {
1726
+ // We don't join m and x here because we only want parents,
1727
+ // not scalar values
1728
+ if (typeof val[m] === 'object') {
1729
+ // Keep going with recursive descent on val's
1730
+ // object children
1731
+ addRet(this._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));
1732
+ }
1733
+ });
1734
+ // The parent sel computation is handled in the frame above using the
1735
+ // ancestor object of val
1736
+ } else if (loc === '^') {
1737
+ // This is not a final endpoint, so we do not invoke the callback here
1738
+ this._hasParentSelector = true;
1739
+ return {
1740
+ path: path.slice(0, -1),
1741
+ expr: x,
1742
+ isParentSelector: true
1743
+ };
1744
+ } else if (loc === '~') {
1745
+ // property name
1746
+ retObj = {
1747
+ path: push(path, loc),
1748
+ value: parentPropName,
1749
+ parent,
1750
+ parentProperty: null
1751
+ };
1752
+ this._handleCallback(retObj, callback, 'property');
1753
+ return retObj;
1754
+ } else if (loc === '$') {
1755
+ // root only
1756
+ addRet(this._trace(x, val, path, null, null, callback, hasArrExpr));
1757
+ } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
1758
+ // [start:end:step] Python slice syntax
1759
+ addRet(this._slice(loc, x, val, path, parent, parentPropName, callback));
1760
+ } else if (loc.indexOf('?(') === 0) {
1761
+ // [?(expr)] (filtering)
1762
+ if (this.currEval === false) {
1763
+ throw new Error('Eval [?(expr)] prevented in JSONPath expression.');
1764
+ }
1765
+ const safeLoc = loc.replace(/^\?\((.*?)\)$/u, '$1');
1766
+ // check for a nested filter expression
1767
+ const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
1768
+ if (nested) {
1769
+ // find if there are matches in the nested expression
1770
+ // add them to the result set if there is at least one match
1771
+ this._walk(val, m => {
1772
+ const npath = [nested[2]];
1773
+ const nvalue = nested[1] ? val[m][nested[1]] : val[m];
1774
+ const filterResults = this._trace(npath, nvalue, path, parent, parentPropName, callback, true);
1775
+ if (filterResults.length > 0) {
1776
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));
1777
+ }
1778
+ });
1779
+ } else {
1780
+ this._walk(val, m => {
1781
+ if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
1782
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));
1783
+ }
1784
+ });
1785
+ }
1786
+ } else if (loc[0] === '(') {
1787
+ // [(expr)] (dynamic property/index)
1788
+ if (this.currEval === false) {
1789
+ throw new Error('Eval [(expr)] prevented in JSONPath expression.');
1790
+ }
1791
+ // As this will resolve to a property name (but we don't know it
1792
+ // yet), property and parent information is relative to the
1793
+ // parent of the property to which this expression will resolve
1794
+ addRet(this._trace(unshift(this._eval(loc, val, path.at(-1), path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback, hasArrExpr));
1795
+ } else if (loc[0] === '@') {
1796
+ // value type: @boolean(), etc.
1797
+ let addType = false;
1798
+ const valueType = loc.slice(1, -2);
1799
+ switch (valueType) {
1800
+ case 'scalar':
1801
+ if (!val || !['object', 'function'].includes(typeof val)) {
1802
+ addType = true;
1803
+ }
1804
+ break;
1805
+ case 'boolean':
1806
+ case 'string':
1807
+ case 'undefined':
1808
+ case 'function':
1809
+ if (typeof val === valueType) {
1810
+ addType = true;
1811
+ }
1812
+ break;
1813
+ case 'integer':
1814
+ if (Number.isFinite(val) && !(val % 1)) {
1815
+ addType = true;
1816
+ }
1817
+ break;
1818
+ case 'number':
1819
+ if (Number.isFinite(val)) {
1820
+ addType = true;
1821
+ }
1822
+ break;
1823
+ case 'nonFinite':
1824
+ if (typeof val === 'number' && !Number.isFinite(val)) {
1825
+ addType = true;
1826
+ }
1827
+ break;
1828
+ case 'object':
1829
+ if (val && typeof val === valueType) {
1830
+ addType = true;
1831
+ }
1832
+ break;
1833
+ case 'array':
1834
+ if (Array.isArray(val)) {
1835
+ addType = true;
1836
+ }
1837
+ break;
1838
+ case 'other':
1839
+ addType = this.currOtherTypeCallback(val, path, parent, parentPropName);
1840
+ break;
1841
+ case 'null':
1842
+ if (val === null) {
1843
+ addType = true;
1844
+ }
1845
+ break;
1846
+ /* c8 ignore next 2 */
1847
+ default:
1848
+ throw new TypeError('Unknown value type ' + valueType);
1849
+ }
1850
+ if (addType) {
1851
+ retObj = {
1852
+ path,
1853
+ value: val,
1854
+ parent,
1855
+ parentProperty: parentPropName
1856
+ };
1857
+ this._handleCallback(retObj, callback, 'value');
1858
+ return retObj;
1859
+ }
1860
+ // `-escaped property
1861
+ } else if (loc[0] === '`' && val && Object.hasOwn(val, loc.slice(1))) {
1862
+ const locProp = loc.slice(1);
1863
+ addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));
1864
+ } else if (loc.includes(',')) {
1865
+ // [name1,name2,...]
1866
+ const parts = loc.split(',');
1867
+ for (const part of parts) {
1868
+ addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true));
1869
+ }
1870
+ // simple case--directly follow property
1871
+ } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
1872
+ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true));
1873
+ }
1874
+
1875
+ // We check the resulting values for parent selections. For parent
1876
+ // selections we discard the value object and continue the trace with the
1877
+ // current val object
1878
+ if (this._hasParentSelector) {
1879
+ for (let t = 0; t < ret.length; t++) {
1880
+ const rett = ret[t];
1881
+ if (rett && rett.isParentSelector) {
1882
+ const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
1883
+ if (Array.isArray(tmp)) {
1884
+ ret[t] = tmp[0];
1885
+ const tl = tmp.length;
1886
+ for (let tt = 1; tt < tl; tt++) {
1887
+ // eslint-disable-next-line @stylistic/max-len -- Long
1888
+ // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
1889
+ t++;
1890
+ ret.splice(t, 0, tmp[tt]);
1891
+ }
1892
+ } else {
1893
+ ret[t] = tmp;
1894
+ }
1895
+ }
1896
+ }
1897
+ }
1898
+ return ret;
1899
+ };
1900
+ JSONPath.prototype._walk = function (val, f) {
1901
+ if (Array.isArray(val)) {
1902
+ const n = val.length;
1903
+ for (let i = 0; i < n; i++) {
1904
+ f(i);
1905
+ }
1906
+ } else if (val && typeof val === 'object') {
1907
+ Object.keys(val).forEach(m => {
1908
+ f(m);
1909
+ });
1910
+ }
1911
+ };
1912
+ JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) {
1913
+ if (!Array.isArray(val)) {
1914
+ return undefined;
1915
+ }
1916
+ const len = val.length,
1917
+ parts = loc.split(':'),
1918
+ step = parts[2] && Number.parseInt(parts[2]) || 1;
1919
+ let start = parts[0] && Number.parseInt(parts[0]) || 0,
1920
+ end = parts[1] && Number.parseInt(parts[1]) || len;
1921
+ start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
1922
+ end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
1923
+ const ret = [];
1924
+ for (let i = start; i < end; i += step) {
1925
+ const tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true);
1926
+ // Should only be possible to be an array here since first part of
1927
+ // ``unshift(i, expr)` passed in above would not be empty, nor `~`,
1928
+ // nor begin with `@` (as could return objects)
1929
+ // This was causing excessive stack size in Node (with or
1930
+ // without Babel) against our performance test: `ret.push(...tmp);`
1931
+ tmp.forEach(t => {
1932
+ ret.push(t);
1933
+ });
1934
+ }
1935
+ return ret;
1936
+ };
1937
+ JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) {
1938
+ this.currSandbox._$_parentProperty = parentPropName;
1939
+ this.currSandbox._$_parent = parent;
1940
+ this.currSandbox._$_property = _vname;
1941
+ this.currSandbox._$_root = this.json;
1942
+ this.currSandbox._$_v = _v;
1943
+ const containsPath = code.includes('@path');
1944
+ if (containsPath) {
1945
+ this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname]));
1946
+ }
1947
+ const scriptCacheKey = this.currEval + 'Script:' + code;
1948
+ if (!JSONPath.cache[scriptCacheKey]) {
1949
+ let script = code.replaceAll('@parentProperty', '_$_parentProperty').replaceAll('@parent', '_$_parent').replaceAll('@property', '_$_property').replaceAll('@root', '_$_root').replaceAll(/@([.\s)[])/gu, '_$_v$1');
1950
+ if (containsPath) {
1951
+ script = script.replaceAll('@path', '_$_path');
1952
+ }
1953
+ if (this.currEval === 'safe' || this.currEval === true || this.currEval === undefined) {
1954
+ JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
1955
+ } else if (this.currEval === 'native') {
1956
+ JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
1957
+ } else if (typeof this.currEval === 'function' && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, 'runInNewContext')) {
1958
+ const CurrEval = this.currEval;
1959
+ JSONPath.cache[scriptCacheKey] = new CurrEval(script);
1960
+ } else if (typeof this.currEval === 'function') {
1961
+ JSONPath.cache[scriptCacheKey] = {
1962
+ runInNewContext: context => this.currEval(script, context)
1963
+ };
1964
+ } else {
1965
+ throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
1966
+ }
1967
+ }
1968
+ try {
1969
+ return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
1970
+ } catch (e) {
1971
+ if (this.ignoreEvalErrors) {
1972
+ return false;
1973
+ }
1974
+ throw new Error('jsonPath: ' + e.message + ': ' + code);
1975
+ }
1976
+ };
1977
+
1978
+ // PUBLIC CLASS PROPERTIES AND METHODS
1979
+
1980
+ // Could store the cache object itself
1981
+ JSONPath.cache = {};
1982
+
1983
+ /**
1984
+ * @param {string[]} pathArr Array to convert
1985
+ * @returns {string} The path string
1986
+ */
1987
+ JSONPath.toPathString = function (pathArr) {
1988
+ const x = pathArr,
1989
+ n = x.length;
1990
+ let p = '$';
1991
+ for (let i = 1; i < n; i++) {
1992
+ if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
1993
+ p += /^[0-9*]+$/u.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']";
1994
+ }
1995
+ }
1996
+ return p;
1997
+ };
1998
+
1999
+ /**
2000
+ * @param {string} pointer JSON Path
2001
+ * @returns {string} JSON Pointer
2002
+ */
2003
+ JSONPath.toPointer = function (pointer) {
2004
+ const x = pointer,
2005
+ n = x.length;
2006
+ let p = '';
2007
+ for (let i = 1; i < n; i++) {
2008
+ if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
2009
+ p += '/' + x[i].toString().replaceAll('~', '~0').replaceAll('/', '~1');
2010
+ }
2011
+ }
2012
+ return p;
2013
+ };
2014
+
2015
+ /**
2016
+ * @param {string} expr Expression to convert
2017
+ * @returns {string[]}
2018
+ */
2019
+ JSONPath.toPathArray = function (expr) {
2020
+ const {
2021
+ cache
2022
+ } = JSONPath;
2023
+ if (cache[expr]) {
2024
+ return cache[expr].concat();
2025
+ }
2026
+ const subx = [];
2027
+ const normalized = expr
2028
+ // Properties
2029
+ .replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ';$&;')
2030
+ // Parenthetical evaluations (filtering and otherwise), directly
2031
+ // within brackets or single quotes
2032
+ .replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function ($0, $1) {
2033
+ return '[#' + (subx.push($1) - 1) + ']';
2034
+ })
2035
+ // Escape periods and tildes within properties
2036
+ .replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function ($0, prop) {
2037
+ return "['" + prop.replaceAll('.', '%@%').replaceAll('~', '%%@@%%') + "']";
2038
+ })
2039
+ // Properties operator
2040
+ .replaceAll('~', ';~;')
2041
+ // Split by property boundaries
2042
+ .replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ';')
2043
+ // Reinsert periods within properties
2044
+ .replaceAll('%@%', '.')
2045
+ // Reinsert tildes within properties
2046
+ .replaceAll('%%@@%%', '~')
2047
+ // Parent
2048
+ .replaceAll(/(?:;)?(\^+)(?:;)?/gu, function ($0, ups) {
2049
+ return ';' + ups.split('').join(';') + ';';
2050
+ })
2051
+ // Descendents
2052
+ .replaceAll(/;;;|;;/gu, ';..;')
2053
+ // Remove trailing
2054
+ .replaceAll(/;$|'?\]|'$/gu, '');
2055
+ const exprList = normalized.split(';').map(function (exp) {
2056
+ const match = exp.match(/#(\d+)/u);
2057
+ return !match || !match[1] ? exp : subx[match[1]];
2058
+ });
2059
+ cache[expr] = exprList;
2060
+ return cache[expr].concat();
2061
+ };
2062
+ JSONPath.prototype.safeVm = {
2063
+ Script: SafeScript
2064
+ };
2065
+
2066
+ JSONPath.prototype.vm = vm;
2067
+
2068
+ export { JSONPath };