ecma-evaluator 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,14 +26,158 @@ var __webpack_require__ = {};
26
26
  var __webpack_exports__ = {};
27
27
  __webpack_require__.r(__webpack_exports__);
28
28
  __webpack_require__.d(__webpack_exports__, {
29
- evaluatorExpression: function() {
30
- return evaluatorExpression;
29
+ evalTemplate: function() {
30
+ return evalTemplate;
31
31
  },
32
- evaluatorTemplate: function() {
33
- return evaluatorTemplate;
32
+ evalExpression: function() {
33
+ return evalExpression;
34
+ },
35
+ Evaluator: function() {
36
+ return Evaluator_Evaluator;
34
37
  }
35
38
  });
36
39
  var external_acorn_namespaceObject = require("acorn");
40
+ var external_globals_namespaceObject = require("globals");
41
+ var mutableMethods = [
42
+ "Array.prototype.push",
43
+ "Array.prototype.pop",
44
+ "Array.prototype.shift",
45
+ "Array.prototype.unshift",
46
+ "Array.prototype.splice",
47
+ "Array.prototype.reverse",
48
+ "Array.prototype.sort",
49
+ "Array.prototype.fill",
50
+ "Array.prototype.copyWithin",
51
+ "Object.defineProperty",
52
+ "Object.defineProperties",
53
+ "Object.preventExtensions",
54
+ "Object.seal",
55
+ "Object.freeze",
56
+ "Object.setPrototypeOf",
57
+ "Object.assign",
58
+ "Reflect.set",
59
+ "Reflect.defineProperty",
60
+ "Reflect.deleteProperty",
61
+ "Reflect.setPrototypeOf",
62
+ "Reflect.preventExtensions",
63
+ "Set.prototype.add",
64
+ "Set.prototype.delete",
65
+ "Set.prototype.clear",
66
+ "WeakSet.prototype.add",
67
+ "WeakSet.prototype.delete",
68
+ "Map.prototype.set",
69
+ "Map.prototype.delete",
70
+ "Map.prototype.clear",
71
+ "WeakMap.prototype.set",
72
+ "WeakMap.prototype.delete",
73
+ "Date.prototype.setTime",
74
+ "Date.prototype.setMilliseconds",
75
+ "Date.prototype.setUTCSeconds",
76
+ "Date.prototype.setSeconds",
77
+ "Date.prototype.setMinutes",
78
+ "Date.prototype.setHours",
79
+ "Date.prototype.setDate",
80
+ "Date.prototype.setMonth",
81
+ "Date.prototype.setFullYear",
82
+ "Date.prototype.setYear",
83
+ "Date.prototype.setUTCMilliseconds",
84
+ "Date.prototype.setUTCMinutes",
85
+ "Date.prototype.setUTCHours",
86
+ "Date.prototype.setUTCDate",
87
+ "Date.prototype.setUTCMonth",
88
+ "Date.prototype.setUTCFullYear",
89
+ "RegExp.prototype.compile",
90
+ "Int8Array.prototype.set",
91
+ "Uint8Array.prototype.set",
92
+ "Uint8ClampedArray.prototype.set",
93
+ "Int16Array.prototype.set",
94
+ "Uint16Array.prototype.set",
95
+ "Int32Array.prototype.set",
96
+ "Uint32Array.prototype.set",
97
+ "Float32Array.prototype.set",
98
+ "Float64Array.prototype.set",
99
+ "BigInt64Array.prototype.set",
100
+ "BigUint64Array.prototype.set",
101
+ "Int8Array.prototype.fill",
102
+ "Uint8Array.prototype.fill",
103
+ "Uint8ClampedArray.prototype.fill",
104
+ "Int16Array.prototype.fill",
105
+ "Uint16Array.prototype.fill",
106
+ "Int32Array.prototype.fill",
107
+ "Uint32Array.prototype.fill",
108
+ "Float32Array.prototype.fill",
109
+ "Float64Array.prototype.fill",
110
+ "BigInt64Array.prototype.fill",
111
+ "BigUint64Array.prototype.fill",
112
+ "Int8Array.prototype.reverse",
113
+ "Uint8Array.prototype.reverse",
114
+ "Uint8ClampedArray.prototype.reverse",
115
+ "Int16Array.prototype.reverse",
116
+ "Uint16Array.prototype.reverse",
117
+ "Int32Array.prototype.reverse",
118
+ "Uint32Array.prototype.reverse",
119
+ "Float32Array.prototype.reverse",
120
+ "Float64Array.prototype.reverse",
121
+ "BigInt64Array.prototype.reverse",
122
+ "BigUint64Array.prototype.reverse",
123
+ "Int8Array.prototype.sort",
124
+ "Uint8Array.prototype.sort",
125
+ "Uint8ClampedArray.prototype.sort",
126
+ "Int16Array.prototype.sort",
127
+ "Uint16Array.prototype.sort",
128
+ "Int32Array.prototype.sort",
129
+ "Uint32Array.prototype.sort",
130
+ "Float32Array.prototype.sort",
131
+ "Float64Array.prototype.sort",
132
+ "BigInt64Array.prototype.sort",
133
+ "BigUint64Array.prototype.sort",
134
+ "Int8Array.prototype.copyWithin",
135
+ "Uint8Array.prototype.copyWithin",
136
+ "Uint8ClampedArray.prototype.copyWithin",
137
+ "Int16Array.prototype.copyWithin",
138
+ "Uint16Array.prototype.copyWithin",
139
+ "Int32Array.prototype.copyWithin",
140
+ "Uint32Array.prototype.copyWithin",
141
+ "Float32Array.prototype.copyWithin",
142
+ "Float64Array.prototype.copyWithin",
143
+ "BigInt64Array.prototype.copyWithin",
144
+ "BigUint64Array.prototype.copyWithin",
145
+ "ArrayBuffer.prototype.transfer",
146
+ "ArrayBuffer.prototype.transferToFixedLength",
147
+ "SharedArrayBuffer.prototype.grow",
148
+ "DataView.prototype.setInt8",
149
+ "DataView.prototype.setUint8",
150
+ "DataView.prototype.setInt16",
151
+ "DataView.prototype.setUint16",
152
+ "DataView.prototype.setInt32",
153
+ "DataView.prototype.setUint32",
154
+ "DataView.prototype.setFloat32",
155
+ "DataView.prototype.setFloat64",
156
+ "DataView.prototype.setBigInt64",
157
+ "DataView.prototype.setBigUint64",
158
+ "Promise.prototype.catch",
159
+ "Promise.prototype.finally",
160
+ "Generator.prototype.next",
161
+ "Generator.prototype.return",
162
+ "Generator.prototype.throw",
163
+ "AsyncGenerator.prototype.next",
164
+ "AsyncGenerator.prototype.return",
165
+ "AsyncGenerator.prototype.throw",
166
+ "Iterator.prototype.next",
167
+ "WeakRef.prototype.deref",
168
+ "FinalizationRegistry.prototype.register",
169
+ "FinalizationRegistry.prototype.unregister",
170
+ "URLSearchParams.prototype.append",
171
+ "URLSearchParams.prototype.delete",
172
+ "URLSearchParams.prototype.set",
173
+ "URLSearchParams.prototype.sort",
174
+ "FormData.prototype.append",
175
+ "FormData.prototype.delete",
176
+ "FormData.prototype.set",
177
+ "Headers.prototype.append",
178
+ "Headers.prototype.delete",
179
+ "Headers.prototype.set"
180
+ ];
37
181
  function _array_like_to_array(arr, len) {
38
182
  if (null == len || len > arr.length) len = arr.length;
39
183
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
@@ -75,62 +219,19 @@ function _create_class(Constructor, protoProps, staticProps) {
75
219
  if (staticProps) _defineProperties(Constructor, staticProps);
76
220
  return Constructor;
77
221
  }
78
- function _define_property(obj, key, value) {
79
- if (key in obj) Object.defineProperty(obj, key, {
80
- value: value,
81
- enumerable: true,
82
- configurable: true,
83
- writable: true
84
- });
85
- else obj[key] = value;
86
- return obj;
222
+ function _instanceof(left, right) {
223
+ if (null != right && "undefined" != typeof Symbol && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
224
+ return left instanceof right;
87
225
  }
88
226
  function _iterable_to_array(iter) {
89
227
  if ("undefined" != typeof Symbol && null != iter[Symbol.iterator] || null != iter["@@iterator"]) return Array.from(iter);
90
228
  }
91
- function _iterable_to_array_limit(arr, i) {
92
- var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
93
- if (null == _i) return;
94
- var _arr = [];
95
- var _n = true;
96
- var _d = false;
97
- var _s, _e;
98
- try {
99
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
100
- _arr.push(_s.value);
101
- if (i && _arr.length === i) break;
102
- }
103
- } catch (err) {
104
- _d = true;
105
- _e = err;
106
- } finally{
107
- try {
108
- if (!_n && null != _i["return"]) _i["return"]();
109
- } finally{
110
- if (_d) throw _e;
111
- }
112
- }
113
- return _arr;
114
- }
115
229
  function _non_iterable_rest() {
116
230
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
117
231
  }
118
232
  function _non_iterable_spread() {
119
233
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
120
234
  }
121
- function _object_spread(target) {
122
- for(var i = 1; i < arguments.length; i++){
123
- var source = null != arguments[i] ? arguments[i] : {};
124
- var ownKeys = Object.keys(source);
125
- if ("function" == typeof Object.getOwnPropertySymbols) ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
126
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
127
- }));
128
- ownKeys.forEach(function(key) {
129
- _define_property(target, key, source[key]);
130
- });
131
- }
132
- return target;
133
- }
134
235
  function _set_prototype_of(o, p) {
135
236
  _set_prototype_of = Object.setPrototypeOf || function(o, p) {
136
237
  o.__proto__ = p;
@@ -138,8 +239,8 @@ function _set_prototype_of(o, p) {
138
239
  };
139
240
  return _set_prototype_of(o, p);
140
241
  }
141
- function _sliced_to_array(arr, i) {
142
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
242
+ function _to_array(arr) {
243
+ return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
143
244
  }
144
245
  function _to_consumable_array(arr) {
145
246
  return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
@@ -163,132 +264,110 @@ function _is_native_reflect_construct() {
163
264
  return !!result;
164
265
  })();
165
266
  }
166
- var typeArrayConstructors = [
167
- Int8Array,
168
- Uint8Array,
169
- Uint8ClampedArray,
170
- Int16Array,
171
- Uint16Array,
172
- Int32Array,
173
- Uint32Array,
174
- Float32Array,
175
- Float64Array,
176
- globalThis.BigInt64Array,
177
- globalThis.BigUint64Array
178
- ].filter(Boolean);
179
- var mutableMethods = new Set([
180
- Array.prototype.push,
181
- Array.prototype.pop,
182
- Array.prototype.shift,
183
- Array.prototype.unshift,
184
- Array.prototype.splice,
185
- Array.prototype.reverse,
186
- Array.prototype.sort,
187
- Array.prototype.fill,
188
- Array.prototype.copyWithin,
189
- ArrayBuffer.prototype.slice,
190
- DataView.prototype.setInt8,
191
- DataView.prototype.setUint8,
192
- DataView.prototype.setInt16,
193
- DataView.prototype.setUint16,
194
- DataView.prototype.setInt32,
195
- DataView.prototype.setUint32,
196
- DataView.prototype.setFloat32,
197
- DataView.prototype.setFloat64
198
- ].concat(_to_consumable_array(typeArrayConstructors.flatMap(function(TypedArray) {
199
- return [
200
- TypedArray.prototype.set,
201
- TypedArray.prototype.fill,
202
- TypedArray.prototype.copyWithin,
203
- TypedArray.prototype.reverse,
204
- TypedArray.prototype.sort
205
- ];
206
- })), [
207
- Object.freeze,
208
- Object.defineProperty,
209
- Object.defineProperties,
210
- Object.preventExtensions,
211
- Object.setPrototypeOf,
212
- Object.assign,
213
- Set.prototype.add,
214
- Set.prototype["delete"],
215
- Set.prototype.clear,
216
- WeakSet.prototype.add,
217
- WeakSet.prototype["delete"],
218
- Map.prototype.set,
219
- Map.prototype["delete"],
220
- Map.prototype.clear,
221
- WeakMap.prototype.set,
222
- WeakMap.prototype["delete"],
223
- Date.prototype.setMilliseconds,
224
- Date.prototype.setMinutes,
225
- Date.prototype.setHours,
226
- Date.prototype.setDate,
227
- Date.prototype.setFullYear,
228
- Date.prototype.setUTCMinutes,
229
- Date.prototype.setUTCHours,
230
- Date.prototype.setUTCDate,
231
- Date.prototype.setUTCFullYear,
232
- Date.prototype.setTime
233
- ]));
267
+ var ERROR_MESSAGES = {
268
+ DELETE_NOT_SUPPORTED: "Delete operator is not allow",
269
+ MUTABLE_METHOD: "Mutable method is not allowed",
270
+ NEW_FUNCTION_NOT_ALLOWED: "Cannot use new with Function constructor",
271
+ NOT_A_FUNCTION: "is not a function",
272
+ PROPERTY_READ_ERROR: "Cannot read property",
273
+ VARIABLE_NOT_DEFINED: "is not defined",
274
+ FUNCTION_CONSTRUCTOR_NOT_ALLOWED: "Function constructor is not allowed",
275
+ THIS_NOT_ALLOWED: "'this' keyword is not allowed",
276
+ NOT_A_VALID_SYNTAX: "is not a valid syntax"
277
+ };
278
+ function createGlobalScope() {
279
+ var scope = Object.create(null);
280
+ var builtin = external_globals_namespaceObject.builtin;
281
+ Object.keys(builtin).forEach(function(key) {
282
+ if (key in globalThis && "eval" !== key && "globalThis" !== key) {
283
+ var isWritable = builtin[key];
284
+ Object.defineProperty(scope, key, {
285
+ value: globalThis[key],
286
+ writable: isWritable,
287
+ enumerable: false,
288
+ configurable: false
289
+ });
290
+ }
291
+ });
292
+ Object.defineProperty(scope, "globalThis", {
293
+ value: scope,
294
+ writable: false,
295
+ enumerable: false,
296
+ configurable: false
297
+ });
298
+ return scope;
299
+ }
300
+ var getMutableMethods = function() {
301
+ var MUTABLE_METHODS = null;
302
+ return function() {
303
+ if (MUTABLE_METHODS) return MUTABLE_METHODS;
304
+ var set = new Set();
305
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
306
+ try {
307
+ for(var _iterator = mutableMethods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
308
+ var path = _step.value;
309
+ var _path_split = _to_array(path.split(".")), object = _path_split[0], properties = _path_split.slice(1);
310
+ var current = globalThis[object];
311
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = void 0;
312
+ try {
313
+ for(var _iterator1 = properties[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
314
+ var prop = _step1.value;
315
+ if (current && Object.hasOwn(current, prop)) current = current[prop];
316
+ else {
317
+ current = null;
318
+ break;
319
+ }
320
+ }
321
+ } catch (err) {
322
+ _didIteratorError1 = true;
323
+ _iteratorError1 = err;
324
+ } finally{
325
+ try {
326
+ if (!_iteratorNormalCompletion1 && null != _iterator1.return) _iterator1.return();
327
+ } finally{
328
+ if (_didIteratorError1) throw _iteratorError1;
329
+ }
330
+ }
331
+ if ("function" == typeof current) set.add(current);
332
+ }
333
+ } catch (err) {
334
+ _didIteratorError = true;
335
+ _iteratorError = err;
336
+ } finally{
337
+ try {
338
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
339
+ } finally{
340
+ if (_didIteratorError) throw _iteratorError;
341
+ }
342
+ }
343
+ MUTABLE_METHODS = set;
344
+ return MUTABLE_METHODS;
345
+ };
346
+ }();
234
347
  var Evaluator_Evaluator = /*#__PURE__*/ function() {
235
348
  "use strict";
236
349
  function Evaluator() {
237
350
  var variables = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
238
351
  _class_call_check(this, Evaluator);
239
- var globalScope = Object.assign(Object.create(null), _object_spread({
240
- Infinity: 1 / 0,
241
- null: null,
242
- undefined: void 0,
243
- NaN: Number.NaN,
244
- isNaN: Number.isNaN,
245
- isFinite: Number.isFinite,
246
- parseFloat: Number.parseFloat,
247
- parseInt: Number.parseInt,
248
- encodeURI: globalThis.encodeURI,
249
- encodeURIComponent: globalThis.encodeURIComponent,
250
- decodeURI: globalThis.decodeURI,
251
- decodeURIComponent: globalThis.decodeURIComponent,
252
- Number: Number,
253
- String: String,
254
- Boolean: Boolean,
255
- BigInt: globalThis.BigInt,
256
- Symbol: globalThis.Symbol,
257
- Object: Object,
258
- Array: Array,
259
- Set: Set,
260
- WeakSet: WeakSet,
261
- Map: Map,
262
- WeakMap: WeakMap,
263
- Math: Math,
264
- JSON: JSON,
265
- Date: Date,
266
- RegExp: RegExp,
267
- Error: Error,
268
- EvalError: EvalError,
269
- RangeError: RangeError,
270
- ReferenceError: ReferenceError,
271
- SyntaxError: SyntaxError,
272
- TypeError: TypeError,
273
- URIError: URIError,
274
- Promise: Promise
275
- }, typeArrayConstructors.reduce(function(acc, obj) {
276
- acc[obj.name] = obj;
277
- return acc;
278
- }, {})));
279
352
  this.scopes = [
280
353
  variables,
281
- globalScope
354
+ createGlobalScope()
282
355
  ];
356
+ this.source = void 0;
283
357
  }
284
358
  _create_class(Evaluator, [
285
359
  {
286
360
  key: "evaluate",
287
361
  value: function(expression) {
362
+ this.source = expression;
288
363
  var ast = external_acorn_namespaceObject.parse(expression, {
289
364
  ecmaVersion: "latest"
290
365
  });
291
- return this.execute(ast.body);
366
+ try {
367
+ return this.execute(ast.body);
368
+ } finally{
369
+ this.source = void 0;
370
+ }
292
371
  }
293
372
  },
294
373
  {
@@ -306,7 +385,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
306
385
  _iteratorError = err;
307
386
  } finally{
308
387
  try {
309
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
388
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
310
389
  } finally{
311
390
  if (_didIteratorError) throw _iteratorError;
312
391
  }
@@ -337,6 +416,10 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
337
416
  return this.handleObjectExpression(node);
338
417
  case "ArrayExpression":
339
418
  return this.handleArrayExpression(node);
419
+ case "SpreadElement":
420
+ return this.handleSpreadElement(node);
421
+ case "ObjectExpression":
422
+ return this.handleObjectExpression(node);
340
423
  case "ArrowFunctionExpression":
341
424
  return this.handleArrowFunctionExpression(node);
342
425
  case "CallExpression":
@@ -345,68 +428,76 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
345
428
  return this.visit(node.test) ? this.visit(node.consequent) : this.visit(node.alternate);
346
429
  case "NewExpression":
347
430
  if ("Identifier" !== node.callee.type) throw new Error("Unsupported callee type '".concat(node.callee.type, "' in new expression"));
348
- if ("Function" === node.callee.name) throw new Error("Cannot use new with Function constructor");
431
+ if ("Function" === node.callee.name) throw new Error(ERROR_MESSAGES.NEW_FUNCTION_NOT_ALLOWED);
349
432
  var Constructor = this.visit(node.callee);
350
- var args = node["arguments"].map(function(arg) {
433
+ var args = node.arguments.length ? node.arguments.map(function(arg) {
351
434
  return _this.visit(arg);
352
- });
435
+ }) : [];
353
436
  return _construct(Constructor, _to_consumable_array(args));
354
437
  case "ChainExpression":
355
438
  return this.visit(node.expression);
356
439
  case "TemplateLiteral":
357
440
  return this.handleTemplateLiteral(node);
441
+ case "ThisExpression":
442
+ throw new Error(ERROR_MESSAGES.THIS_NOT_ALLOWED);
358
443
  default:
359
- throw new Error("Unsupported node type: ".concat(node.type));
444
+ var content = this.source.slice(node.start, node.end);
445
+ if (content.length > 20) content = content.slice(0, 17) + "...";
446
+ throw new Error("'".concat(content, "'") + " " + ERROR_MESSAGES.NOT_A_VALID_SYNTAX);
360
447
  }
361
448
  }
362
449
  },
363
450
  {
364
451
  key: "handleBinaryExpression",
365
452
  value: function(node) {
366
- switch(node.operator){
453
+ var op = node.operator;
454
+ var left = this.visit(node.left);
455
+ var right = this.visit(node.right);
456
+ switch(op){
367
457
  case "+":
368
- return this.visit(node.left) + this.visit(node.right);
458
+ return left + right;
369
459
  case "-":
370
- return this.visit(node.left) - this.visit(node.right);
460
+ return left - right;
371
461
  case "*":
372
- return this.visit(node.left) * this.visit(node.right);
462
+ return left * right;
373
463
  case "**":
374
- return Math.pow(this.visit(node.left), this.visit(node.right));
375
- case "/":
376
- var left = this.visit(node.left);
377
- var right = this.visit(node.right);
378
- if (0 === right) throw new Error("Division by zero");
379
- return left / right;
464
+ return Math.pow(left, right);
380
465
  case "==":
381
- return this.visit(node.left) == this.visit(node.right);
466
+ return left == right;
382
467
  case "===":
383
- return this.visit(node.left) === this.visit(node.right);
468
+ return left === right;
384
469
  case "!=":
385
- return this.visit(node.left) != this.visit(node.right);
470
+ return left != right;
386
471
  case "!==":
387
- return this.visit(node.left) !== this.visit(node.right);
472
+ return left !== right;
388
473
  case ">":
389
- return this.visit(node.left) > this.visit(node.right);
474
+ return left > right;
390
475
  case ">=":
391
- return this.visit(node.left) >= this.visit(node.right);
476
+ return left >= right;
392
477
  case "<":
393
- return this.visit(node.left) < this.visit(node.right);
478
+ return left < right;
394
479
  case "<=":
395
- return this.visit(node.left) <= this.visit(node.right);
480
+ return left <= right;
396
481
  case "%":
397
- return this.visit(node.left) % this.visit(node.right);
398
- case "&":
399
- return this.visit(node.left) & this.visit(node.right);
482
+ return left % right;
483
+ case "/":
484
+ return left / right;
400
485
  case "|":
401
- return this.visit(node.left) | this.visit(node.right);
486
+ return left | right;
487
+ case "&":
488
+ return left & right;
402
489
  case "^":
403
- return this.visit(node.left) ^ this.visit(node.right);
490
+ return left ^ right;
404
491
  case "<<":
405
- return this.visit(node.left) << this.visit(node.right);
492
+ return left << right;
406
493
  case ">>":
407
- return this.visit(node.left) >> this.visit(node.right);
494
+ return left >> right;
408
495
  case ">>>":
409
- return this.visit(node.left) >>> this.visit(node.right);
496
+ return left >>> right;
497
+ case "in":
498
+ return left in right;
499
+ case "instanceof":
500
+ return _instanceof(left, right);
410
501
  default:
411
502
  throw new Error("Unsupported operator: ".concat(node.operator));
412
503
  }
@@ -417,12 +508,14 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
417
508
  value: function(node) {
418
509
  switch(node.operator){
419
510
  case "&&":
420
- return this.visit(node.left) && this.visit(node.right);
511
+ var left = this.visit(node.left);
512
+ return left ? this.visit(node.right) : left;
421
513
  case "||":
422
- return this.visit(node.left) || this.visit(node.right);
514
+ var left1 = this.visit(node.left);
515
+ return left1 ? left1 : this.visit(node.right);
423
516
  case "??":
424
- var left = this.visit(node.left);
425
- return null != left ? left : this.visit(node.right);
517
+ var left2 = this.visit(node.left);
518
+ return null != left2 ? left2 : this.visit(node.right);
426
519
  default:
427
520
  throw new Error("Unsupported logical operator: ".concat(node.operator));
428
521
  }
@@ -445,7 +538,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
445
538
  case "void":
446
539
  return void this.visit(node.argument);
447
540
  case "delete":
448
- throw new Error("Delete operator is mutable and not supported");
541
+ throw new Error(ERROR_MESSAGES.DELETE_NOT_SUPPORTED);
449
542
  default:
450
543
  throw new Error("Unsupported unary operator: ".concat(node.operator));
451
544
  }
@@ -466,28 +559,25 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
466
559
  _iteratorError = err;
467
560
  } finally{
468
561
  try {
469
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
562
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
470
563
  } finally{
471
564
  if (_didIteratorError) throw _iteratorError;
472
565
  }
473
566
  }
474
- throw new ReferenceError("".concat(name, " is not defined"));
567
+ throw new ReferenceError("".concat(name, " ").concat(ERROR_MESSAGES.VARIABLE_NOT_DEFINED));
475
568
  }
476
569
  },
477
570
  {
478
571
  key: "handleMemberExpression",
479
572
  value: function(node) {
480
573
  var object = this.visit(node.object);
481
- var property = "Identifier" !== node.property.type || node.computed ? this.visit(node.property) : node.property.name;
574
+ var isStaticProperty = "Identifier" === node.property.type && !node.computed;
575
+ var property = isStaticProperty ? node.property.name : this.visit(node.property);
482
576
  if (null == object) {
483
577
  if (node.optional) return;
484
- throw new TypeError("Cannot read property '".concat(property, "' of ").concat(object));
578
+ throw new TypeError("".concat(ERROR_MESSAGES.PROPERTY_READ_ERROR, " '").concat(property, "' of ").concat(object));
485
579
  }
486
- if (Object.hasOwn(object, property)) return object[property];
487
- var prototypeValue = object[property];
488
- if (mutableMethods.has(prototypeValue)) throw new Error("Cannot call mutable prototype method: ".concat(property));
489
- if ("function" == typeof prototypeValue) return prototypeValue.bind(object);
490
- return prototypeValue;
580
+ return object[property];
491
581
  }
492
582
  },
493
583
  {
@@ -498,6 +588,10 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
498
588
  try {
499
589
  for(var _iterator = node.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
500
590
  var prop = _step.value;
591
+ if ("SpreadElement" === prop.type) {
592
+ Object.assign(obj, this.visit(prop.argument));
593
+ continue;
594
+ }
501
595
  var key = prop.key.name || prop.key.value;
502
596
  var value = this.visit(prop.value);
503
597
  obj[key] = value;
@@ -507,7 +601,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
507
601
  _iteratorError = err;
508
602
  } finally{
509
603
  try {
510
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
604
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
511
605
  } finally{
512
606
  if (_didIteratorError) throw _iteratorError;
513
607
  }
@@ -518,10 +612,22 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
518
612
  {
519
613
  key: "handleArrayExpression",
520
614
  value: function(node) {
521
- var _this = this;
522
- return node.elements.map(function(element) {
523
- return _this.visit(element);
524
- });
615
+ var result = [];
616
+ for(var i = 0; i < node.elements.length; i++){
617
+ var element = node.elements.at(i);
618
+ var value = this.visit(element);
619
+ if ("SpreadElement" === element.type) {
620
+ var _result;
621
+ (_result = result).push.apply(_result, _to_consumable_array(value));
622
+ } else result.push(value);
623
+ }
624
+ return result;
625
+ }
626
+ },
627
+ {
628
+ key: "handleSpreadElement",
629
+ value: function(node) {
630
+ return this.visit(node.argument);
525
631
  }
526
632
  },
527
633
  {
@@ -531,22 +637,8 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
531
637
  return function() {
532
638
  for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
533
639
  var newScope = {};
534
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
535
- try {
536
- for(var _iterator = node.params.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
537
- var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], param = _step_value[1];
538
- newScope[param.name] = args[index];
539
- }
540
- } catch (err) {
541
- _didIteratorError = true;
542
- _iteratorError = err;
543
- } finally{
544
- try {
545
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
546
- } finally{
547
- if (_didIteratorError) throw _iteratorError;
548
- }
549
- }
640
+ var paramCount = node.params.length;
641
+ for(var i = 0; i < paramCount; i++)newScope[node.params[i].name] = args[i];
550
642
  _this.scopes.unshift(newScope);
551
643
  var result = _this.visit(node.body);
552
644
  _this.scopes.shift();
@@ -558,78 +650,276 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
558
650
  key: "handleCallExpression",
559
651
  value: function(node) {
560
652
  var _this = this;
561
- var calledString = this.getNodeString(node.callee);
653
+ if ("MemberExpression" === node.callee.type) {
654
+ var object = this.visit(node.callee.object);
655
+ if (getMutableMethods().has(object)) throw new Error(ERROR_MESSAGES.MUTABLE_METHOD);
656
+ }
657
+ var calledString = getNodeString(node.callee);
562
658
  var func = this.visit(node.callee);
563
659
  if ("function" != typeof func) {
564
660
  var isOptional = node.optional || node.callee.optional;
565
661
  if (null == func && isOptional) return;
566
- throw new TypeError("".concat(calledString, " is not a function"));
662
+ throw new TypeError("".concat(calledString, " ").concat(ERROR_MESSAGES.NOT_A_FUNCTION));
567
663
  }
568
- var args = node["arguments"].map(function(arg) {
569
- return _this.visit(arg);
570
- });
571
- return func.apply(void 0, _to_consumable_array(args));
664
+ if (func === Function) throw new Error(ERROR_MESSAGES.FUNCTION_CONSTRUCTOR_NOT_ALLOWED);
665
+ var args = function() {
666
+ if (0 === node.arguments.length) return [];
667
+ var result = [];
668
+ for(var i = 0; i < node.arguments.length; i++){
669
+ var element = node.arguments.at(i);
670
+ var value = _this.visit(element);
671
+ if ("SpreadElement" === element.type) {
672
+ var _result;
673
+ (_result = result).push.apply(_result, _to_consumable_array(value));
674
+ } else result.push(value);
675
+ }
676
+ return result;
677
+ }();
678
+ if (getMutableMethods().has(func)) throw new Error(ERROR_MESSAGES.MUTABLE_METHOD);
679
+ var target = "MemberExpression" === node.callee.type ? this.visit(node.callee.object) : null;
680
+ return func.apply(target, args);
572
681
  }
573
682
  },
574
683
  {
575
684
  key: "handleTemplateLiteral",
576
685
  value: function(node) {
577
- var _this = this;
578
- return node.quasis.concat(node.expressions).filter(Boolean).sort(function(a, b) {
579
- return a.start - b.start;
580
- }).map(function(node) {
581
- if ("TemplateElement" === node.type) return node.value.raw;
582
- return _this.visit(node);
583
- }).join("");
686
+ var result = "";
687
+ var expressionCount = node.expressions.length;
688
+ for(var i = 0; i < node.quasis.length; i++){
689
+ result += node.quasis[i].value.raw;
690
+ if (i < expressionCount) result += this.visit(node.expressions[i]);
691
+ }
692
+ return result;
584
693
  }
585
- },
694
+ }
695
+ ], [
586
696
  {
587
- key: "getNodeString",
588
- value: function(node) {
589
- switch(node.type){
590
- case "Identifier":
591
- return node.name;
592
- case "Literal":
593
- return node.raw;
594
- case "ArrayExpression":
595
- return "(array)";
596
- case "ObjectExpression":
597
- return "(object)";
598
- case "MemberExpression":
599
- var accessor = this.getNodeString(node.object);
600
- if (node.computed) accessor += "[".concat(this.getNodeString(node.property), "]");
601
- else accessor += ".".concat(this.getNodeString(node.property));
602
- return accessor;
603
- default:
604
- return null;
605
- }
697
+ key: "evaluate",
698
+ value: function(expression, context) {
699
+ var evaluator = new Evaluator(context);
700
+ return evaluator.evaluate(expression);
606
701
  }
607
702
  }
608
703
  ]);
609
704
  return Evaluator;
610
705
  }();
611
- var TEMPLATE_EXPRESSION_REGEX = /\$\{\{((?:[^{}]|{[^{}]*})+)\}\}/g;
612
- function evaluatorExpression(expression, context) {
613
- var evaluator = new Evaluator_Evaluator(context);
614
- return evaluator.evaluate(expression);
706
+ function getNodeString(node) {
707
+ switch(node.type){
708
+ case "Identifier":
709
+ return node.name;
710
+ case "Literal":
711
+ return node.raw;
712
+ case "ArrayExpression":
713
+ return "[".concat(node.elements.map(function(child) {
714
+ return getNodeString(child);
715
+ }).join(","), "]");
716
+ case "ObjectExpression":
717
+ if (0 === node.properties.length) return "{}";
718
+ return "{(intermediate value)}";
719
+ case "MemberExpression":
720
+ var objectStr = getNodeString(node.object);
721
+ var propertyStr = getNodeString(node.property);
722
+ if (node.computed) return "".concat(objectStr, "[").concat(propertyStr, "]");
723
+ return "".concat(objectStr, ".").concat(propertyStr);
724
+ default:
725
+ return null;
726
+ }
727
+ }
728
+ function TemplateParser_class_call_check(instance, Constructor) {
729
+ if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
615
730
  }
616
- function evaluatorTemplate(template, context) {
617
- var evaluator = new Evaluator_Evaluator(context);
618
- return template.replace(TEMPLATE_EXPRESSION_REGEX, function(match, expression) {
731
+ function TemplateParser_defineProperties(target, props) {
732
+ for(var i = 0; i < props.length; i++){
733
+ var descriptor = props[i];
734
+ descriptor.enumerable = descriptor.enumerable || false;
735
+ descriptor.configurable = true;
736
+ if ("value" in descriptor) descriptor.writable = true;
737
+ Object.defineProperty(target, descriptor.key, descriptor);
738
+ }
739
+ }
740
+ function TemplateParser_create_class(Constructor, protoProps, staticProps) {
741
+ if (protoProps) TemplateParser_defineProperties(Constructor.prototype, protoProps);
742
+ if (staticProps) TemplateParser_defineProperties(Constructor, staticProps);
743
+ return Constructor;
744
+ }
745
+ var TemplateParser_TemplateParser = /*#__PURE__*/ function() {
746
+ "use strict";
747
+ function TemplateParser() {
748
+ var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
749
+ TemplateParser_class_call_check(this, TemplateParser);
750
+ this.exprStart = options.expressionStart || "{{";
751
+ this.exprEnd = options.expressionEnd || "}}";
752
+ this.startLen = this.exprStart.length;
753
+ this.endLen = this.exprEnd.length;
754
+ this.preserveWhitespace = true === options.preserveWhitespace;
755
+ }
756
+ TemplateParser_create_class(TemplateParser, [
757
+ {
758
+ key: "parse",
759
+ value: function(template) {
760
+ if ("string" != typeof template) throw new TypeError("模板必须是字符串");
761
+ var tokens = [];
762
+ var length = template.length;
763
+ var state = "TEXT";
764
+ var buffer = "";
765
+ var exprStartPos = 0;
766
+ var pos = 0;
767
+ while(pos < length){
768
+ var char = template[pos];
769
+ var nextChar = template[pos + 1];
770
+ switch(state){
771
+ case "TEXT":
772
+ if (this._isMatch(pos, template, this.exprStart)) {
773
+ if (buffer.length > 0) {
774
+ tokens.push({
775
+ type: "text",
776
+ value: buffer,
777
+ start: pos - buffer.length,
778
+ end: pos
779
+ });
780
+ buffer = "";
781
+ }
782
+ state = "EXPR";
783
+ exprStartPos = pos;
784
+ pos += this.startLen;
785
+ continue;
786
+ }
787
+ buffer += char;
788
+ break;
789
+ case "EXPR":
790
+ if ("'" === char) state = "STRING_SQ";
791
+ else if ('"' === char) state = "STRING_DQ";
792
+ else if ("`" === char) state = "TEMPLATE";
793
+ else if ("\\" === char) state = "'" === nextChar ? "ESCAPE_SQ" : '"' === nextChar ? "ESCAPE_DQ" : "`" === nextChar ? "ESCAPE_TEMPLATE" : "ESCAPE_EXPR";
794
+ else if (this._isMatch(pos, template, this.exprEnd)) {
795
+ var exprValue = this.preserveWhitespace ? buffer : buffer.trim();
796
+ if (exprValue.length > 0) tokens.push({
797
+ type: "expression",
798
+ value: exprValue,
799
+ start: exprStartPos,
800
+ end: pos + this.endLen,
801
+ contentStart: exprStartPos + this.startLen,
802
+ contentEnd: pos
803
+ });
804
+ buffer = "";
805
+ state = "TEXT";
806
+ pos += this.endLen;
807
+ continue;
808
+ }
809
+ buffer += char;
810
+ break;
811
+ case "STRING_SQ":
812
+ if ("\\" === char) state = "ESCAPE_SQ";
813
+ else if ("'" === char) state = "EXPR";
814
+ buffer += char;
815
+ break;
816
+ case "STRING_DQ":
817
+ if ("\\" === char) state = "ESCAPE_DQ";
818
+ else if ('"' === char) state = "EXPR";
819
+ buffer += char;
820
+ break;
821
+ case "TEMPLATE":
822
+ if ("\\" === char) state = "ESCAPE_TEMPLATE";
823
+ else if ("`" === char) state = "EXPR";
824
+ buffer += char;
825
+ break;
826
+ case "ESCAPE_SQ":
827
+ buffer += char;
828
+ state = "STRING_SQ";
829
+ break;
830
+ case "ESCAPE_DQ":
831
+ buffer += char;
832
+ state = "STRING_DQ";
833
+ break;
834
+ case "ESCAPE_TEMPLATE":
835
+ buffer += char;
836
+ state = "TEMPLATE";
837
+ break;
838
+ case "ESCAPE_EXPR":
839
+ buffer += char;
840
+ state = "EXPR";
841
+ break;
842
+ }
843
+ pos++;
844
+ }
845
+ if (buffer.length > 0) if ("TEXT" === state) tokens.push({
846
+ type: "text",
847
+ value: buffer,
848
+ start: pos - buffer.length,
849
+ end: pos
850
+ });
851
+ else {
852
+ var incompleteExpr = this.exprStart + buffer;
853
+ tokens.push({
854
+ type: "text",
855
+ value: incompleteExpr,
856
+ start: exprStartPos,
857
+ end: pos
858
+ });
859
+ console.warn("警告:在位置 ".concat(exprStartPos, " 开始的表达式未正确结束"));
860
+ }
861
+ return tokens;
862
+ }
863
+ },
864
+ {
865
+ key: "_isMatch",
866
+ value: function(pos, template, sequence) {
867
+ if (pos + sequence.length > template.length) return false;
868
+ for(var i = 0; i < sequence.length; i++)if (template[pos + i] !== sequence[i]) return false;
869
+ return true;
870
+ }
871
+ }
872
+ ], [
873
+ {
874
+ key: "parse",
875
+ value: function(template, options) {
876
+ var parser = new TemplateParser(options);
877
+ return parser.parse(template);
878
+ }
879
+ }
880
+ ]);
881
+ return TemplateParser;
882
+ }();
883
+ function src_instanceof(left, right) {
884
+ if (null != right && "undefined" != typeof Symbol && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
885
+ return left instanceof right;
886
+ }
887
+ function evalExpression(expression, context) {
888
+ return Evaluator_Evaluator.evaluate(expression, context);
889
+ }
890
+ function evalTemplate(template, context, templateParserOptions) {
891
+ var result = "";
892
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
893
+ try {
894
+ for(var _iterator = TemplateParser_TemplateParser.parse(template, templateParserOptions)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
895
+ var token = _step.value;
896
+ if ("text" === token.type) result += token.value;
897
+ else if ("expression" === token.type) try {
898
+ result += Evaluator_Evaluator.evaluate(token.value, context);
899
+ } catch (error) {
900
+ if (src_instanceof(error, ReferenceError) && error.message.endsWith("is not defined")) result += "undefined";
901
+ else throw error;
902
+ }
903
+ }
904
+ } catch (err) {
905
+ _didIteratorError = true;
906
+ _iteratorError = err;
907
+ } finally{
619
908
  try {
620
- var value = evaluator.evaluate(expression.trim());
621
- return String(value);
622
- } catch (error) {
623
- if (error instanceof ReferenceError && error.message.endsWith("is not defined")) return "";
624
- throw error;
909
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
910
+ } finally{
911
+ if (_didIteratorError) throw _iteratorError;
625
912
  }
626
- });
913
+ }
914
+ return result;
627
915
  }
628
- exports.evaluatorExpression = __webpack_exports__.evaluatorExpression;
629
- exports.evaluatorTemplate = __webpack_exports__.evaluatorTemplate;
916
+ exports.Evaluator = __webpack_exports__.Evaluator;
917
+ exports.evalExpression = __webpack_exports__.evalExpression;
918
+ exports.evalTemplate = __webpack_exports__.evalTemplate;
630
919
  for(var __webpack_i__ in __webpack_exports__)if (-1 === [
631
- "evaluatorExpression",
632
- "evaluatorTemplate"
920
+ "Evaluator",
921
+ "evalExpression",
922
+ "evalTemplate"
633
923
  ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
634
924
  Object.defineProperty(exports, '__esModule', {
635
925
  value: true