@nocobase/plugin-workflow-json-query 1.9.0-beta.17

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