@zvenigora/ng-eval-core 0.11.1 → 0.12.1

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.
@@ -1,7 +1,7 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable, inject } from '@angular/core';
2
+ import { InjectionToken, inject, makeEnvironmentProviders, provideEnvironmentInitializer, Injectable } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
- import { parse as parse$1, defaultOptions, version } from 'acorn';
4
+ import { tokTypes, Parser, parse as parse$1, defaultOptions, version } from 'acorn';
5
5
  import * as walk from 'acorn-walk';
6
6
 
7
7
  /**
@@ -694,50 +694,6 @@ const setContextValue = (context, key, value) => {
694
694
  }
695
695
  };
696
696
 
697
- /**
698
- * The two push helpers each carry their own trace-bound call rather than
699
- * sharing one.
700
- *
701
- * **Why the read is at these two sites.** `st.maxTraceItems` is the *walk's*
702
- * bound. `EvalResult` cannot read it for itself: it holds a context, and a
703
- * context's options are not the walk's - the split `CLAUDE.md` documents for
704
- * `caseInsensitive`. So the option is read where `st` is in hand and passed in.
705
- *
706
- * **Why the one line is duplicated rather than factored.** A shared helper put
707
- * a third frame on a path taken once per node - `push` -> helper ->
708
- * `addTraceBounded` -> `EvalTrace.add` - to save one identical line. Measured
709
- * both ways at 50,000 walks of `2 + 3 * a`, the difference was inside
710
- * run-to-run noise, so this is not a speed claim; it is that the helper cost a
711
- * frame on the hot path and bought nothing, and that `addTraceBounded`'s own
712
- * docblock claims one call per push, which only this shape makes true.
713
- *
714
- * **The value stack is not bounded and must not be.** It is how visitors return
715
- * values to each other, and dropping an entry desynchronises every node above
716
- * it. Only the trace - which nothing in this library reads - is capped.
717
- */
718
- const pushVisitorResult = (node, st, value) => {
719
- const result = st.result;
720
- result.stack.push(value);
721
- result.addTraceBounded(node, value, st.maxTraceItems);
722
- return value;
723
- };
724
- const popVisitorResult = (node, st) => {
725
- const result = st.result;
726
- const value = result.stack.pop();
727
- return value;
728
- };
729
- const pushVisitorResultAsync = (node, st, value) => {
730
- const result = st.result;
731
- result.stack.push(value);
732
- result.addTraceBounded(node, value, st.maxTraceItems);
733
- return value;
734
- };
735
- const popVisitorResultAsync = (node, st) => {
736
- const result = st.result;
737
- const value = result.stack.pop();
738
- return value;
739
- };
740
-
741
697
  /**
742
698
  * Opens a node: records it as open and fires the registered 'before' hooks.
743
699
  *
@@ -775,80 +731,6 @@ const afterVisitor = (node, st) => {
775
731
  st.hooks.dispatch('after', node, st, value);
776
732
  };
777
733
 
778
- /**
779
- * Strips the `ParenthesizedExpression` wrappers acorn keeps around a node
780
- * under `preserveParens`, so `(a)` and `((a))` are handled as `a`. A walk
781
- * passes through them without help, since `acorn-walk`'s base visitor does;
782
- * only a visitor that branches on a child's *type* has to unwrap it first.
783
- * @param node - The node, possibly parenthesised.
784
- * @returns The innermost node that is not a `ParenthesizedExpression`.
785
- */
786
- const unwrapParentheses = (node) => {
787
- let inner = node;
788
- while (inner.type === 'ParenthesizedExpression') {
789
- inner = inner.expression;
790
- }
791
- return inner;
792
- };
793
- /**
794
- * Retrieves the key-value pair from an object based on the provided key.
795
- * @param obj - The object to search for the key-value pair.
796
- * @param key - The key to search for in the object.
797
- * @param caseInsesitive - Specifies whether the key comparison should be case-insensitive.
798
- * @returns The key-value pair as an array, or undefined if the key is not found.
799
- */
800
- const getKeyValue = (obj, key, caseInsesitive) => {
801
- if (!caseInsesitive || typeof key !== 'string') {
802
- const value = obj[key];
803
- return [key, value];
804
- }
805
- if (typeof key === 'string') {
806
- let currentObj = obj;
807
- do {
808
- const keys = Object.getOwnPropertyNames(currentObj);
809
- if (Array.isArray(keys)) {
810
- const foundKey = keys.find(k => equalIgnoreCase(key, k));
811
- if (foundKey) {
812
- const value = currentObj[foundKey];
813
- return [foundKey, value];
814
- }
815
- }
816
- } while ((currentObj = Object.getPrototypeOf(currentObj)));
817
- }
818
- return undefined;
819
- };
820
- /**
821
- * Compares two values for equality, ignoring case sensitivity.
822
- * @param a - The first value to compare.
823
- * @param b - The second value to compare.
824
- * @returns `true` if the values are equal, `false` otherwise.
825
- */
826
- const equalIgnoreCase = (a, b) => {
827
- if (typeof a === 'number' || typeof b === 'number') {
828
- return a === b;
829
- }
830
- else if (typeof a === 'symbol' || typeof b === 'symbol') {
831
- return a === b;
832
- }
833
- else if (typeof a === 'string' || typeof b === 'string') {
834
- return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
835
- }
836
- return undefined;
837
- };
838
- /**
839
- * Retrieves the value from an object, ignoring the case of the key.
840
- * @param obj - The object to retrieve the value from.
841
- * @param key - The key to search for, ignoring the case.
842
- * @returns The value associated with the key, or undefined if the key is not found.
843
- */
844
- const getValueIgnoreCase = (obj, key) => {
845
- const pair = getKeyValue(obj, key, true);
846
- if (pair) {
847
- return pair[1];
848
- }
849
- return undefined;
850
- };
851
-
852
734
  /**
853
735
  * Prototype Pollution Prevention Utilities
854
736
  *
@@ -1104,318 +986,78 @@ const validateSafeObject = (obj) => {
1104
986
  }
1105
987
  };
1106
988
 
1107
- const literals = Registry.fromObject({
1108
- 'undefined': undefined,
1109
- 'null': null,
1110
- 'true': true,
1111
- 'false': false,
1112
- }, { caseInsensitive: true });
1113
989
  /**
1114
- * Reports a resolved identifier read to the hook layer.
1115
- *
1116
- * The key is the one the context actually matched, so a case-insensitive
1117
- * lookup reports the corrected spelling; `getKey` returns undefined for a name
1118
- * the context does not hold - a literal-registry resolution, or a miss - and
1119
- * the source name stands in. The path is always the source spelling, since it
1120
- * is reconstructed statically.
1121
- *
1122
- * `scoped` marks a read of a name bound by any scope on the context's scope
1123
- * stack when the name is read, whoever pushed it: an arrow-function
1124
- * parameter, a declaration in the lexical scope `program.ts`,
1125
- * `block-statement.ts` or `for-statement.ts` pushes, or a binding the caller
1126
- * pushed with `EvalContext.push` before the walk - which is how `eval-signals`
1127
- * binds a run's `AbortSignal` under `abortSignalKey`, and why that key never
1128
- * reaches its `dependencies`. It is asked of `EvalContext.hasInScopes`, which
1129
- * tests for the binding rather than for its value: a parameter bound to
1130
- * `undefined` is still a parameter, and reading the flag off the resolved value
1131
- * would make it vary with the data rather than with the expression.
1132
- *
1133
- * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
1134
- * long-lived objects and are real dependencies, so the discriminator is
1135
- * lifetime rather than `instanceof EvalScope`. The property is omitted rather
1136
- * than set to false, so absent reads as "not scoped" the same way it does at
1137
- * the member emission sites.
1138
- *
1139
- * The scope stack is empty only for a walk that does not start at a `Program`
1140
- * and has nothing pushed by its caller: `program.ts` pushes a scope at the root
1141
- * of every walk through `EvalService`. `Stack.asArray` allocates, so that empty
1142
- * case is short-circuited on length.
990
+ * Strips the `ParenthesizedExpression` wrappers acorn keeps around a node
991
+ * under `preserveParens`, so `(a)` and `((a))` are handled as `a`. A walk
992
+ * passes through them without help, since `acorn-walk`'s base visitor does;
993
+ * only a visitor that branches on a child's *type* has to unwrap it first.
994
+ * @param node - The node, possibly parenthesised.
995
+ * @returns The innermost node that is not a `ParenthesizedExpression`.
1143
996
  */
1144
- const emitRead = (node, st, value) => {
1145
- const key = st.context?.getKey(node.name) ?? node.name;
1146
- const scoped = !!st.context
1147
- && st.context.scopes.length > 0
1148
- && st.context.hasInScopes(node.name);
1149
- st.hooks.dispatchRead({
1150
- kind: 'identifier',
1151
- node,
1152
- state: st,
1153
- key,
1154
- target: st.context,
1155
- path: node.name,
1156
- value,
1157
- ...(scoped ? { scoped: true } : {})
1158
- });
997
+ const unwrapParentheses = (node) => {
998
+ let inner = node;
999
+ while (inner.type === 'ParenthesizedExpression') {
1000
+ inner = inner.expression;
1001
+ }
1002
+ return inner;
1159
1003
  };
1160
1004
  /**
1161
- * Refuses an identifier whose name is on the prototype-pollution blocklist,
1162
- * before any lookup, with the member visitor's error.
1163
- *
1164
- * An identifier is resolved against the context, and `EvalContext.get` reads a
1165
- * plain object there - the original, or a scope - with a bare property access.
1166
- * So up to 0.10.x a name on the blocklist resolved to what the context inherits
1167
- * from `Object.prototype` (`docs/backlog-retired.md` B6): the blocklist guarded
1168
- * member access to the objects an expression holds, and the context is not one
1169
- * of them. Every kind of context is refused alike, including those - a
1170
- * `Registry`, a signal context's source - that hold such a name only as a key
1171
- * of their own.
1005
+ * Retrieves the key-value pair from an object based on the provided key.
1006
+ * @param obj - The object to search for the key-value pair.
1007
+ * @param key - The key to search for in the object.
1008
+ * @param caseInsesitive - Specifies whether the key comparison should be case-insensitive.
1009
+ * @returns The key-value pair as an array, or undefined if the key is not found.
1172
1010
  */
1173
- const refuseDangerousName = (node) => {
1174
- if (isDangerousProperty(node.name)) {
1175
- throw new Error(`Access to dangerous property "${node.name}" is blocked for security reasons`);
1011
+ const getKeyValue = (obj, key, caseInsesitive) => {
1012
+ if (!caseInsesitive || typeof key !== 'string') {
1013
+ const value = obj[key];
1014
+ return [key, value];
1015
+ }
1016
+ if (typeof key === 'string') {
1017
+ let currentObj = obj;
1018
+ do {
1019
+ const keys = Object.getOwnPropertyNames(currentObj);
1020
+ if (Array.isArray(keys)) {
1021
+ const foundKey = keys.find(k => equalIgnoreCase(key, k));
1022
+ if (foundKey) {
1023
+ const value = currentObj[foundKey];
1024
+ return [foundKey, value];
1025
+ }
1026
+ }
1027
+ } while ((currentObj = Object.getPrototypeOf(currentObj)));
1176
1028
  }
1029
+ return undefined;
1177
1030
  };
1178
1031
  /**
1179
- * Under `caseInsensitive`, refuses an identifier whose lookup matched a key on
1180
- * the blocklist - `CONSTRUCTOR` over a context holding `constructor` - as the
1181
- * member visitor re-checks `foundKey` for another object.
1182
- *
1183
- * The matched key is asked of `getKey`, which answers the key `get` resolves,
1184
- * and only for a name `mayMatchDangerousProperty` lets through. Any other name
1185
- * cannot match a blocklisted key, and an identifier must not pay a second
1186
- * resolution for nothing: the performance spec's read-emission guard asserts
1187
- * that, with no read hook, `getKey` is not called per identifier.
1032
+ * Compares two values for equality, ignoring case sensitivity.
1033
+ * @param a - The first value to compare.
1034
+ * @param b - The second value to compare.
1035
+ * @returns `true` if the values are equal, `false` otherwise.
1188
1036
  */
1189
- const refuseDangerousMatch = (node, st) => {
1190
- if (!st.context || !mayMatchDangerousProperty(node.name)) {
1191
- return;
1037
+ const equalIgnoreCase = (a, b) => {
1038
+ if (typeof a === 'number' || typeof b === 'number') {
1039
+ return a === b;
1192
1040
  }
1193
- const matched = st.context.getKey(node.name);
1194
- if (isDangerousProperty(matched)) {
1195
- throw new Error(`Access to dangerous property "${String(matched)}" is blocked for security reasons`);
1041
+ else if (typeof a === 'symbol' || typeof b === 'symbol') {
1042
+ return a === b;
1196
1043
  }
1197
- };
1198
- const identifierVisitor = (node, st) => {
1199
- if (st.options?.caseInsensitive) {
1200
- return identifierVisitorCaseInsensitive(node, st);
1044
+ else if (typeof a === 'string' || typeof b === 'string') {
1045
+ return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
1201
1046
  }
1202
- beforeVisitor(node, st);
1203
- refuseDangerousName(node);
1204
- const context = st.context;
1205
- const isThis = node.name === 'this';
1206
- const value = isThis
1207
- ? st.context
1208
- : context?.get(node.name);
1209
- // `this` resolves to the context object itself rather than to a key within
1210
- // it, so it is not a read: reporting it would have a dependency tracker
1211
- // record the whole context and re-fire on every change to it.
1212
- if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
1213
- emitRead(node, st, value);
1214
- }
1215
- pushVisitorResult(node, st, value);
1216
- afterVisitor(node, st);
1217
- };
1218
- const identifierVisitorCaseInsensitive = (node, st) => {
1219
- beforeVisitor(node, st);
1220
- refuseDangerousName(node);
1221
- const context = st.context;
1222
- const isThis = !!equalIgnoreCase(node.name, 'this');
1223
- if (!isThis) {
1224
- refuseDangerousMatch(node, st);
1225
- }
1226
- const value = isThis
1227
- ? st.context
1228
- : context?.get(node.name) ?? literals.get(node.name);
1229
- if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
1230
- emitRead(node, st, value);
1231
- }
1232
- pushVisitorResult(node, st, value);
1233
- afterVisitor(node, st);
1234
- };
1235
-
1236
- const literalVisitor = (node, st) => {
1237
- beforeVisitor(node, st);
1238
- // A regex literal is a new `RegExp` on every evaluation, as it is in
1239
- // JavaScript. Acorn builds `node.value` once, at parse time, and every walk of
1240
- // the parsed tree used to push that one object - a cached `simpleEval` string
1241
- // and each recompute of a compiled expression alike - so `lastIndex` carried
1242
- // from one evaluation into the next, and `/a/g.test("a")` answered true, then
1243
- // false. A copy starts at `lastIndex` 0, and being new it is recorded under a
1244
- // member-write policy, as a literal is - `EvalContext.checkMemberWrite`. When
1245
- // acorn could not build the regex in this environment, `value` is null and is
1246
- // pushed as before.
1247
- let value = node.value;
1248
- if (value instanceof RegExp) {
1249
- value = new RegExp(value);
1250
- st.createdObjects?.add(value);
1251
- }
1252
- pushVisitorResult(node, st, value);
1253
- afterVisitor(node, st);
1254
- };
1255
-
1256
- // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1257
- /**
1258
- * Converts value to primitive for comparison operations
1259
- */
1260
- const toPrimitive = (value, hint) => {
1261
- if (value === null || value === undefined)
1262
- return value;
1263
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||
1264
- typeof value === 'symbol' || typeof value === 'bigint')
1265
- return value;
1266
- // For objects, call valueOf/toString based on hint
1267
- if (typeof value === 'object') {
1268
- if (hint === 'number') {
1269
- const valueOf = value.valueOf;
1270
- if (typeof valueOf === 'function') {
1271
- const result = valueOf.call(value);
1272
- if (typeof result !== 'object')
1273
- return result;
1274
- }
1275
- const toString = value.toString;
1276
- if (typeof toString === 'function') {
1277
- return toString.call(value);
1278
- }
1279
- }
1280
- else {
1281
- const toString = value.toString;
1282
- if (typeof toString === 'function') {
1283
- const result = toString.call(value);
1284
- if (typeof result === 'string')
1285
- return result;
1286
- }
1287
- const valueOf = value.valueOf;
1288
- if (typeof valueOf === 'function') {
1289
- const result = valueOf.call(value);
1290
- if (typeof result !== 'object')
1291
- return result;
1292
- }
1293
- }
1294
- }
1295
- return String(value);
1047
+ return undefined;
1296
1048
  };
1297
1049
  /**
1298
- * Safely evaluates binary operations with proper type coercion
1050
+ * Retrieves the value from an object, ignoring the case of the key.
1051
+ * @param obj - The object to retrieve the value from.
1052
+ * @param key - The key to search for, ignoring the case.
1053
+ * @returns The value associated with the key, or undefined if the key is not found.
1299
1054
  */
1300
- const evaluateBinaryOperation = (operator, left, right) => {
1301
- switch (operator) {
1302
- case '+': {
1303
- // Handle string concatenation and numeric addition according to JavaScript rules
1304
- const leftPrim = toPrimitive(left);
1305
- const rightPrim = toPrimitive(right);
1306
- if (typeof leftPrim === 'string' || typeof rightPrim === 'string') {
1307
- return String(leftPrim) + String(rightPrim);
1308
- }
1309
- return Number(leftPrim) + Number(rightPrim);
1310
- }
1311
- case '-':
1312
- return Number(toPrimitive(left, 'number')) - Number(toPrimitive(right, 'number'));
1313
- case '*':
1314
- return Number(toPrimitive(left, 'number')) * Number(toPrimitive(right, 'number'));
1315
- case '/':
1316
- return Number(toPrimitive(left, 'number')) / Number(toPrimitive(right, 'number'));
1317
- case '%':
1318
- return Number(toPrimitive(left, 'number')) % Number(toPrimitive(right, 'number'));
1319
- case '**':
1320
- return Number(toPrimitive(left, 'number')) ** Number(toPrimitive(right, 'number'));
1321
- // Bitwise operations - convert to 32-bit integers
1322
- case '<<':
1323
- return (Number(toPrimitive(left, 'number')) | 0) << (Number(toPrimitive(right, 'number')) | 0);
1324
- case '>>':
1325
- return (Number(toPrimitive(left, 'number')) | 0) >> (Number(toPrimitive(right, 'number')) | 0);
1326
- case '>>>':
1327
- return (Number(toPrimitive(left, 'number')) >>> 0) >>> (Number(toPrimitive(right, 'number')) | 0);
1328
- case '&':
1329
- return (Number(toPrimitive(left, 'number')) | 0) & (Number(toPrimitive(right, 'number')) | 0);
1330
- case '^':
1331
- return (Number(toPrimitive(left, 'number')) | 0) ^ (Number(toPrimitive(right, 'number')) | 0);
1332
- case '|':
1333
- return (Number(toPrimitive(left, 'number')) | 0) | (Number(toPrimitive(right, 'number')) | 0);
1334
- // Comparison operations - follow JavaScript's abstract comparison rules
1335
- case '==':
1336
- return left == right;
1337
- case '!=':
1338
- return left != right;
1339
- case '===':
1340
- return left === right;
1341
- case '!==':
1342
- return left !== right;
1343
- case '<': {
1344
- const leftComp = toPrimitive(left, 'number');
1345
- const rightComp = toPrimitive(right, 'number');
1346
- // If both are strings, do string comparison
1347
- if (typeof leftComp === 'string' && typeof rightComp === 'string') {
1348
- return leftComp < rightComp;
1349
- }
1350
- return Number(leftComp) < Number(rightComp);
1351
- }
1352
- case '<=': {
1353
- const leftLE = toPrimitive(left, 'number');
1354
- const rightLE = toPrimitive(right, 'number');
1355
- if (typeof leftLE === 'string' && typeof rightLE === 'string') {
1356
- return leftLE <= rightLE;
1357
- }
1358
- return Number(leftLE) <= Number(rightLE);
1359
- }
1360
- case '>': {
1361
- const leftGT = toPrimitive(left, 'number');
1362
- const rightGT = toPrimitive(right, 'number');
1363
- if (typeof leftGT === 'string' && typeof rightGT === 'string') {
1364
- return leftGT > rightGT;
1365
- }
1366
- return Number(leftGT) > Number(rightGT);
1367
- }
1368
- case '>=': {
1369
- const leftGE = toPrimitive(left, 'number');
1370
- const rightGE = toPrimitive(right, 'number');
1371
- if (typeof leftGE === 'string' && typeof rightGE === 'string') {
1372
- return leftGE >= rightGE;
1373
- }
1374
- return Number(leftGE) >= Number(rightGE);
1375
- }
1376
- // Special operations
1377
- case 'in': {
1378
- if (typeof left === 'string' || typeof left === 'number' || typeof left === 'symbol') {
1379
- if (right == null) {
1380
- throw new Error(`Cannot use 'in' operator with null or undefined right operand`);
1381
- }
1382
- return left in right;
1383
- }
1384
- throw new Error(`Invalid left operand for 'in' operator: ${typeof left}`);
1385
- }
1386
- case 'instanceof': {
1387
- if (typeof right === 'function') {
1388
- return left instanceof right;
1389
- }
1390
- throw new Error(`Right operand of 'instanceof' is not a constructor`);
1391
- }
1392
- case '??':
1393
- return left ?? right;
1394
- default:
1395
- throw new Error(`Unsupported binary operator: ${operator}`);
1055
+ const getValueIgnoreCase = (obj, key) => {
1056
+ const pair = getKeyValue(obj, key, true);
1057
+ if (pair) {
1058
+ return pair[1];
1396
1059
  }
1397
- };
1398
- /**
1399
- * Safely evaluates binary expressions with proper type handling
1400
- */
1401
- const binaryExpressionVisitor = (node, st, callback) => {
1402
- beforeVisitor(node, st);
1403
- // Disable visitor result caching for now due to context sensitivity issues
1404
- // const cachedResult = getCachedVisitorResult(node, st.context);
1405
- // if (cachedResult !== undefined) {
1406
- // pushVisitorResult(node, st, cachedResult);
1407
- // afterVisitor(node, st);
1408
- // return;
1409
- // }
1410
- callback(node.left, st);
1411
- const left = popVisitorResult(node, st);
1412
- callback(node.right, st);
1413
- const right = popVisitorResult(node, st);
1414
- const value = evaluateBinaryOperation(node.operator, left, right);
1415
- // Disable visitor result caching for now
1416
- // setCachedVisitorResult(node, st.context, value);
1417
- pushVisitorResult(node, st, value);
1418
- afterVisitor(node, st);
1060
+ return undefined;
1419
1061
  };
1420
1062
 
1421
1063
  /**
@@ -1857,8 +1499,10 @@ const argumentsOf = (list) => isObjectLike(list) ? Array.prototype.slice.call(li
1857
1499
  * arguments: binding a built-in to an object the walk did not create is
1858
1500
  * refused before the bound function exists (`docs/backlog-retired.md` C5).
1859
1501
  *
1860
- * Called by `call-expression.ts` immediately before the call, and only after
1861
- * it has read `st.createdObjects` and found it set, as for a member write.
1502
+ * Called by `call-expression.ts` immediately before a call, and by
1503
+ * `tagged-template-expression.ts` immediately before a tag is called, in each
1504
+ * case only after the caller has read `st.createdObjects` and found it set, as
1505
+ * for a member write.
1862
1506
  *
1863
1507
  * @param st - The state of the walk making the call.
1864
1508
  * @param created - `st.createdObjects`, already read by the caller.
@@ -1894,6 +1538,9 @@ const consultMethodWrite = (st, created, fn, receiver, args) => {
1894
1538
 
1895
1539
  /**
1896
1540
  * Security: List of dangerous functions that should not be callable
1541
+ *
1542
+ * Also the names `dangerous-values.ts` reads from `globalThis` into its
1543
+ * identity set, and the names its bound-function rule refuses.
1897
1544
  */
1898
1545
  const DANGEROUS_FUNCTIONS = new Set([
1899
1546
  'Function',
@@ -1958,6 +1605,12 @@ const isFunctionSafe = (fn, fnName) => {
1958
1605
  if (fn === Function) {
1959
1606
  return false;
1960
1607
  }
1608
+ // A dangerous function by value, under whatever name it was reached:
1609
+ // an alias, a member, a call result, a case variant (`dangerous-values.ts`).
1610
+ // Up to 0.12.0 only the written name was checked (`docs/backlog.md` A35).
1611
+ if (isDangerousValue(fn)) {
1612
+ return false;
1613
+ }
1961
1614
  try {
1962
1615
  // Check function string for dangerous patterns
1963
1616
  const fnString = fn.toString();
@@ -1979,107 +1632,712 @@ const isFunctionSafe = (fn, fnName) => {
1979
1632
  * re-raised as a new `Error` with a fixed prefix on its message, which no
1980
1633
  * caller could route around, since the call is inside the walk
1981
1634
  * (`docs/backlog-retired.md` A6).
1635
+ *
1636
+ * Also the call a tag that is not a member goes through
1637
+ * (`tagged-template-expression.ts`).
1982
1638
  */
1983
1639
  const safeCall = (caller, thisArg, args, optional = false, fnName) => {
1984
1640
  if (!caller) {
1985
1641
  if (optional) {
1986
1642
  return undefined;
1987
1643
  }
1988
- throw new Error(`Cannot call undefined or null function`);
1989
- }
1990
- if (typeof caller !== 'function') {
1991
- throw new Error(`Value is not a function: ${typeof caller}`);
1992
- }
1993
- if (!isFunctionSafe(caller, fnName)) {
1994
- throw new Error(`Function call blocked for security reasons: ${fnName || 'anonymous'}`);
1995
- }
1996
- return caller.apply(thisArg, args);
1997
- };
1998
- /**
1999
- * The receiver for a method called on `object`: a prior scope's `thisArg` when
2000
- * `object` is that scope's own object, `object` otherwise.
2001
- *
2002
- * `ns.fn()` reaches `fn` through the namespace, which evaluates to the scope's
2003
- * object and has to keep doing so - `ns` alone, or `ns === x`, must not see
2004
- * `thisArg`. So the substitution is made here, at the call, and nowhere
2005
- * earlier: `evaluateMember`'s first slot is also the target of `ns.x = v`, and
2006
- * a write belongs on the scope's object. Matched by identity, so it follows the
2007
- * object rather than the name it was reached by; the first scope holding the
2008
- * object answers, as in `EvalContext.get`. Up to 0.6.x `thisArg` was never
2009
- * applied (`docs/backlog-retired.md` A7).
2010
- *
2011
- * `this.fn()` does not need this: `EvalContext.getThis` answers it.
2012
- *
2013
- * A call with no prior scopes pays one length check.
2014
- */
2015
- const scopeReceiver = (st, object) => {
2016
- const priorScopes = st.context?.priorScopes;
2017
- if (!priorScopes?.length) {
2018
- return object;
2019
- }
2020
- for (const scope of priorScopes) {
2021
- if (scope.context === object) {
2022
- return scope.options.thisArg ?? object;
1644
+ throw new Error(`Cannot call undefined or null function`);
1645
+ }
1646
+ if (typeof caller !== 'function') {
1647
+ throw new Error(`Value is not a function: ${typeof caller}`);
1648
+ }
1649
+ if (!isFunctionSafe(caller, fnName)) {
1650
+ throw new Error(`Function call blocked for security reasons: ${fnName || 'anonymous'}`);
1651
+ }
1652
+ return caller.apply(thisArg, args);
1653
+ };
1654
+ /**
1655
+ * The receiver for a method called on `object`: a prior scope's `thisArg` when
1656
+ * `object` is that scope's own object, `object` otherwise.
1657
+ *
1658
+ * `ns.fn()` reaches `fn` through the namespace, which evaluates to the scope's
1659
+ * object and has to keep doing so - `ns` alone, or `ns === x`, must not see
1660
+ * `thisArg`. So the substitution is made here, at the call, and nowhere
1661
+ * earlier: `evaluateMember`'s first slot is also the target of `ns.x = v`, and
1662
+ * a write belongs on the scope's object. Matched by identity, so it follows the
1663
+ * object rather than the name it was reached by; the first scope holding the
1664
+ * object answers, as in `EvalContext.get`. Up to 0.6.x `thisArg` was never
1665
+ * applied (`docs/backlog-retired.md` A7).
1666
+ *
1667
+ * `this.fn()` does not need this: `EvalContext.getThis` answers it.
1668
+ *
1669
+ * A call with no prior scopes pays one length check.
1670
+ */
1671
+ const scopeReceiver = (st, object) => {
1672
+ const priorScopes = st.context?.priorScopes;
1673
+ if (!priorScopes?.length) {
1674
+ return object;
1675
+ }
1676
+ for (const scope of priorScopes) {
1677
+ if (scope.context === object) {
1678
+ return scope.options.thisArg ?? object;
1679
+ }
1680
+ }
1681
+ return object;
1682
+ };
1683
+ /**
1684
+ * Calls the function a member callee reads, from what `evaluateMember`
1685
+ * returned for it: the receiver `scopeReceiver` gives, the context's write
1686
+ * policy asked first, then the sandbox, with the property name as the checked
1687
+ * name - a computed key included, since `obj["fetch"]` reads the key `fetch`.
1688
+ *
1689
+ * Shared by a member call and a member tag (`tagged-template-expression.ts`),
1690
+ * so the two cannot drift. Up to 0.12.0 a tag was applied with the context as
1691
+ * `this` and no check at all (`docs/backlog-retired.md` A36). Each visitor
1692
+ * evaluates the member itself and hands the result in, so each keeps its own
1693
+ * order: a call's arguments before its callee, a tag before its template's
1694
+ * expressions.
1695
+ */
1696
+ const callMember = (st, [object, propertyName, fn], args, optional) => {
1697
+ const functionName = typeof propertyName === 'string' ? propertyName : undefined;
1698
+ const receiver = scopeReceiver(st, object);
1699
+ const created = st.createdObjects;
1700
+ if (created) {
1701
+ consultMethodWrite(st, created, fn, receiver, args);
1702
+ }
1703
+ return safeCall(fn, receiver, args, optional, functionName);
1704
+ };
1705
+ /**
1706
+ * Enhanced call expression visitor with security checks
1707
+ *
1708
+ * A context with a member-write policy is asked, before the call, about a
1709
+ * built-in that writes into its receiver or its first argument - see
1710
+ * `consultMethodWrite`. The receiver asked about is the one the call is made
1711
+ * with: the member's object, a prior scope's `thisArg`, or the context itself
1712
+ * for a bare call. A context without a policy pays one field read per call.
1713
+ */
1714
+ const callExpressionVisitor = (node, st, callback) => {
1715
+ beforeVisitor(node, st);
1716
+ const args = evaluateArray(node, node.arguments, st, callback);
1717
+ if (node.callee.type === 'MemberExpression') {
1718
+ const value = callMember(st, evaluateMember(node.callee, st, callback), args, node.callee.optional);
1719
+ pushVisitorResult(node, st, value);
1720
+ }
1721
+ else {
1722
+ // The callee's own value is checked by `safeCall`, with the call's
1723
+ // message; what is read under it still passes the funnel.
1724
+ exemptFromFunnel(node.callee);
1725
+ callback(node.callee, st);
1726
+ const caller = popVisitorResult(node, st);
1727
+ // Try to get function name for security checks
1728
+ let functionName;
1729
+ if (node.callee.type === 'Identifier') {
1730
+ functionName = node.callee.name;
1731
+ }
1732
+ const created = st.createdObjects;
1733
+ if (created) {
1734
+ consultMethodWrite(st, created, caller, st.context, args);
1735
+ }
1736
+ const value = safeCall(caller, st.context, args, node.optional, functionName);
1737
+ pushVisitorResult(node, st, value);
1738
+ }
1739
+ afterVisitor(node, st);
1740
+ };
1741
+ const evaluateCall = (node, st, callback) => {
1742
+ callback(node.callee, st);
1743
+ const caller = popVisitorResult(node, st);
1744
+ const args = node.arguments.map((argument) => {
1745
+ callback(argument, st);
1746
+ const value = popVisitorResult(node, st);
1747
+ return value;
1748
+ });
1749
+ // Get function name for security checks
1750
+ let functionName;
1751
+ if (node.callee.type === 'Identifier') {
1752
+ functionName = node.callee.name;
1753
+ }
1754
+ const value = safeCall(caller, st.context, args, false, functionName);
1755
+ return value;
1756
+ };
1757
+
1758
+ /**
1759
+ * The prototype of a function literal of each kind, read from this module's
1760
+ * own literals. Never built from source text through `Function` or `eval`:
1761
+ * that fails under a CSP without `unsafe-eval`, and a sandbox must not
1762
+ * construct code to defend itself.
1763
+ */
1764
+ const literalPrototypes = () => ({
1765
+ AsyncFunction: Object.getPrototypeOf(async function () { }),
1766
+ GeneratorFunction: Object.getPrototypeOf(function* () { }),
1767
+ AsyncGeneratorFunction: Object.getPrototypeOf(async function* () { }),
1768
+ });
1769
+ /**
1770
+ * Reads the constructor off each prototype in `prototypes`.
1771
+ *
1772
+ * A constructor that is `Function` itself is not captured, and is recorded
1773
+ * as such: a realm whose bundler downlevels async functions - Jest's, or an
1774
+ * Angular zone.js build - makes an async literal a plain function, and the
1775
+ * real constructor is no global there. An expression reaches it only through
1776
+ * some value's `constructor`, which the guard refuses, so only a host could
1777
+ * put it in the context.
1778
+ *
1779
+ * @param prototypes - The prototype of each kind; this module's literals by
1780
+ * default. A spec injects its own.
1781
+ */
1782
+ const captureFunctionConstructors = (prototypes = literalPrototypes()) => {
1783
+ const captured = new Map();
1784
+ const notCaptured = [];
1785
+ for (const name of Object.keys(prototypes)) {
1786
+ const prototype = prototypes[name];
1787
+ const constructor = prototype ? prototype.constructor : undefined;
1788
+ if (typeof constructor === 'function' && constructor !== Function) {
1789
+ captured.set(name, constructor);
1790
+ }
1791
+ else {
1792
+ notCaptured.push(name);
1793
+ }
1794
+ }
1795
+ return { captured, notCaptured };
1796
+ };
1797
+ /** The prefix `Function.prototype.bind` gives a bound function's `name`. */
1798
+ const BOUND_PREFIX = 'bound ';
1799
+ /** The realm, read by name. */
1800
+ const realmGlobals = globalThis;
1801
+ /**
1802
+ * The prefix under which zone.js keeps the original of a global it patched:
1803
+ * the realm's `__Zone_symbol_prefix` when that is a string, as zone.js reads
1804
+ * it, and `__zone_symbol__` otherwise.
1805
+ */
1806
+ const zoneOriginalPrefix = () => {
1807
+ const prefix = realmGlobals['__Zone_symbol_prefix'];
1808
+ return typeof prefix === 'string' ? prefix : '__zone_symbol__';
1809
+ };
1810
+ /**
1811
+ * Weak, so a function that was once a listed global - a test's fake timer, a
1812
+ * patcher's wrapper - is not kept alive by having been captured.
1813
+ */
1814
+ let dangerousValues;
1815
+ let listedNames;
1816
+ /** The `setTimeout` the set last captured: the sentinel. */
1817
+ let capturedSetTimeout;
1818
+ /**
1819
+ * Adds each call-list name's current global value, and zone.js's saved
1820
+ * original of it where there is one. Adds only: a value captured earlier
1821
+ * stays, so a context that took it before a replacement is still refused.
1822
+ */
1823
+ const addGlobals = (set) => {
1824
+ const zonePrefix = zoneOriginalPrefix();
1825
+ for (const name of DANGEROUS_FUNCTIONS) {
1826
+ for (const value of [realmGlobals[name], realmGlobals[zonePrefix + name]]) {
1827
+ if (typeof value === 'function') {
1828
+ set.add(value);
1829
+ }
1830
+ }
1831
+ }
1832
+ capturedSetTimeout = realmGlobals['setTimeout'];
1833
+ };
1834
+ /**
1835
+ * The identity set, captured at the first check and never at module load: an
1836
+ * eval-core module evaluated before zone.js would otherwise hold the native
1837
+ * timers and miss the wrappers every later context holds.
1838
+ *
1839
+ * Each check compares the last captured `setTimeout` with the current one.
1840
+ * When `setTimeout` has been replaced - zone.js loaded late, or any other
1841
+ * patcher - the current value of every listed global is added. Another listed
1842
+ * global replaced on its own is not seen until `setTimeout` changes.
1843
+ *
1844
+ * Assigned only once it is filled, so a throw part-way through leaves no
1845
+ * half-captured set behind; the next check captures again.
1846
+ */
1847
+ const dangerousValueSet = () => {
1848
+ if (!dangerousValues) {
1849
+ const set = new WeakSet();
1850
+ addGlobals(set);
1851
+ for (const constructor of captureFunctionConstructors().captured.values()) {
1852
+ set.add(constructor);
1853
+ }
1854
+ dangerousValues = set;
1855
+ }
1856
+ else if (realmGlobals['setTimeout'] !== capturedSetTimeout) {
1857
+ addGlobals(dangerousValues);
1858
+ }
1859
+ return dangerousValues;
1860
+ };
1861
+ /**
1862
+ * The names the bound-function rule refuses: the call list, `import`
1863
+ * included, and the three function constructors.
1864
+ */
1865
+ const boundListedNames = () => (listedNames ??= new Set([
1866
+ ...DANGEROUS_FUNCTIONS, 'AsyncFunction', 'GeneratorFunction', 'AsyncGeneratorFunction',
1867
+ ]));
1868
+ /**
1869
+ * Whether `fn` is a bound function whose name, stripped of every `bound `
1870
+ * prefix, is a listed name: `eval.bind(null)` is named `"bound eval"`, and
1871
+ * binding it again gives `"bound bound eval"`. A heuristic: a host's own
1872
+ * function bound under a listed name is refused as well. An unbound function
1873
+ * is never refused by its name here.
1874
+ *
1875
+ * A `name` that cannot be read - a revoked proxy - is not a listed name; the
1876
+ * call sandbox's source test refuses a function it cannot read.
1877
+ */
1878
+ const isBoundListedFunction = (fn) => {
1879
+ let name;
1880
+ try {
1881
+ name = fn.name;
1882
+ }
1883
+ catch {
1884
+ return false;
1885
+ }
1886
+ if (typeof name !== 'string' || !name.startsWith(BOUND_PREFIX)) {
1887
+ return false;
1888
+ }
1889
+ let target = name;
1890
+ while (target.startsWith(BOUND_PREFIX)) {
1891
+ target = target.slice(BOUND_PREFIX.length);
1892
+ }
1893
+ return boundListedNames().has(target);
1894
+ };
1895
+ /**
1896
+ * Whether `value` is a dangerous function: a member of the realm's identity
1897
+ * set, or a bound function of a listed name. Anything that is not a function
1898
+ * is not.
1899
+ */
1900
+ const isDangerousValue = (value) => {
1901
+ if (typeof value !== 'function') {
1902
+ return false;
1903
+ }
1904
+ return dangerousValueSet().has(value) || isBoundListedFunction(value);
1905
+ };
1906
+ /**
1907
+ * The nodes whose own pushed value the funnel leaves to the site that uses
1908
+ * it. Weak, so a cached AST that is dropped takes its marks with it.
1909
+ *
1910
+ * Keyed by node object, so it assumes a tree: no node object in two places.
1911
+ * acorn never shares one, and nothing in this library builds nodes. A
1912
+ * host-built AST that reused one object as both a callee and an argument
1913
+ * would see the argument refused until the callee had been visited once, and
1914
+ * exempt after.
1915
+ */
1916
+ const exemptNodes = new WeakSet();
1917
+ /**
1918
+ * Exempts `node`'s own pushed value from {@link refuseDangerousRead}, and
1919
+ * nothing under it.
1920
+ *
1921
+ * - The call, `new` and tag visitors mark the callee or tag they visit. Its
1922
+ * value is checked by that site's sandbox, with that site's message (K1).
1923
+ * - The unary visitor marks `typeof`'s operand, so `typeof eval` is still
1924
+ * `"function"`.
1925
+ *
1926
+ * Only the node itself: in `(0, eval)("1+1")` the callee is the sequence, so
1927
+ * the identifier `eval` under it is refused when it is pushed. A mark records
1928
+ * the node's place in the AST, which never changes, so it is never cleared.
1929
+ */
1930
+ const exemptFromFunnel = (node) => {
1931
+ exemptNodes.add(node);
1932
+ };
1933
+ /**
1934
+ * The name a refused read reports: the identifier, the member's property name
1935
+ * where the node holds it, or the function's own `name`.
1936
+ */
1937
+ const readName = (node, fn) => {
1938
+ if (node.type === 'Identifier') {
1939
+ return node.name;
1940
+ }
1941
+ if (node.type === 'MemberExpression') {
1942
+ if (!node.computed && node.property.type === 'Identifier') {
1943
+ return node.property.name;
1944
+ }
1945
+ if (node.property.type === 'Literal') {
1946
+ return String(node.property.value);
1947
+ }
1948
+ }
1949
+ return typeof fn.name === 'string' && fn.name ? fn.name : 'anonymous';
1950
+ };
1951
+ /**
1952
+ * The funnel (`docs/a35/plan.md` § 3.3): refuses a dangerous function pushed
1953
+ * by any node but an exempt one, so no visitor - including one not yet
1954
+ * written - can hand it on as an argument, a receiver, an element, a branch
1955
+ * or the expression's result. `pushVisitorResult` calls it for a function
1956
+ * value only.
1957
+ *
1958
+ * It sees only what passes through the walk's own stack. A value that reaches
1959
+ * native code without being pushed is not seen: the elements of an array the
1960
+ * host built, spread into a call, and the route `docs/backlog.md` A39
1961
+ * records, which 0.13.0 closes.
1962
+ *
1963
+ * Up to 0.12.0 nothing refused such a read: `["1+1"].map(eval)` gave `[2]`
1964
+ * (`docs/backlog.md` A35).
1965
+ */
1966
+ const refuseDangerousRead = (node, value) => {
1967
+ if (exemptNodes.has(node) || !isDangerousValue(value)) {
1968
+ return;
1969
+ }
1970
+ throw new Error(`Access to dangerous function "${readName(node, value)}" is blocked for security reasons`);
1971
+ };
1972
+
1973
+ /**
1974
+ * The two push helpers each carry their own trace-bound call rather than
1975
+ * sharing one.
1976
+ *
1977
+ * **Why the read is at these two sites.** `st.maxTraceItems` is the *walk's*
1978
+ * bound. `EvalResult` cannot read it for itself: it holds a context, and a
1979
+ * context's options are not the walk's - the split `CLAUDE.md` documents for
1980
+ * `caseInsensitive`. So the option is read where `st` is in hand and passed in.
1981
+ *
1982
+ * **Why the one line is duplicated rather than factored.** A shared helper put
1983
+ * a third frame on a path taken once per node - `push` -> helper ->
1984
+ * `addTraceBounded` -> `EvalTrace.add` - to save one identical line. Measured
1985
+ * both ways at 50,000 walks of `2 + 3 * a`, the difference was inside
1986
+ * run-to-run noise, so this is not a speed claim; it is that the helper cost a
1987
+ * frame on the hot path and bought nothing, and that `addTraceBounded`'s own
1988
+ * docblock claims one call per push, which only this shape makes true.
1989
+ *
1990
+ * **The value stack is not bounded and must not be.** It is how visitors return
1991
+ * values to each other, and dropping an entry desynchronises every node above
1992
+ * it. Only the trace - which nothing in this library reads - is capped.
1993
+ *
1994
+ * **Every function value pushed here passes the funnel**, `refuseDangerousRead`
1995
+ * (`docs/a35/plan.md` § 3.3): a dangerous function is refused wherever it was
1996
+ * read, unless the node pushing it is a callee, a tag or `typeof`'s operand.
1997
+ * The call is behind `typeof value === 'function'`, so a value that is not a
1998
+ * function pays one comparison and no frame on this per-node path. `await`
1999
+ * pushes its promise here too, which is not a function.
2000
+ * `pushVisitorResultAsync` has no caller, and no check.
2001
+ */
2002
+ const pushVisitorResult = (node, st, value) => {
2003
+ if (typeof value === 'function') {
2004
+ refuseDangerousRead(node, value);
2005
+ }
2006
+ const result = st.result;
2007
+ result.stack.push(value);
2008
+ result.addTraceBounded(node, value, st.maxTraceItems);
2009
+ return value;
2010
+ };
2011
+ const popVisitorResult = (node, st) => {
2012
+ const result = st.result;
2013
+ const value = result.stack.pop();
2014
+ return value;
2015
+ };
2016
+ const pushVisitorResultAsync = (node, st, value) => {
2017
+ const result = st.result;
2018
+ result.stack.push(value);
2019
+ result.addTraceBounded(node, value, st.maxTraceItems);
2020
+ return value;
2021
+ };
2022
+ const popVisitorResultAsync = (node, st) => {
2023
+ const result = st.result;
2024
+ const value = result.stack.pop();
2025
+ return value;
2026
+ };
2027
+
2028
+ const literals = Registry.fromObject({
2029
+ 'undefined': undefined,
2030
+ 'null': null,
2031
+ 'true': true,
2032
+ 'false': false,
2033
+ }, { caseInsensitive: true });
2034
+ /**
2035
+ * Reports a resolved identifier read to the hook layer.
2036
+ *
2037
+ * The key is the one the context actually matched, so a case-insensitive
2038
+ * lookup reports the corrected spelling; `getKey` returns undefined for a name
2039
+ * the context does not hold - a literal-registry resolution, or a miss - and
2040
+ * the source name stands in. The path is always the source spelling, since it
2041
+ * is reconstructed statically.
2042
+ *
2043
+ * `scoped` marks a read of a name bound by any scope on the context's scope
2044
+ * stack when the name is read, whoever pushed it: an arrow-function
2045
+ * parameter, a declaration in the lexical scope `program.ts`,
2046
+ * `block-statement.ts` or `for-statement.ts` pushes, or a binding the caller
2047
+ * pushed with `EvalContext.push` before the walk - which is how `eval-signals`
2048
+ * binds a run's `AbortSignal` under `abortSignalKey`, and why that key never
2049
+ * reaches its `dependencies`. It is asked of `EvalContext.hasInScopes`, which
2050
+ * tests for the binding rather than for its value: a parameter bound to
2051
+ * `undefined` is still a parameter, and reading the flag off the resolved value
2052
+ * would make it vary with the data rather than with the expression.
2053
+ *
2054
+ * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
2055
+ * long-lived objects and are real dependencies, so the discriminator is
2056
+ * lifetime rather than `instanceof EvalScope`. The property is omitted rather
2057
+ * than set to false, so absent reads as "not scoped" the same way it does at
2058
+ * the member emission sites.
2059
+ *
2060
+ * The scope stack is empty only for a walk that does not start at a `Program`
2061
+ * and has nothing pushed by its caller: `program.ts` pushes a scope at the root
2062
+ * of every walk through `EvalService`. `Stack.asArray` allocates, so that empty
2063
+ * case is short-circuited on length.
2064
+ */
2065
+ const emitRead = (node, st, value) => {
2066
+ const key = st.context?.getKey(node.name) ?? node.name;
2067
+ const scoped = !!st.context
2068
+ && st.context.scopes.length > 0
2069
+ && st.context.hasInScopes(node.name);
2070
+ st.hooks.dispatchRead({
2071
+ kind: 'identifier',
2072
+ node,
2073
+ state: st,
2074
+ key,
2075
+ target: st.context,
2076
+ path: node.name,
2077
+ value,
2078
+ ...(scoped ? { scoped: true } : {})
2079
+ });
2080
+ };
2081
+ /**
2082
+ * Refuses an identifier whose name is on the prototype-pollution blocklist,
2083
+ * before any lookup, with the member visitor's error.
2084
+ *
2085
+ * An identifier is resolved against the context, and `EvalContext.get` reads a
2086
+ * plain object there - the original, or a scope - with a bare property access.
2087
+ * So up to 0.10.x a name on the blocklist resolved to what the context inherits
2088
+ * from `Object.prototype` (`docs/backlog-retired.md` B6): the blocklist guarded
2089
+ * member access to the objects an expression holds, and the context is not one
2090
+ * of them. Every kind of context is refused alike, including those - a
2091
+ * `Registry`, a signal context's source - that hold such a name only as a key
2092
+ * of their own.
2093
+ */
2094
+ const refuseDangerousName = (node) => {
2095
+ if (isDangerousProperty(node.name)) {
2096
+ throw new Error(`Access to dangerous property "${node.name}" is blocked for security reasons`);
2097
+ }
2098
+ };
2099
+ /**
2100
+ * Under `caseInsensitive`, refuses an identifier whose lookup matched a key on
2101
+ * the blocklist - `CONSTRUCTOR` over a context holding `constructor` - as the
2102
+ * member visitor re-checks `foundKey` for another object.
2103
+ *
2104
+ * The matched key is asked of `getKey`, which answers the key `get` resolves,
2105
+ * and only for a name `mayMatchDangerousProperty` lets through. Any other name
2106
+ * cannot match a blocklisted key, and an identifier must not pay a second
2107
+ * resolution for nothing: the performance spec's read-emission guard asserts
2108
+ * that, with no read hook, `getKey` is not called per identifier.
2109
+ */
2110
+ const refuseDangerousMatch = (node, st) => {
2111
+ if (!st.context || !mayMatchDangerousProperty(node.name)) {
2112
+ return;
2113
+ }
2114
+ const matched = st.context.getKey(node.name);
2115
+ if (isDangerousProperty(matched)) {
2116
+ throw new Error(`Access to dangerous property "${String(matched)}" is blocked for security reasons`);
2117
+ }
2118
+ };
2119
+ const identifierVisitor = (node, st) => {
2120
+ if (st.options?.caseInsensitive) {
2121
+ return identifierVisitorCaseInsensitive(node, st);
2122
+ }
2123
+ beforeVisitor(node, st);
2124
+ refuseDangerousName(node);
2125
+ const context = st.context;
2126
+ const isThis = node.name === 'this';
2127
+ const value = isThis
2128
+ ? st.context
2129
+ : context?.get(node.name);
2130
+ // `this` resolves to the context object itself rather than to a key within
2131
+ // it, so it is not a read: reporting it would have a dependency tracker
2132
+ // record the whole context and re-fire on every change to it.
2133
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2134
+ emitRead(node, st, value);
2135
+ }
2136
+ pushVisitorResult(node, st, value);
2137
+ afterVisitor(node, st);
2138
+ };
2139
+ const identifierVisitorCaseInsensitive = (node, st) => {
2140
+ beforeVisitor(node, st);
2141
+ refuseDangerousName(node);
2142
+ const context = st.context;
2143
+ const isThis = !!equalIgnoreCase(node.name, 'this');
2144
+ if (!isThis) {
2145
+ refuseDangerousMatch(node, st);
2146
+ }
2147
+ const value = isThis
2148
+ ? st.context
2149
+ : context?.get(node.name) ?? literals.get(node.name);
2150
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2151
+ emitRead(node, st, value);
2152
+ }
2153
+ pushVisitorResult(node, st, value);
2154
+ afterVisitor(node, st);
2155
+ };
2156
+
2157
+ const literalVisitor = (node, st) => {
2158
+ beforeVisitor(node, st);
2159
+ // A regex literal is a new `RegExp` on every evaluation, as it is in
2160
+ // JavaScript. Acorn builds `node.value` once, at parse time, and every walk of
2161
+ // the parsed tree used to push that one object - a cached `simpleEval` string
2162
+ // and each recompute of a compiled expression alike - so `lastIndex` carried
2163
+ // from one evaluation into the next, and `/a/g.test("a")` answered true, then
2164
+ // false. A copy starts at `lastIndex` 0, and being new it is recorded under a
2165
+ // member-write policy, as a literal is - `EvalContext.checkMemberWrite`. When
2166
+ // acorn could not build the regex in this environment, `value` is null and is
2167
+ // pushed as before.
2168
+ let value = node.value;
2169
+ if (value instanceof RegExp) {
2170
+ value = new RegExp(value);
2171
+ st.createdObjects?.add(value);
2172
+ }
2173
+ pushVisitorResult(node, st, value);
2174
+ afterVisitor(node, st);
2175
+ };
2176
+
2177
+ // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
2178
+ /**
2179
+ * Converts value to primitive for comparison operations
2180
+ */
2181
+ const toPrimitive = (value, hint) => {
2182
+ if (value === null || value === undefined)
2183
+ return value;
2184
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||
2185
+ typeof value === 'symbol' || typeof value === 'bigint')
2186
+ return value;
2187
+ // For objects, call valueOf/toString based on hint
2188
+ if (typeof value === 'object') {
2189
+ if (hint === 'number') {
2190
+ const valueOf = value.valueOf;
2191
+ if (typeof valueOf === 'function') {
2192
+ const result = valueOf.call(value);
2193
+ if (typeof result !== 'object')
2194
+ return result;
2195
+ }
2196
+ const toString = value.toString;
2197
+ if (typeof toString === 'function') {
2198
+ return toString.call(value);
2199
+ }
2200
+ }
2201
+ else {
2202
+ const toString = value.toString;
2203
+ if (typeof toString === 'function') {
2204
+ const result = toString.call(value);
2205
+ if (typeof result === 'string')
2206
+ return result;
2207
+ }
2208
+ const valueOf = value.valueOf;
2209
+ if (typeof valueOf === 'function') {
2210
+ const result = valueOf.call(value);
2211
+ if (typeof result !== 'object')
2212
+ return result;
2213
+ }
2214
+ }
2215
+ }
2216
+ return String(value);
2217
+ };
2218
+ /**
2219
+ * Safely evaluates binary operations with proper type coercion
2220
+ */
2221
+ const evaluateBinaryOperation = (operator, left, right) => {
2222
+ switch (operator) {
2223
+ case '+': {
2224
+ // Handle string concatenation and numeric addition according to JavaScript rules
2225
+ const leftPrim = toPrimitive(left);
2226
+ const rightPrim = toPrimitive(right);
2227
+ if (typeof leftPrim === 'string' || typeof rightPrim === 'string') {
2228
+ return String(leftPrim) + String(rightPrim);
2229
+ }
2230
+ return Number(leftPrim) + Number(rightPrim);
2231
+ }
2232
+ case '-':
2233
+ return Number(toPrimitive(left, 'number')) - Number(toPrimitive(right, 'number'));
2234
+ case '*':
2235
+ return Number(toPrimitive(left, 'number')) * Number(toPrimitive(right, 'number'));
2236
+ case '/':
2237
+ return Number(toPrimitive(left, 'number')) / Number(toPrimitive(right, 'number'));
2238
+ case '%':
2239
+ return Number(toPrimitive(left, 'number')) % Number(toPrimitive(right, 'number'));
2240
+ case '**':
2241
+ return Number(toPrimitive(left, 'number')) ** Number(toPrimitive(right, 'number'));
2242
+ // Bitwise operations - convert to 32-bit integers
2243
+ case '<<':
2244
+ return (Number(toPrimitive(left, 'number')) | 0) << (Number(toPrimitive(right, 'number')) | 0);
2245
+ case '>>':
2246
+ return (Number(toPrimitive(left, 'number')) | 0) >> (Number(toPrimitive(right, 'number')) | 0);
2247
+ case '>>>':
2248
+ return (Number(toPrimitive(left, 'number')) >>> 0) >>> (Number(toPrimitive(right, 'number')) | 0);
2249
+ case '&':
2250
+ return (Number(toPrimitive(left, 'number')) | 0) & (Number(toPrimitive(right, 'number')) | 0);
2251
+ case '^':
2252
+ return (Number(toPrimitive(left, 'number')) | 0) ^ (Number(toPrimitive(right, 'number')) | 0);
2253
+ case '|':
2254
+ return (Number(toPrimitive(left, 'number')) | 0) | (Number(toPrimitive(right, 'number')) | 0);
2255
+ // Comparison operations - follow JavaScript's abstract comparison rules
2256
+ case '==':
2257
+ return left == right;
2258
+ case '!=':
2259
+ return left != right;
2260
+ case '===':
2261
+ return left === right;
2262
+ case '!==':
2263
+ return left !== right;
2264
+ case '<': {
2265
+ const leftComp = toPrimitive(left, 'number');
2266
+ const rightComp = toPrimitive(right, 'number');
2267
+ // If both are strings, do string comparison
2268
+ if (typeof leftComp === 'string' && typeof rightComp === 'string') {
2269
+ return leftComp < rightComp;
2270
+ }
2271
+ return Number(leftComp) < Number(rightComp);
2272
+ }
2273
+ case '<=': {
2274
+ const leftLE = toPrimitive(left, 'number');
2275
+ const rightLE = toPrimitive(right, 'number');
2276
+ if (typeof leftLE === 'string' && typeof rightLE === 'string') {
2277
+ return leftLE <= rightLE;
2278
+ }
2279
+ return Number(leftLE) <= Number(rightLE);
2280
+ }
2281
+ case '>': {
2282
+ const leftGT = toPrimitive(left, 'number');
2283
+ const rightGT = toPrimitive(right, 'number');
2284
+ if (typeof leftGT === 'string' && typeof rightGT === 'string') {
2285
+ return leftGT > rightGT;
2286
+ }
2287
+ return Number(leftGT) > Number(rightGT);
2288
+ }
2289
+ case '>=': {
2290
+ const leftGE = toPrimitive(left, 'number');
2291
+ const rightGE = toPrimitive(right, 'number');
2292
+ if (typeof leftGE === 'string' && typeof rightGE === 'string') {
2293
+ return leftGE >= rightGE;
2294
+ }
2295
+ return Number(leftGE) >= Number(rightGE);
2296
+ }
2297
+ // Special operations
2298
+ case 'in': {
2299
+ if (typeof left === 'string' || typeof left === 'number' || typeof left === 'symbol') {
2300
+ if (right == null) {
2301
+ throw new Error(`Cannot use 'in' operator with null or undefined right operand`);
2302
+ }
2303
+ return left in right;
2304
+ }
2305
+ throw new Error(`Invalid left operand for 'in' operator: ${typeof left}`);
2306
+ }
2307
+ case 'instanceof': {
2308
+ if (typeof right === 'function') {
2309
+ return left instanceof right;
2310
+ }
2311
+ throw new Error(`Right operand of 'instanceof' is not a constructor`);
2023
2312
  }
2313
+ case '??':
2314
+ return left ?? right;
2315
+ default:
2316
+ throw new Error(`Unsupported binary operator: ${operator}`);
2024
2317
  }
2025
- return object;
2026
2318
  };
2027
2319
  /**
2028
- * Enhanced call expression visitor with security checks
2029
- *
2030
- * A context with a member-write policy is asked, before the call, about a
2031
- * built-in that writes into its receiver or its first argument - see
2032
- * `consultMethodWrite`. The receiver asked about is the one the call is made
2033
- * with: the member's object, a prior scope's `thisArg`, or the context itself
2034
- * for a bare call. A context without a policy pays one field read per call.
2320
+ * Safely evaluates binary expressions with proper type handling
2035
2321
  */
2036
- const callExpressionVisitor = (node, st, callback) => {
2322
+ const binaryExpressionVisitor = (node, st, callback) => {
2037
2323
  beforeVisitor(node, st);
2038
- const args = evaluateArray(node, node.arguments, st, callback);
2039
- if (node.callee.type === 'MemberExpression') {
2040
- const [object, propertyName, fn] = evaluateMember(node.callee, st, callback);
2041
- const functionName = typeof propertyName === 'string' ? propertyName : undefined;
2042
- const receiver = scopeReceiver(st, object);
2043
- const created = st.createdObjects;
2044
- if (created) {
2045
- consultMethodWrite(st, created, fn, receiver, args);
2046
- }
2047
- const value = safeCall(fn, receiver, args, node.callee.optional, functionName);
2048
- pushVisitorResult(node, st, value);
2049
- }
2050
- else {
2051
- callback(node.callee, st);
2052
- const caller = popVisitorResult(node, st);
2053
- // Try to get function name for security checks
2054
- let functionName;
2055
- if (node.callee.type === 'Identifier') {
2056
- functionName = node.callee.name;
2057
- }
2058
- const created = st.createdObjects;
2059
- if (created) {
2060
- consultMethodWrite(st, created, caller, st.context, args);
2061
- }
2062
- const value = safeCall(caller, st.context, args, node.optional, functionName);
2063
- pushVisitorResult(node, st, value);
2064
- }
2324
+ // Disable visitor result caching for now due to context sensitivity issues
2325
+ // const cachedResult = getCachedVisitorResult(node, st.context);
2326
+ // if (cachedResult !== undefined) {
2327
+ // pushVisitorResult(node, st, cachedResult);
2328
+ // afterVisitor(node, st);
2329
+ // return;
2330
+ // }
2331
+ callback(node.left, st);
2332
+ const left = popVisitorResult(node, st);
2333
+ callback(node.right, st);
2334
+ const right = popVisitorResult(node, st);
2335
+ const value = evaluateBinaryOperation(node.operator, left, right);
2336
+ // Disable visitor result caching for now
2337
+ // setCachedVisitorResult(node, st.context, value);
2338
+ pushVisitorResult(node, st, value);
2065
2339
  afterVisitor(node, st);
2066
2340
  };
2067
- const evaluateCall = (node, st, callback) => {
2068
- callback(node.callee, st);
2069
- const caller = popVisitorResult(node, st);
2070
- const args = node.arguments.map((argument) => {
2071
- callback(argument, st);
2072
- const value = popVisitorResult(node, st);
2073
- return value;
2074
- });
2075
- // Get function name for security checks
2076
- let functionName;
2077
- if (node.callee.type === 'Identifier') {
2078
- functionName = node.callee.name;
2079
- }
2080
- const value = safeCall(caller, st.context, args, false, functionName);
2081
- return value;
2082
- };
2083
2341
 
2084
2342
  /**
2085
2343
  * ImportExpression visitor - blocks all dynamic imports for security
@@ -2165,6 +2423,11 @@ const conditionalExpressionVisitor = (node, st, callback) => {
2165
2423
 
2166
2424
  const unaryExpressionVisitor = (node, st, callback) => {
2167
2425
  beforeVisitor(node, st);
2426
+ // `typeof eval` reads a dangerous function to name its type, and hands it
2427
+ // on to nothing, so its operand is exempt from the funnel.
2428
+ if (node.operator === 'typeof') {
2429
+ exemptFromFunnel(node.argument);
2430
+ }
2168
2431
  callback(node.argument, st);
2169
2432
  const argument = popVisitorResult(node, st);
2170
2433
  const value = node.operator === '-' ? -argument :
@@ -2263,6 +2526,12 @@ const isConstructorSafe = (constructor, constructorName) => {
2263
2526
  constructor === (async function* () { }).constructor) {
2264
2527
  return false;
2265
2528
  }
2529
+ // A dangerous function by value, under whatever name it was reached
2530
+ // (`dangerous-values.ts`). Up to 0.12.0 only a bare identifier's name was
2531
+ // checked (`docs/backlog.md` A35).
2532
+ if (isDangerousValue(constructor)) {
2533
+ return false;
2534
+ }
2266
2535
  try {
2267
2536
  // Check constructor string for dangerous patterns
2268
2537
  const constructorString = constructor.toString();
@@ -2300,6 +2569,9 @@ const safeNew = (constructor, args, constructorName) => {
2300
2569
  const newExpressionVisitor = (node, st, callback) => {
2301
2570
  beforeVisitor(node, st);
2302
2571
  const args = evaluateArray(node, node.arguments, st, callback);
2572
+ // The callee's own value is checked by `safeNew`, with the constructor's
2573
+ // message; what is read under it still passes the funnel.
2574
+ exemptFromFunnel(node.callee);
2303
2575
  callback(node.callee, st);
2304
2576
  const constructor = popVisitorResult(node, st);
2305
2577
  // Try to get constructor name for security checks
@@ -2334,20 +2606,60 @@ const templateLiteralVisitor = (node, st, callback) => {
2334
2606
  afterVisitor(node, st);
2335
2607
  };
2336
2608
 
2337
- const taggedTemplateExpressionVisitor = (node, st, callback) => {
2338
- beforeVisitor(node, st);
2339
- callback(node.tag, st);
2340
- const tag = popVisitorResult(node, st);
2341
- const quasiExpressions = node.quasi.expressions.map((expression) => {
2609
+ /**
2610
+ * The tag's arguments: the template's cooked strings, then the value of each
2611
+ * of its expressions, evaluated in order.
2612
+ */
2613
+ const templateArguments = (node, st, callback) => {
2614
+ const values = node.quasi.expressions.map((expression) => {
2342
2615
  callback(expression, st);
2343
- const value = popVisitorResult(node, st);
2344
- return value;
2345
- });
2346
- const quasi = node.quasi.quasis.map((templateElement) => {
2347
- return templateElement.value.cooked;
2616
+ return popVisitorResult(node, st);
2348
2617
  });
2349
- const value = tag.apply(st.context, [quasi, ...quasiExpressions]);
2350
- pushVisitorResult(node, st, value);
2618
+ const strings = node.quasi.quasis.map((templateElement) => templateElement.value.cooked);
2619
+ return [strings, ...values];
2620
+ };
2621
+ /**
2622
+ * Calls the tag as a call calls its callee (`call-expression.ts`): past the
2623
+ * context's write policy, then through the call sandbox.
2624
+ *
2625
+ * - A member tag goes through `callMember`, as a member call does: `obj.m`
2626
+ * is called with `obj` as `this` - or a prior scope's `thisArg` - and checked
2627
+ * under the property name, a computed key included. Its own
2628
+ * `MemberExpression` is evaluated by `evaluateMember`, not visited, so it
2629
+ * raises no `before` or `after` node-hook events and leaves no trace entry,
2630
+ * as a member callee does. Its read event still fires.
2631
+ * - Any other tag is called with the context as `this`, as a bare call is,
2632
+ * and checked under its identifier's name, or none.
2633
+ *
2634
+ * The tag is evaluated before the template's expressions, as in JavaScript;
2635
+ * a call evaluates its arguments first.
2636
+ *
2637
+ * Up to 0.12.0 the tag was applied directly, with the context as `this` and no
2638
+ * check at all, so `` Function`return 7`() `` ran (`docs/backlog-retired.md`
2639
+ * A36).
2640
+ */
2641
+ const taggedTemplateExpressionVisitor = (node, st, callback) => {
2642
+ beforeVisitor(node, st);
2643
+ if (node.tag.type === 'MemberExpression') {
2644
+ const member = evaluateMember(node.tag, st, callback);
2645
+ const args = templateArguments(node, st, callback);
2646
+ const value = callMember(st, member, args, false);
2647
+ pushVisitorResult(node, st, value);
2648
+ }
2649
+ else {
2650
+ // As a call's callee: the tag's own value is checked by `safeCall`.
2651
+ exemptFromFunnel(node.tag);
2652
+ callback(node.tag, st);
2653
+ const tag = popVisitorResult(node, st);
2654
+ const args = templateArguments(node, st, callback);
2655
+ const tagName = node.tag.type === 'Identifier' ? node.tag.name : undefined;
2656
+ const created = st.createdObjects;
2657
+ if (created) {
2658
+ consultMethodWrite(st, created, tag, st.context, args);
2659
+ }
2660
+ const value = safeCall(tag, st.context, args, false, tagName);
2661
+ pushVisitorResult(node, st, value);
2662
+ }
2351
2663
  afterVisitor(node, st);
2352
2664
  };
2353
2665
 
@@ -2447,6 +2759,7 @@ const getDefaultVisitors = () => {
2447
2759
  visitors['AssignmentExpression'] = assignmentExpressionVisitor;
2448
2760
  visitors['UpdateExpression'] = updateExpressionVisitor;
2449
2761
  visitors['ArrowFunctionExpression'] = arrowFunctionExpressionVisitor;
2762
+ visitors['SequenceExpression'] = sequenceExpressionVisitor;
2450
2763
  // The statement family. `Program` is the root of every walk that arrives
2451
2764
  // through `EvalService`, whose parser options leave `extractExpressions` off.
2452
2765
  visitors['Program'] = programVisitor;
@@ -3006,16 +3319,211 @@ const updateExpressionVisitor = (node, st, callback) => {
3006
3319
  afterVisitor(node, st);
3007
3320
  };
3008
3321
 
3322
+ /**
3323
+ * @description
3324
+ * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
3325
+ * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
3326
+ * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
3327
+ * is rewritten, so every position acorn reports is a position in what the
3328
+ * author wrote. Not re-exported from any barrel.
3329
+ *
3330
+ * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
3331
+ * the `input` member. Everything else it touches is an acorn internal,
3332
+ * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
3333
+ * checks at the `acorn` peer floor:
3334
+ *
3335
+ * - members read: `pos`, `start`, `type`, `value`, `keywords`;
3336
+ * - members written: `pos`, `containsEsc`;
3337
+ * - methods overridden, each calling acorn's own through `super`: `readWord`,
3338
+ * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
3339
+ * - methods called: `finishToken`, `raise`;
3340
+ * - what the overrides assume of acorn's tokenizer: `readToken` is the only
3341
+ * caller of `readWord`, with `pos` at the token's first character; every
3342
+ * token is finished through `finishToken`, in source order, before the next
3343
+ * is read — except that a `/` read as `slash` is finished again as
3344
+ * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
3345
+ * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
3346
+ * constructor reads no token;
3347
+ * - what they assume of acorn's parser: every key of an object literal, an
3348
+ * object pattern or a class body is read through `parsePropertyName`, with
3349
+ * the key as the current token; every statement through `parseStatement`,
3350
+ * with its first token as the current token; a colon the grammar cannot
3351
+ * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
3352
+ * `start` still at that colon.
3353
+ *
3354
+ * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
3355
+ * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
3356
+ * `braceL`, `braceR`, `dollarBraceL`.
3357
+ */
3358
+ const COLON = 58;
3359
+ /** `[A-Za-z_$]`: the first character of a name that may join. */
3360
+ const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
3361
+ /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
3362
+ const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
3363
+ /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
3364
+ const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
3365
+ const colonIdentifiers = (Base) => {
3366
+ class ColonParser extends Base {
3367
+ constructor() {
3368
+ super(...arguments);
3369
+ /** Never empty: the top level is never closed. */
3370
+ this.levels = [{ pending: 0 }];
3371
+ /**
3372
+ * The level the current token was read at: for a `(`, `[`, `{` or `${`,
3373
+ * the one around the level it opened.
3374
+ */
3375
+ this.tokenLevel = this.levels[0];
3376
+ }
3377
+ get level() {
3378
+ return this.levels[this.levels.length - 1];
3379
+ }
3380
+ /**
3381
+ * Reads a colon-joined name as one `name` token when one starts at `pos`
3382
+ * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
3383
+ * other case acorn's own `readWord`, so a word that does not join is read
3384
+ * exactly as acorn reads it.
3385
+ */
3386
+ readWord() {
3387
+ const end = this.colonNameEnd();
3388
+ if (end === undefined) {
3389
+ return super.readWord();
3390
+ }
3391
+ const name = this.input.slice(this.pos, end);
3392
+ if (this.level.pending > 0) {
3393
+ this.level.suppressed = name;
3394
+ return super.readWord();
3395
+ }
3396
+ this.pos = end;
3397
+ this.containsEsc = false;
3398
+ this.finishToken(tokTypes.name, name);
3399
+ }
3400
+ /**
3401
+ * Where the colon name that starts at `pos` ends — its longest match — or
3402
+ * `undefined` when none does: the first segment is not ASCII, is a keyword
3403
+ * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
3404
+ */
3405
+ colonNameEnd() {
3406
+ const input = this.input;
3407
+ let end = this.pos;
3408
+ if (!isFirstChar(input.charCodeAt(end))) {
3409
+ return undefined;
3410
+ }
3411
+ do {
3412
+ end++;
3413
+ } while (isSegmentChar(input.charCodeAt(end)));
3414
+ if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
3415
+ return undefined;
3416
+ }
3417
+ do {
3418
+ end += 2;
3419
+ while (isSegmentChar(input.charCodeAt(end))) {
3420
+ end++;
3421
+ }
3422
+ } while (joinsAt(input, end));
3423
+ return end;
3424
+ }
3425
+ /**
3426
+ * Keeps the levels after acorn has finished the token, recording the one
3427
+ * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
3428
+ * and `}` close it; a `?` is counted at its level and a `:` there
3429
+ * uncounts it. `?.` and `??` are other token types, and count for nothing.
3430
+ */
3431
+ finishToken(type, value) {
3432
+ super.finishToken(type, value);
3433
+ const level = this.level;
3434
+ this.tokenLevel = level;
3435
+ switch (type) {
3436
+ case tokTypes.parenL:
3437
+ case tokTypes.bracketL:
3438
+ case tokTypes.braceL:
3439
+ case tokTypes.dollarBraceL:
3440
+ this.levels.push({ pending: 0 });
3441
+ break;
3442
+ case tokTypes.parenR:
3443
+ case tokTypes.bracketR:
3444
+ case tokTypes.braceR:
3445
+ if (this.levels.length > 1) {
3446
+ this.levels.pop();
3447
+ }
3448
+ break;
3449
+ case tokTypes.question:
3450
+ level.pending++;
3451
+ break;
3452
+ case tokTypes.colon:
3453
+ if (level.pending > 0) {
3454
+ level.pending--;
3455
+ }
3456
+ break;
3457
+ case tokTypes.comma:
3458
+ case tokTypes.semi:
3459
+ level.suppressed = undefined;
3460
+ break;
3461
+ }
3462
+ }
3463
+ /**
3464
+ * Refuses a colon name as an object key, in a literal or a pattern alike
3465
+ * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
3466
+ * grammar, and keeping either would answer some author wrongly. Only a
3467
+ * joined token is a `name` holding a colon.
3468
+ */
3469
+ parsePropertyName(prop) {
3470
+ const name = this.value;
3471
+ if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
3472
+ const first = name.slice(0, name.indexOf(':'));
3473
+ this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
3474
+ `write '${first}: ...' with a space for a property, or quote the key`);
3475
+ }
3476
+ return super.parsePropertyName(prop);
3477
+ }
3478
+ /**
3479
+ * Forgets the name not joined at the level a statement starts at: the
3480
+ * statement boundary ended the conditional whose consequent lost it. A
3481
+ * semicolon acorn inserts at a line break is such a boundary, and no `;`
3482
+ * token marks it.
3483
+ */
3484
+ parseStatement(...args) {
3485
+ this.tokenLevel.suppressed = undefined;
3486
+ return super.parseStatement(...args);
3487
+ }
3488
+ /**
3489
+ * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
3490
+ * is a `:` at a level that did not join a name since its last `,`, `;` or
3491
+ * statement start: the colon the name lost to the conditional. Any other
3492
+ * error is left as acorn words it.
3493
+ */
3494
+ unexpected(pos) {
3495
+ const suppressed = this.tokenLevel.suppressed;
3496
+ if (suppressed !== undefined && this.type === tokTypes.colon &&
3497
+ (pos === undefined || pos === this.start)) {
3498
+ return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
3499
+ `consequent of a conditional needs parentheses: (${suppressed})`);
3500
+ }
3501
+ return super.unexpected(pos);
3502
+ }
3503
+ }
3504
+ return ColonParser;
3505
+ };
3506
+ /**
3507
+ * acorn's `Parser` with the grammar, built once, at module load. `extend`
3508
+ * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
3509
+ * left as it was.
3510
+ */
3511
+ const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
3512
+
3009
3513
  /**
3010
3514
  * @description
3011
3515
  * Parses expression and returns ES6/ES2020 AST.
3516
+ * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
3517
+ * otherwise it is acorn's own `parse`.
3012
3518
  * @param expr expression to parse
3013
3519
  * @param options parser options
3014
3520
  */
3015
3521
  const parse = (expr, options) => {
3016
3522
  options = { ecmaVersion: 2020, ...options };
3017
3523
  const acornOptions = { ecmaVersion: 2020, ...options };
3018
- const program = parse$1(expr, acornOptions);
3524
+ const program = options.colonIdentifiers
3525
+ ? ColonIdentifiersParser.parse(expr, acornOptions)
3526
+ : parse$1(expr, acornOptions);
3019
3527
  if (!options.extractExpressions) {
3020
3528
  return program;
3021
3529
  }
@@ -3738,6 +4246,27 @@ const forStatementVisitor = (node, st, callback) => {
3738
4246
  afterVisitor(node, st);
3739
4247
  };
3740
4248
 
4249
+ /**
4250
+ * Evaluates a sequence, `(a, b, c)`: each expression in order, the value the
4251
+ * last one's.
4252
+ *
4253
+ * Registered rather than left to `acorn-walk`'s base walker, which walked the
4254
+ * expressions and popped none of them, so every value but the last stayed on
4255
+ * the stack: `(0, 1)` left one entry and `((1, 2), 3)` two, a reused state
4256
+ * accumulated them, and no hook saw the node (`docs/backlog-retired.md` A37).
4257
+ * Each value is popped as it arrives, so the visitor leaves exactly one.
4258
+ */
4259
+ const sequenceExpressionVisitor = (node, st, callback) => {
4260
+ beforeVisitor(node, st);
4261
+ let value;
4262
+ for (const expression of node.expressions) {
4263
+ callback(expression, st);
4264
+ value = popVisitorResult(node, st);
4265
+ }
4266
+ pushVisitorResult(node, st, value);
4267
+ afterVisitor(node, st);
4268
+ };
4269
+
3741
4270
  const defaultEvalScopeOptions = {
3742
4271
  global: false,
3743
4272
  caseInsensitive: false,
@@ -5682,6 +6211,148 @@ class BaseEval {
5682
6211
  }
5683
6212
  }
5684
6213
 
6214
+ /**
6215
+ * The options a cached AST cannot honour: acorn calls each callback as it
6216
+ * parses, and appends to a caller's `program` node. A parse carrying any of
6217
+ * them with a value acorn acts on bypasses the cache, reading and writing
6218
+ * (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The test is on the value,
6219
+ * never the key: `defaultParserOptions`, which every service passes, carries
6220
+ * all five as `null`.
6221
+ */
6222
+ const UNCACHEABLE_OPTIONS = [
6223
+ 'onToken', 'onComment', 'onInsertedSemicolon', 'onTrailingComma', 'program'
6224
+ ];
6225
+ /**
6226
+ * Left out of the fingerprint: the five above, and `cacheSize`, which sizes
6227
+ * the cache and changes no parse.
6228
+ */
6229
+ const UNKEYED_OPTIONS = new Set([...UNCACHEABLE_OPTIONS, 'cacheSize']);
6230
+ /** Stands for a call that passes no options object of its own. */
6231
+ const NO_CALL_OPTIONS = Object.freeze({});
6232
+ /**
6233
+ * Builds the fingerprint of a parse with the given options — the service's and
6234
+ * the call's, merged as `ParserService.parse` merges them — or `null` when the
6235
+ * parse must bypass the cache.
6236
+ *
6237
+ * Every other option is in it under its own name, so an option this file does
6238
+ * not list keys the cache with no change here. Sorted `[key, value]` pairs as
6239
+ * JSON: canonical, so equal options give one fingerprint whatever their key
6240
+ * order or identity. A key whose value is `undefined` is written `[key]`
6241
+ * rather than dropped, since acorn reads it differently from a missing key:
6242
+ * `checkPrivateFields` defaults to `true`. A value JSON cannot hold, a cycle
6243
+ * or a `BigInt`, gives no fingerprint, so that parse bypasses the cache rather
6244
+ * than throw where it used to succeed.
6245
+ */
6246
+ const buildParseFingerprint = (options) => {
6247
+ for (const key of UNCACHEABLE_OPTIONS) {
6248
+ if (options[key]) {
6249
+ return null;
6250
+ }
6251
+ }
6252
+ const values = options;
6253
+ const pairs = Object.keys(values)
6254
+ .filter(key => !UNKEYED_OPTIONS.has(key))
6255
+ .sort()
6256
+ .map(key => values[key] === undefined ? [key] : [key, values[key]]);
6257
+ try {
6258
+ return JSON.stringify(pairs);
6259
+ }
6260
+ catch {
6261
+ return null;
6262
+ }
6263
+ };
6264
+ /**
6265
+ * Returns the cache namespace for a parse with the service's options and the
6266
+ * call's — the sha256 of their fingerprint, in hex — or `null` when the parse
6267
+ * must bypass the cache. Built once per pair of objects and remembered by
6268
+ * identity in the service's `memo`, so `EvalService`, which passes the same
6269
+ * `defaultParserOptions` on every call, pays two lookups per parse rather than
6270
+ * a serialization and a digest. The digest keeps `getHashKey`'s input short:
6271
+ * it joins the namespace and the text with `:`, and 64 hex characters, none a
6272
+ * colon, cannot make two (options, text) pairs one key when the text holds
6273
+ * colons.
6274
+ *
6275
+ * Remembered by identity, it does not see an object changed in place: the
6276
+ * object the `parserOptions` getter returns, an options object a caller passes
6277
+ * again after writing into it, or the exported `defaultParserOptions`. A change
6278
+ * through the `parserOptions` setter installs a new object, and is seen
6279
+ * (`docs/backlog.md` A34).
6280
+ */
6281
+ const parseFingerprint = (memo, serviceOptions, callOptions) => {
6282
+ let byCall = memo.get(serviceOptions);
6283
+ if (!byCall) {
6284
+ byCall = new WeakMap();
6285
+ memo.set(serviceOptions, byCall);
6286
+ }
6287
+ // A JavaScript caller can pass something other than an object, such as the
6288
+ // `false` of `condition && options`. It cannot be a `WeakMap` key, and acorn
6289
+ // reads none of its options from it, so it is fingerprinted as none.
6290
+ const call = typeof callOptions === 'object' && callOptions !== null
6291
+ ? callOptions : undefined;
6292
+ const callKey = call ?? NO_CALL_OPTIONS;
6293
+ let digest = byCall.get(callKey);
6294
+ if (digest === undefined) {
6295
+ const fingerprint = buildParseFingerprint({ ...serviceOptions, ...call });
6296
+ digest = fingerprint === null ? null : sha256(fingerprint);
6297
+ byCall.set(callKey, digest);
6298
+ }
6299
+ return digest;
6300
+ };
6301
+
6302
+ /**
6303
+ * Set by {@link provideColonIdentifiers}, and by nothing else. Exported from no
6304
+ * barrel: the provider is the only way to set it, and
6305
+ * `inject(ParserService).parserOptions` the published way to read the
6306
+ * effective value (`docs/colon-identifiers/phase-9-plan.md` § 3.3).
6307
+ */
6308
+ const COLON_IDENTIFIERS = new InjectionToken('COLON_IDENTIFIERS');
6309
+ /** Angular's code for `inject()` called outside an injection context, NG0203. */
6310
+ const MISSING_INJECTION_CONTEXT = -203;
6311
+ /**
6312
+ * Whether the injector constructing a `ParserService` holds
6313
+ * {@link provideColonIdentifiers}. `false` outside an injection context:
6314
+ * `new ParserService()` constructed a working service before the provider
6315
+ * existed, and still does, with the option off. Any other error from the read
6316
+ * is rethrown (plan § 3.1).
6317
+ */
6318
+ const injectColonIdentifiers = () => {
6319
+ try {
6320
+ return inject(COLON_IDENTIFIERS, { optional: true }) === true;
6321
+ }
6322
+ catch (error) {
6323
+ if (error?.code === MISSING_INJECTION_CONTEXT) {
6324
+ return false;
6325
+ }
6326
+ throw error;
6327
+ }
6328
+ };
6329
+ /**
6330
+ * Turns `colonIdentifiers` on for every parse through `ParserService`, and so
6331
+ * through `EvalService`, `CompilerService` and `DiscoveryService`: a
6332
+ * colon-joined name such as `Q1:1:3` parses as one identifier and reads the
6333
+ * context key of that spelling. A per-call `colonIdentifiers` overrides it.
6334
+ *
6335
+ * Belongs in the application's root providers. `ParserService` is provided in
6336
+ * the root, so in a child environment injector - a lazy route's `providers` -
6337
+ * it would reach no parse; there it throws when that injector is created.
6338
+ *
6339
+ * @returns The providers, for the application's root providers.
6340
+ */
6341
+ function provideColonIdentifiers() {
6342
+ return makeEnvironmentProviders([
6343
+ { provide: COLON_IDENTIFIERS, useValue: true },
6344
+ provideEnvironmentInitializer(() => {
6345
+ if (inject(ParserService).parserOptions?.colonIdentifiers !== true) {
6346
+ throw new Error('provideColonIdentifiers() reaches no parse here: ' +
6347
+ 'ParserService is provided in the root, and the root ParserService ' +
6348
+ 'does not have colonIdentifiers on. Put provideColonIdentifiers() in ' +
6349
+ 'the application\'s root providers, not a lazy route\'s or another ' +
6350
+ 'child injector\'s.');
6351
+ }
6352
+ }),
6353
+ ]);
6354
+ }
6355
+
5685
6356
  /**
5686
6357
  * @description
5687
6358
  * Service for parsing expressions and returning ES6/ES2020 AST.
@@ -5702,13 +6373,17 @@ class ParserService {
5702
6373
  this._parserOptions = value;
5703
6374
  }
5704
6375
  /**
5705
- * Constructs a new instance of the ParserService class.
6376
+ * Constructs a new instance of the ParserService class. Its options carry
6377
+ * `colonIdentifiers: true` when the injector constructing it holds
6378
+ * `provideColonIdentifiers()`, and no such key otherwise.
5706
6379
  */
5707
6380
  constructor() {
6381
+ this._fingerprints = new WeakMap();
5708
6382
  this._isDestroyed = false;
5709
6383
  this.parserOptions = {
5710
6384
  ...defaultParserOptions,
5711
- extractExpressions: true
6385
+ extractExpressions: true,
6386
+ ...(injectColonIdentifiers() ? { colonIdentifiers: true } : {})
5712
6387
  };
5713
6388
  if (this.parserOptions.cacheSize) {
5714
6389
  this._cache = new Cache(this.parserOptions.cacheSize);
@@ -5777,19 +6452,30 @@ class ParserService {
5777
6452
  const parserOptions = { ...this.parserOptions, ...options };
5778
6453
  const isCache = this.parserOptions.cacheSize && this._cache;
5779
6454
  const ast = isCache
5780
- ? this.fromCacheOrParse(expr, parserOptions)
6455
+ ? this.fromCacheOrParse(expr, parserOptions, options)
5781
6456
  : parse(expr, parserOptions);
5782
6457
  return ast;
5783
6458
  }
5784
6459
  return undefined;
5785
6460
  }
5786
6461
  //#region Private methods
5787
- fromCacheOrParse(expr, options) {
6462
+ /**
6463
+ * Serves a cached AST only to a parse whose parse-relevant options match the
6464
+ * parse that cached it: the key is the text under a digest of the
6465
+ * fingerprint of the service's options and the call's, not the text alone
6466
+ * (`docs/backlog-retired.md` A26). A parse carrying a callback or a
6467
+ * `program` neither reads nor writes the cache.
6468
+ */
6469
+ fromCacheOrParse(expr, parserOptions, callOptions) {
5788
6470
  if (this._cache) {
5789
- const hashKey = this._cache.getHashKey('', expr);
6471
+ const namespace = parseFingerprint(this._fingerprints, this.parserOptions, callOptions);
6472
+ if (namespace === null) {
6473
+ return parse(expr, parserOptions);
6474
+ }
6475
+ const hashKey = this._cache.getHashKey(namespace, expr);
5790
6476
  let ast = this._cache.get(hashKey);
5791
6477
  if (!ast) {
5792
- ast = parse(expr, options);
6478
+ ast = parse(expr, parserOptions);
5793
6479
  this._cache.set(hashKey, ast);
5794
6480
  }
5795
6481
  return ast;
@@ -5928,6 +6614,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
5928
6614
  }]
5929
6615
  }], ctorParameters: () => [] });
5930
6616
 
6617
+ /** Stands for a `ParserService` that has no options object of its own. */
6618
+ const NO_SERVICE_OPTIONS = Object.freeze({});
5931
6619
  /**
5932
6620
  * CompilerService class that extends BaseEval.
5933
6621
  * Provides methods for compiling and evaluating expressions with performance caching.
@@ -5941,6 +6629,7 @@ class CompilerService extends BaseEval {
5941
6629
  this._cacheTTL = 10 * 60 * 1000; // 10 minutes
5942
6630
  this._accessOrder = new Set();
5943
6631
  this._isDestroyed = false;
6632
+ this._fingerprints = new WeakMap();
5944
6633
  this.parserService = inject(ParserService);
5945
6634
  this.evalService = inject(EvalService);
5946
6635
  this.parserOptions = defaultParserOptions;
@@ -6000,10 +6689,23 @@ class CompilerService extends BaseEval {
6000
6689
  }
6001
6690
  /**
6002
6691
  * Generate cache key for expression. Only a string is cached, so only a
6003
- * string has a key.
6692
+ * string has a key: the text under the digest of the options its parse
6693
+ * uses, `ParserService`'s merged with this service's, so a change through
6694
+ * the `ParserService.parserOptions` setter reaches a string compiled before
6695
+ * it (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The memo is
6696
+ * `ParserService`'s kind, and a write in place goes unseen here as there
6697
+ * (`docs/backlog.md` A34). `null` when that parse bypasses `ParserService`'s
6698
+ * cache - a callback or a `program` among its options, or a value JSON
6699
+ * cannot hold - and this cache then bypasses too, since a cached function
6700
+ * runs no callback.
6004
6701
  */
6005
6702
  generateCacheKey(expression) {
6006
- return `str:${expression}`;
6703
+ // A test double for `ParserService` need not carry `parserOptions`, and a
6704
+ // missing one cannot key the memo; it is fingerprinted as none.
6705
+ const serviceOptions = this.parserService.parserOptions;
6706
+ const digest = parseFingerprint(this._fingerprints, typeof serviceOptions === 'object' && serviceOptions !== null
6707
+ ? serviceOptions : NO_SERVICE_OPTIONS, this.parserOptions);
6708
+ return digest === null ? null : `str:${digest}:${expression}`;
6007
6709
  }
6008
6710
  /**
6009
6711
  * Update access order for LRU cache
@@ -6014,7 +6716,8 @@ class CompilerService extends BaseEval {
6014
6716
  }
6015
6717
  /**
6016
6718
  * Compiles the given expression into a state callback function. A string is
6017
- * compiled once and cached; an AST is compiled on every call.
6719
+ * compiled once and cached, unless its parse bypasses `ParserService`'s
6720
+ * cache; an AST is compiled on every call.
6018
6721
  * @param expression - The expression to compile.
6019
6722
  * @returns The compiled state callback function.
6020
6723
  * @throws Error if there is an error during compilation.
@@ -6033,6 +6736,9 @@ class CompilerService extends BaseEval {
6033
6736
  return compile(this.parse(expression));
6034
6737
  }
6035
6738
  const cacheKey = this.generateCacheKey(expression);
6739
+ if (cacheKey === null) {
6740
+ return compile(this.parse(expression));
6741
+ }
6036
6742
  // Check cache first
6037
6743
  const cached = this._compilationCache.get(cacheKey);
6038
6744
  if (cached?.sync) {
@@ -6099,8 +6805,8 @@ class CompilerService extends BaseEval {
6099
6805
  }
6100
6806
  /**
6101
6807
  * Compiles the given expression into an asynchronous state callback
6102
- * function. A string is compiled once and cached; an AST is compiled on
6103
- * every call.
6808
+ * function. A string is compiled once and cached, unless its parse bypasses
6809
+ * `ParserService`'s cache; an AST is compiled on every call.
6104
6810
  * @param expression - The expression to compile.
6105
6811
  * @returns The compiled asynchronous state callback function.
6106
6812
  * @throws Error if there is an error during compilation.
@@ -6111,6 +6817,9 @@ class CompilerService extends BaseEval {
6111
6817
  return compileAsync(this.parse(expression));
6112
6818
  }
6113
6819
  const cacheKey = this.generateCacheKey(expression);
6820
+ if (cacheKey === null) {
6821
+ return compileAsync(this.parse(expression));
6822
+ }
6114
6823
  // Check cache first
6115
6824
  const cached = this._compilationCache.get(cacheKey);
6116
6825
  if (cached?.async) {
@@ -6231,5 +6940,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
6231
6940
  * Generated bundle index. Do not edit.
6232
6941
  */
6233
6942
 
6234
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse };
6943
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse, provideColonIdentifiers };
6235
6944
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map