@zvenigora/ng-eval-core 0.10.1 → 0.11.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.
@@ -400,48 +400,6 @@ class Registry {
400
400
  }
401
401
  }
402
402
 
403
- /**
404
- * Represents a generic queue data structure.
405
- * @template T The type of elements stored in the queue.
406
- */
407
- class Queue {
408
- /**
409
- * Creates a new instance of the Queue class.
410
- * @param _queue Optional initial array of elements.
411
- */
412
- constructor(_queue = []) {
413
- this._queue = _queue;
414
- }
415
- /**
416
- * Gets the number of elements in the queue.
417
- */
418
- get length() {
419
- return this._queue.length;
420
- }
421
- /**
422
- * Removes and returns the first element in the queue.
423
- * @returns The first element in the queue, or undefined if the queue is empty.
424
- */
425
- dequeue() {
426
- return this._queue.shift();
427
- }
428
- /**
429
- * Adds an element to the end of the queue.
430
- * @param value The element to add to the queue.
431
- * @returns The new length of the queue.
432
- */
433
- enqueue(value) {
434
- return this._queue.push(value);
435
- }
436
- /**
437
- * Returns the first element in the queue without removing it.
438
- * @returns The first element in the queue.
439
- */
440
- peek() {
441
- return this._queue[0];
442
- }
443
- }
444
-
445
403
  /**
446
404
  * Represents a stack data structure with proper memory management.
447
405
  * @template T The type of elements in the stack.
@@ -675,84 +633,6 @@ class Cache {
675
633
  }
676
634
  }
677
635
 
678
- /**
679
- * Strips the `ParenthesizedExpression` wrappers acorn keeps around a node
680
- * under `preserveParens`, so `(a)` and `((a))` are handled as `a`. A walk
681
- * passes through them without help, since `acorn-walk`'s base visitor does;
682
- * only a visitor that branches on a child's *type* has to unwrap it first.
683
- * @param node - The node, possibly parenthesised.
684
- * @returns The innermost node that is not a `ParenthesizedExpression`.
685
- */
686
- const unwrapParentheses = (node) => {
687
- let inner = node;
688
- while (inner.type === 'ParenthesizedExpression') {
689
- inner = inner.expression;
690
- }
691
- return inner;
692
- };
693
- /**
694
- * Retrieves the key-value pair from an object based on the provided key.
695
- * @param obj - The object to search for the key-value pair.
696
- * @param key - The key to search for in the object.
697
- * @param caseInsesitive - Specifies whether the key comparison should be case-insensitive.
698
- * @returns The key-value pair as an array, or undefined if the key is not found.
699
- */
700
- const getKeyValue = (obj, key, caseInsesitive) => {
701
- if (!caseInsesitive || typeof key !== 'string') {
702
- const value = obj[key];
703
- return [key, value];
704
- }
705
- if (typeof key === 'string') {
706
- let currentObj = obj;
707
- do {
708
- const keys = Object.getOwnPropertyNames(currentObj);
709
- if (Array.isArray(keys)) {
710
- const foundKey = keys.find(k => equalIgnoreCase(key, k));
711
- if (foundKey) {
712
- const value = currentObj[foundKey];
713
- return [foundKey, value];
714
- }
715
- }
716
- } while ((currentObj = Object.getPrototypeOf(currentObj)));
717
- }
718
- return undefined;
719
- };
720
- /**
721
- * Compares two values for equality, ignoring case sensitivity.
722
- * @param a - The first value to compare.
723
- * @param b - The second value to compare.
724
- * @returns `true` if the values are equal, `false` otherwise.
725
- */
726
- const equalIgnoreCase = (a, b) => {
727
- if (typeof a === 'number' || typeof b === 'number') {
728
- return a === b;
729
- }
730
- else if (typeof a === 'symbol' || typeof b === 'symbol') {
731
- return a === b;
732
- }
733
- else if (typeof a === 'string' || typeof b === 'string') {
734
- return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
735
- }
736
- return undefined;
737
- };
738
- /**
739
- * Retrieves the value from an object, ignoring the case of the key.
740
- * @param obj - The object to retrieve the value from.
741
- * @param key - The key to search for, ignoring the case.
742
- * @returns The value associated with the key, or undefined if the key is not found.
743
- */
744
- const getValueIgnoreCase = (obj, key) => {
745
- const pair = getKeyValue(obj, key, true);
746
- if (pair) {
747
- return pair[1];
748
- }
749
- return undefined;
750
- };
751
-
752
- function isRegistryContext(context) {
753
- const value = ['Registry', 'CaseInsensitiveRegistry', 'BaseRegistry'].includes(context?.type);
754
- return value;
755
- }
756
636
  /**
757
637
  * Converts a context object to a Context instance.
758
638
  * @param context - The context object to convert.
@@ -813,33 +693,6 @@ const setContextValue = (context, key, value) => {
813
693
  object[key] = value;
814
694
  }
815
695
  };
816
- /**
817
- * Retrieves the key from the given context object.
818
- * If the context is an instance of Registry, it searches for the key in a case-insensitive manner if specified.
819
- * If the context is an instance of Object, it uses the getKeyValue function to retrieve the key-value pair.
820
- * @param context - The context object.
821
- * @param key - The key to retrieve.
822
- * @param caseInsensitive - Specifies whether the search should be case-insensitive (only applicable for Registry instances).
823
- * @returns The retrieved key, or undefined if the key is not found.
824
- */
825
- const getContextKey = (context, key, caseInsensitive) => {
826
- if (context instanceof Registry) {
827
- const keys = [...context.keys]; // : (string | number | symbol)[]
828
- const foundKey = caseInsensitive && typeof key === 'string'
829
- ? keys.find(k => equalIgnoreCase(key, k))
830
- : keys.find(k => k === key);
831
- if (foundKey) {
832
- return foundKey;
833
- }
834
- }
835
- else if (context instanceof Object) {
836
- const pair = getKeyValue(context, key, caseInsensitive);
837
- if (pair) {
838
- return pair[0];
839
- }
840
- }
841
- return undefined;
842
- };
843
696
 
844
697
  /**
845
698
  * The two push helpers each carry their own trace-bound call rather than
@@ -922,11 +775,79 @@ const afterVisitor = (node, st) => {
922
775
  st.hooks.dispatch('after', node, st, value);
923
776
  };
924
777
 
925
- var RecursiveVisitorResultType;
926
- (function (RecursiveVisitorResultType) {
927
- RecursiveVisitorResultType[RecursiveVisitorResultType["Stack"] = 0] = "Stack";
928
- RecursiveVisitorResultType[RecursiveVisitorResultType["Registry"] = 1] = "Registry";
929
- })(RecursiveVisitorResultType || (RecursiveVisitorResultType = {}));
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
+ };
930
851
 
931
852
  /**
932
853
  * Prototype Pollution Prevention Utilities
@@ -1198,8 +1119,13 @@ const literals = Registry.fromObject({
1198
1119
  * the source name stands in. The path is always the source spelling, since it
1199
1120
  * is reconstructed statically.
1200
1121
  *
1201
- * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
1202
- * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
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
1203
1129
  * tests for the binding rather than for its value: a parameter bound to
1204
1130
  * `undefined` is still a parameter, and reading the flag off the resolved value
1205
1131
  * would make it vary with the data rather than with the expression.
@@ -1210,8 +1136,10 @@ const literals = Registry.fromObject({
1210
1136
  * than set to false, so absent reads as "not scoped" the same way it does at
1211
1137
  * the member emission sites.
1212
1138
  *
1213
- * The scope stack is empty for any expression without an arrow function, and
1214
- * `Stack.asArray` allocates, so the common case is short-circuited on length.
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.
1215
1143
  */
1216
1144
  const emitRead = (node, st, value) => {
1217
1145
  const key = st.context?.getKey(node.name) ?? node.name;
@@ -1235,7 +1163,7 @@ const emitRead = (node, st, value) => {
1235
1163
  *
1236
1164
  * An identifier is resolved against the context, and `EvalContext.get` reads a
1237
1165
  * plain object there - the original, or a scope - with a bare property access.
1238
- * So up to 0.10.0 a name on the blocklist resolved to what the context inherits
1166
+ * So up to 0.10.x a name on the blocklist resolved to what the context inherits
1239
1167
  * from `Object.prototype` (`docs/backlog-retired.md` B6): the blocklist guarded
1240
1168
  * member access to the objects an expression holds, and the context is not one
1241
1169
  * of them. Every kind of context is refused alike, including those - a
@@ -1493,144 +1421,67 @@ const binaryExpressionVisitor = (node, st, callback) => {
1493
1421
  /**
1494
1422
  * Property Lookup Cache
1495
1423
  *
1496
- * Provides efficient caching for case-insensitive property lookups
1497
- * to avoid repeated O(n) searches through object property lists.
1424
+ * Remembers, per object, which own key a case-insensitive name resolved to,
1425
+ * so that a repeated read skips the O(n) scan of the object's own names.
1426
+ *
1427
+ * Keyed by the object itself (`docs/backlog-retired.md` A31). Up to 0.11.0 the
1428
+ * key was the object's own-key count and its first five own names, in one
1429
+ * cache for the whole process, so two objects that shared those answered for
1430
+ * each other: a read could return the wrong property, or `undefined`, and a
1431
+ * case variant of a blocked name read `undefined` instead of being refused.
1498
1432
  */
1433
+ // A `WeakMap`, so an entry lives exactly as long as its object, and nothing
1434
+ // one object answered can be read for another.
1435
+ let propertyLookupCache = new WeakMap();
1436
+ // Entries made since the last clear. A `WeakMap` cannot say how many are live.
1437
+ let entriesCreated = 0;
1499
1438
  /**
1500
- * Cache for property lookup results to optimize case-insensitive property access
1439
+ * Performs optimized case-insensitive property lookup with caching.
1440
+ *
1441
+ * A key found before is still the answer while it is still an own key of the
1442
+ * object, which is checked without a scan. One deleted or renamed since is
1443
+ * scanned for again. A miss stays a miss while the object's own-key count is
1444
+ * unchanged; a key added since changes the count, and the object's answers
1445
+ * are made afresh. Not caught: a key added in the same interval as another is
1446
+ * deleted, which leaves the count as it was, so a cached miss can outlive it.
1501
1447
  */
1502
- class PropertyLookupCache {
1503
- constructor(maxSize = 1000, expirationTimeMs = 5 * 60 * 1000) {
1504
- this._cache = new Map();
1505
- this._maxSize = maxSize;
1506
- this._expirationTime = expirationTimeMs;
1507
- }
1508
- /**
1509
- * Generates a simple hash for an object based on its own property names
1510
- */
1511
- generateObjectHash(obj) {
1512
- try {
1513
- const keys = Object.getOwnPropertyNames(obj);
1514
- return keys.length.toString() + '_' + keys.slice(0, 5).join('_');
1515
- }
1516
- catch {
1517
- return 'unknown_hash';
1518
- }
1519
- }
1520
- /**
1521
- * Generates a cache key for a property lookup
1522
- */
1523
- generateCacheKey(objectHash, searchKey) {
1524
- return `${objectHash}:${searchKey.toLowerCase()}`;
1525
- }
1526
- /**
1527
- * Checks if a cache entry is still valid
1528
- */
1529
- isEntryValid(entry, objectHash) {
1530
- const now = Date.now();
1531
- return (entry.objectHash === objectHash &&
1532
- (now - entry.lastAccessed) < this._expirationTime);
1533
- }
1534
- /**
1535
- * Cleans up expired entries and maintains cache size
1536
- */
1537
- cleanup() {
1538
- const now = Date.now();
1539
- const entries = Array.from(this._cache.entries());
1540
- // Remove expired entries
1541
- for (const [key, entry] of entries) {
1542
- if ((now - entry.lastAccessed) >= this._expirationTime) {
1543
- this._cache.delete(key);
1544
- }
1545
- }
1546
- // If still too large, remove oldest entries
1547
- if (this._cache.size > this._maxSize) {
1548
- const sortedEntries = Array.from(this._cache.entries())
1549
- .sort(([, a], [, b]) => a.lastAccessed - b.lastAccessed);
1550
- const entriesToRemove = sortedEntries.slice(0, this._cache.size - this._maxSize);
1551
- for (const [key] of entriesToRemove) {
1552
- this._cache.delete(key);
1553
- }
1554
- }
1555
- }
1556
- /**
1557
- * Gets a cached property lookup result
1558
- */
1559
- get(obj, searchKey) {
1560
- const objectHash = this.generateObjectHash(obj);
1561
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1562
- const entry = this._cache.get(cacheKey);
1563
- if (entry && this.isEntryValid(entry, objectHash)) {
1564
- // Update access time
1565
- entry.lastAccessed = Date.now();
1566
- return entry.foundKey;
1567
- }
1568
- return undefined; // Cache miss
1448
+ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1449
+ if (!obj || typeof obj !== 'object') {
1450
+ return null;
1569
1451
  }
1570
- /**
1571
- * Sets a cached property lookup result
1572
- */
1573
- set(obj, searchKey, foundKey) {
1574
- // Perform cleanup periodically
1575
- if (this._cache.size > this._maxSize * 0.8) {
1576
- this.cleanup();
1577
- }
1578
- const objectHash = this.generateObjectHash(obj);
1579
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1580
- this._cache.set(cacheKey, {
1581
- foundKey,
1582
- lastAccessed: Date.now(),
1583
- objectHash
1584
- });
1452
+ const lowered = searchKey.toLowerCase();
1453
+ let entry = propertyLookupCache.get(obj);
1454
+ const cached = entry?.found.get(lowered);
1455
+ if (typeof cached === 'string' && Object.prototype.hasOwnProperty.call(obj, cached)) {
1456
+ return cached;
1585
1457
  }
1586
- /**
1587
- * Clears the entire cache
1588
- */
1589
- clear() {
1590
- this._cache.clear();
1458
+ const ownKeys = Object.getOwnPropertyNames(obj);
1459
+ if (!entry || entry.keyCount !== ownKeys.length) {
1460
+ entry = { keyCount: ownKeys.length, found: new Map() };
1461
+ propertyLookupCache.set(obj, entry);
1462
+ entriesCreated++;
1591
1463
  }
1592
- /**
1593
- * Gets current cache size
1594
- */
1595
- get size() {
1596
- return this._cache.size;
1464
+ else if (cached === null) {
1465
+ return null;
1597
1466
  }
1598
- }
1599
- // Global property lookup cache instance
1600
- const propertyLookupCache = new PropertyLookupCache();
1601
- /**
1602
- * Performs optimized case-insensitive property lookup with caching
1603
- */
1604
- function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1605
- // Try to get from cache first
1606
- const cachedResult = propertyLookupCache.get(obj, searchKey);
1607
- if (cachedResult !== undefined) {
1608
- return cachedResult;
1609
- }
1610
- // Cache miss - perform actual lookup
1611
- let foundKey = null;
1612
- if (obj && typeof obj === 'object') {
1613
- const ownKeys = Object.getOwnPropertyNames(obj);
1614
- const matchingKey = ownKeys.find(k => equalIgnoreCase(k, searchKey));
1615
- foundKey = matchingKey || null;
1616
- }
1617
- // Cache the result
1618
- propertyLookupCache.set(obj, searchKey, foundKey);
1467
+ const foundKey = ownKeys.find(k => equalIgnoreCase(k, searchKey)) || null;
1468
+ entry.found.set(lowered, foundKey);
1619
1469
  return foundKey;
1620
1470
  }
1621
1471
  /**
1622
1472
  * Clears the property lookup cache (for testing or memory management)
1623
1473
  */
1624
1474
  function clearPropertyLookupCache() {
1625
- propertyLookupCache.clear();
1475
+ propertyLookupCache = new WeakMap();
1476
+ entriesCreated = 0;
1626
1477
  }
1627
1478
  /**
1628
- * Gets current property lookup cache statistics
1479
+ * Gets current property lookup cache statistics: the number of objects given
1480
+ * an entry since the last clear, live or collected.
1629
1481
  */
1630
1482
  function getPropertyLookupCacheStats() {
1631
1483
  return {
1632
- size: propertyLookupCache.size,
1633
- maxSize: 1000 // This should match the maxSize in constructor
1484
+ size: entriesCreated
1634
1485
  };
1635
1486
  }
1636
1487
 
@@ -1706,7 +1557,7 @@ const evaluateMember = (node, st, callback) => {
1706
1557
  // `this.k` resolves `k` against the context, as an identifier does, so it
1707
1558
  // is refused as one is (`identifier.ts`, `docs/backlog-retired.md` B6): a
1708
1559
  // blocklisted key before the lookup, and under `caseInsensitive` a
1709
- // blocklisted key the lookup matched. Up to 0.10.0 neither was checked,
1560
+ // blocklisted key the lookup matched. Up to 0.10.x neither was checked,
1710
1561
  // and `this.constructor` over a plain object was `Object`.
1711
1562
  if (isDangerousProperty(key)) {
1712
1563
  throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
@@ -1901,6 +1752,146 @@ const evaluateArray = (node, items, st, callback) => {
1901
1752
  return elements;
1902
1753
  };
1903
1754
 
1755
+ /**
1756
+ * Whether `value` can be held in a `WeakSet` - an object or a function.
1757
+ */
1758
+ const isObjectLike = (value) => (typeof value === 'object' && value !== null) || typeof value === 'function';
1759
+ /**
1760
+ * Records `value` as created by the walk, unless it is a primitive.
1761
+ *
1762
+ * For the one recording site whose value may be a primitive: an array or
1763
+ * parameter rest is `args.slice(i)`, which is a string when the destructured
1764
+ * source is one (`let [h, ...t] = "abc"`), and `WeakSet.add` throws on a
1765
+ * primitive. The literal, object-rest and arrow-function sites always create
1766
+ * an object and add directly.
1767
+ *
1768
+ * @param created - `st.createdObjects`, already read and found set by the caller.
1769
+ * @param value - The value the walk created.
1770
+ */
1771
+ const recordCreated = (created, value) => {
1772
+ if (isObjectLike(value)) {
1773
+ created.add(value);
1774
+ }
1775
+ };
1776
+ /**
1777
+ * Asks the context whether a member write may happen, through
1778
+ * `EvalContext.checkMemberWrite`. A refusal is a throw, and it propagates from
1779
+ * here unchanged: nothing has been written yet.
1780
+ *
1781
+ * Called by the member branches of `assignment-expression.ts` and
1782
+ * `update-expression.ts`, immediately before `safeSetProperty`, and only after
1783
+ * the caller has read `st.createdObjects` and found it set. That read is the
1784
+ * whole of the default path's cost: a state whose context has no policy holds
1785
+ * no set, so neither visitor reaches this call.
1786
+ *
1787
+ * @param st - The state of the walk making the write.
1788
+ * @param created - `st.createdObjects`, already read by the caller.
1789
+ * @param target - The object about to receive the write.
1790
+ * @param key - The property about to be written.
1791
+ */
1792
+ const consultMemberWrite = (st, created, target, key) => {
1793
+ st.context?.checkMemberWrite?.({
1794
+ target,
1795
+ key,
1796
+ createdByEvaluation: isObjectLike(target) && created.has(target),
1797
+ });
1798
+ };
1799
+ /**
1800
+ * The built-ins that write into their receiver or their first argument, keyed
1801
+ * by the function itself. Identity is the point: a method of the caller's own
1802
+ * named `push` is not one of these, and `Array.prototype.push` reached under
1803
+ * another name is.
1804
+ *
1805
+ * Read through property descriptors, since `%TypedArray%.prototype` carries
1806
+ * getters that throw when read off the prototype itself. Built once, from this
1807
+ * realm's built-ins: an array made in another realm - an iframe - holds that
1808
+ * realm's `push`, which is not in here.
1809
+ */
1810
+ const MUTATING_BUILT_INS = (() => {
1811
+ const table = new Map();
1812
+ const add = (owner, ownerName, names, writes) => {
1813
+ for (const name of names) {
1814
+ const fn = Object.getOwnPropertyDescriptor(owner, name)?.value;
1815
+ if (typeof fn === 'function') {
1816
+ table.set(fn, { name: `${ownerName}.${name}`, writes });
1817
+ }
1818
+ }
1819
+ };
1820
+ add(Array.prototype, 'Array.prototype', ['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], 'receiver');
1821
+ add(Object.getPrototypeOf(Int8Array.prototype), '%TypedArray%.prototype', ['copyWithin', 'fill', 'reverse', 'set', 'sort'], 'receiver');
1822
+ add(Map.prototype, 'Map.prototype', ['set', 'delete', 'clear'], 'receiver');
1823
+ add(Set.prototype, 'Set.prototype', ['add', 'delete', 'clear'], 'receiver');
1824
+ add(WeakMap.prototype, 'WeakMap.prototype', ['set', 'delete'], 'receiver');
1825
+ add(WeakSet.prototype, 'WeakSet.prototype', ['add', 'delete'], 'receiver');
1826
+ add(Date.prototype, 'Date.prototype', Object.getOwnPropertyNames(Date.prototype).filter((name) => name.startsWith('set')), 'receiver');
1827
+ add(Object, 'Object', ['assign', 'defineProperty', 'defineProperties', 'setPrototypeOf', 'freeze', 'seal', 'preventExtensions'], 'first argument');
1828
+ return table;
1829
+ })();
1830
+ /**
1831
+ * `Function.prototype`'s three ways to run a function with a `this` the
1832
+ * caller chooses. Read once, from this realm, as the table above is.
1833
+ */
1834
+ const FUNCTION_CALL = Function.prototype.call;
1835
+ const FUNCTION_APPLY = Function.prototype.apply;
1836
+ const FUNCTION_BIND = Function.prototype.bind;
1837
+ /**
1838
+ * The arguments `Function.prototype.apply` passes on: its second argument, read
1839
+ * as an array-like, as `apply` reads it. Nothing for anything else - `apply`
1840
+ * passes none for `null` or `undefined`, and throws for a primitive.
1841
+ */
1842
+ const argumentsOf = (list) => isObjectLike(list) ? Array.prototype.slice.call(list) : [];
1843
+ /**
1844
+ * Asks the context whether a call may run, when the function is a built-in
1845
+ * that writes into an object it is handed, through
1846
+ * `EvalContext.checkMemberWrite` with `method` naming it. Any other function is
1847
+ * not asked about. A refusal is a throw, and it propagates from here
1848
+ * unchanged: the call has not been made.
1849
+ *
1850
+ * Reached through `Function.prototype.call`, `apply` or `bind`, the function
1851
+ * the visitor calls is one of those three and not the built-in, so it is asked
1852
+ * about as a direct call of the function they run: its receiver is the `this`
1853
+ * they pass, and its arguments are the rest, or `apply`'s list. Followed
1854
+ * through `call.call`, `call.apply` and the like, since each hop is one more of
1855
+ * the three. `bind` makes a new function, which no table could recognise when
1856
+ * it is called later, so it is asked at bind time, about the bound `this` and
1857
+ * arguments: binding a built-in to an object the walk did not create is
1858
+ * refused before the bound function exists (`docs/backlog-retired.md` C5).
1859
+ *
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.
1862
+ *
1863
+ * @param st - The state of the walk making the call.
1864
+ * @param created - `st.createdObjects`, already read by the caller.
1865
+ * @param fn - The function about to be called.
1866
+ * @param receiver - The `this` it is about to be called with.
1867
+ * @param args - The arguments it is about to be called with.
1868
+ */
1869
+ const consultMethodWrite = (st, created, fn, receiver, args) => {
1870
+ if (fn === FUNCTION_CALL) {
1871
+ consultMethodWrite(st, created, receiver, args[0], args.slice(1));
1872
+ return;
1873
+ }
1874
+ if (fn === FUNCTION_APPLY) {
1875
+ consultMethodWrite(st, created, receiver, args[0], argumentsOf(args[1]));
1876
+ return;
1877
+ }
1878
+ if (fn === FUNCTION_BIND) {
1879
+ consultMethodWrite(st, created, receiver, args[0], args.slice(1));
1880
+ return;
1881
+ }
1882
+ const builtIn = MUTATING_BUILT_INS.get(fn);
1883
+ if (!builtIn) {
1884
+ return;
1885
+ }
1886
+ const target = builtIn.writes === 'receiver' ? receiver : args[0];
1887
+ st.context?.checkMemberWrite?.({
1888
+ target,
1889
+ key: undefined,
1890
+ createdByEvaluation: isObjectLike(target) && created.has(target),
1891
+ method: builtIn.name,
1892
+ });
1893
+ };
1894
+
1904
1895
  /**
1905
1896
  * Security: List of dangerous functions that should not be callable
1906
1897
  */
@@ -2035,6 +2026,12 @@ const scopeReceiver = (st, object) => {
2035
2026
  };
2036
2027
  /**
2037
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.
2038
2035
  */
2039
2036
  const callExpressionVisitor = (node, st, callback) => {
2040
2037
  beforeVisitor(node, st);
@@ -2042,7 +2039,12 @@ const callExpressionVisitor = (node, st, callback) => {
2042
2039
  if (node.callee.type === 'MemberExpression') {
2043
2040
  const [object, propertyName, fn] = evaluateMember(node.callee, st, callback);
2044
2041
  const functionName = typeof propertyName === 'string' ? propertyName : undefined;
2045
- const value = safeCall(fn, scopeReceiver(st, object), args, node.callee.optional, functionName);
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);
2046
2048
  pushVisitorResult(node, st, value);
2047
2049
  }
2048
2050
  else {
@@ -2053,6 +2055,10 @@ const callExpressionVisitor = (node, st, callback) => {
2053
2055
  if (node.callee.type === 'Identifier') {
2054
2056
  functionName = node.callee.name;
2055
2057
  }
2058
+ const created = st.createdObjects;
2059
+ if (created) {
2060
+ consultMethodWrite(st, created, caller, st.context, args);
2061
+ }
2056
2062
  const value = safeCall(caller, st.context, args, node.optional, functionName);
2057
2063
  pushVisitorResult(node, st, value);
2058
2064
  }
@@ -2453,51 +2459,6 @@ const getDefaultVisitors = () => {
2453
2459
  return visitors;
2454
2460
  };
2455
2461
 
2456
- /**
2457
- * Whether `value` can be held in a `WeakSet` - an object or a function.
2458
- */
2459
- const isObjectLike = (value) => (typeof value === 'object' && value !== null) || typeof value === 'function';
2460
- /**
2461
- * Records `value` as created by the walk, unless it is a primitive.
2462
- *
2463
- * For the one recording site whose value may be a primitive: an array or
2464
- * parameter rest is `args.slice(i)`, which is a string when the destructured
2465
- * source is one (`let [h, ...t] = "abc"`), and `WeakSet.add` throws on a
2466
- * primitive. The literal, object-rest and arrow-function sites always create
2467
- * an object and add directly.
2468
- *
2469
- * @param created - `st.createdObjects`, already read and found set by the caller.
2470
- * @param value - The value the walk created.
2471
- */
2472
- const recordCreated = (created, value) => {
2473
- if (isObjectLike(value)) {
2474
- created.add(value);
2475
- }
2476
- };
2477
- /**
2478
- * Asks the context whether a member write may happen, through
2479
- * `EvalContext.checkMemberWrite`. A refusal is a throw, and it propagates from
2480
- * here unchanged: nothing has been written yet.
2481
- *
2482
- * Called by the member branches of `assignment-expression.ts` and
2483
- * `update-expression.ts`, immediately before `safeSetProperty`, and only after
2484
- * the caller has read `st.createdObjects` and found it set. That read is the
2485
- * whole of the default path's cost: a state whose context has no policy holds
2486
- * no set, so neither visitor reaches this call.
2487
- *
2488
- * @param st - The state of the walk making the write.
2489
- * @param created - `st.createdObjects`, already read by the caller.
2490
- * @param target - The object about to receive the write.
2491
- * @param key - The property about to be written.
2492
- */
2493
- const consultMemberWrite = (st, created, target, key) => {
2494
- st.context?.checkMemberWrite?.({
2495
- target,
2496
- key,
2497
- createdByEvaluation: isObjectLike(target) && created.has(target),
2498
- });
2499
- };
2500
-
2501
2462
  // based on evalArrowContext
2502
2463
  // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
2503
2464
  /**
@@ -3875,9 +3836,8 @@ class EvalScope {
3875
3836
  * Whether a context holds a key at all, regardless of the value bound to it.
3876
3837
  *
3877
3838
  * There is no `getContextValue` counterpart for this: that helper cannot
3878
- * distinguish an absent key from one bound to `undefined`, and `getContextKey`
3879
- * with `caseInsensitive: false` reports every key as present for a plain
3880
- * object. Own properties only - the scopes this is used on are object literals
3839
+ * distinguish an absent key from one bound to `undefined`. Own properties
3840
+ * only - the scopes this is used on are object literals
3881
3841
  * built by `evaluatePatterns`, and inherited names are not bindings.
3882
3842
  */
3883
3843
  const hasContextKey = (context, key) => {
@@ -4032,8 +3992,8 @@ class EvalContext {
4032
3992
  return resolve(this, key)?.value;
4033
3993
  }
4034
3994
  /**
4035
- * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
4036
- * during this evaluation, innermost first.
3995
+ * Step 1 of {@link get}'s resolution order on its own: the scope stack,
3996
+ * innermost first, whoever pushed each scope.
4037
3997
  *
4038
3998
  * {@link get} calls this rather than inlining the loop, so that the read
4039
3999
  * hooks' `scoped` flag and the resolution it describes are the *same*
@@ -4107,8 +4067,11 @@ class EvalContext {
4107
4067
  return undefined;
4108
4068
  }
4109
4069
  /**
4110
- * Whether any scope pushed during this evaluation *binds* the key - the
4111
- * question the read hooks' `scoped` flag asks.
4070
+ * Whether any scope on the scope stack *binds* the key - the question the
4071
+ * read hooks' `scoped` flag asks. Every scope on the stack counts, whoever
4072
+ * pushed it: an arrow call's parameters, the lexical scope of a program, a
4073
+ * block or a `for` loop, and a scope a caller pushed with {@link push}
4074
+ * before the walk.
4112
4075
  *
4113
4076
  * Deliberately about binding rather than about value. It no longer parts
4114
4077
  * company with {@link getFromScopes} over it: both go through
@@ -5586,9 +5549,11 @@ const rootOf = (path) => {
5586
5549
  * rules do the filtering:
5587
5550
  *
5588
5551
  * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
5589
- * from a scope pushed during the walk - an arrow-function parameter. Only
5590
- * the walker can tell one from a real context read, which is why the flag
5591
- * exists; a consumer using this tracker inherits the filtering for free.
5552
+ * from a scope on the context's scope stack, whoever pushed it - an
5553
+ * arrow-function parameter, a declaration in a program, block or `for`
5554
+ * scope, or a binding the caller pushed before the walk. Only the walker
5555
+ * can tell one from a real context read, which is why the flag exists; a
5556
+ * consumer using this tracker inherits the filtering for free.
5592
5557
  * 2. **Nor is anything reached *through* one.** `item` being a binding makes
5593
5558
  * `item.name` one too, and that read carries no flag of its own: `scoped` is
5594
5559
  * set at identifier resolution, and the member hop resolves against the
@@ -6034,21 +5999,11 @@ class CompilerService extends BaseEval {
6034
5999
  }
6035
6000
  }
6036
6001
  /**
6037
- * Generate cache key for expression
6002
+ * Generate cache key for expression. Only a string is cached, so only a
6003
+ * string has a key.
6038
6004
  */
6039
6005
  generateCacheKey(expression) {
6040
- if (typeof expression === 'string') {
6041
- return `str:${expression}`;
6042
- }
6043
- else if (expression && typeof expression === 'object') {
6044
- // Use a simplified hash for AST nodes to avoid deep serialization overhead
6045
- return `ast:${expression.type}:${JSON.stringify({
6046
- type: expression.type,
6047
- start: expression.start,
6048
- end: expression.end
6049
- })}:${expression.toString()}`;
6050
- }
6051
- return 'undefined';
6006
+ return `str:${expression}`;
6052
6007
  }
6053
6008
  /**
6054
6009
  * Update access order for LRU cache
@@ -6058,7 +6013,8 @@ class CompilerService extends BaseEval {
6058
6013
  this._accessOrder.add(key);
6059
6014
  }
6060
6015
  /**
6061
- * Compiles the given expression into a state callback function with caching.
6016
+ * Compiles the given expression into a state callback function. A string is
6017
+ * compiled once and cached; an AST is compiled on every call.
6062
6018
  * @param expression - The expression to compile.
6063
6019
  * @returns The compiled state callback function.
6064
6020
  * @throws Error if there is an error during compilation.
@@ -6068,6 +6024,14 @@ class CompilerService extends BaseEval {
6068
6024
  // thrown. Each used to raise a bare `Error` carrying only the message in its
6069
6025
  // place, or a fixed message for a thrown non-`Error`
6070
6026
  // (`docs/backlog-retired.md` A5).
6027
+ // Only a string is cached, here and in `compileAsync`. Compiling a node is
6028
+ // binding `evaluate` to it, so caching one saves nothing, and the key it
6029
+ // was cached under - its type, start, end and `toString()`, which is
6030
+ // `[object Object]` for every node - gave two expressions of one shape and
6031
+ // span one compiled function (`docs/backlog-retired.md` A29).
6032
+ if (typeof expression !== 'string') {
6033
+ return compile(this.parse(expression));
6034
+ }
6071
6035
  const cacheKey = this.generateCacheKey(expression);
6072
6036
  // Check cache first
6073
6037
  const cached = this._compilationCache.get(cacheKey);
@@ -6134,12 +6098,18 @@ class CompilerService extends BaseEval {
6134
6098
  return undefined;
6135
6099
  }
6136
6100
  /**
6137
- * Compiles the given expression into an asynchronous state callback function with caching.
6101
+ * 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.
6138
6104
  * @param expression - The expression to compile.
6139
6105
  * @returns The compiled asynchronous state callback function.
6140
6106
  * @throws Error if there is an error during compilation.
6141
6107
  */
6142
6108
  compileAsync(expression) {
6109
+ // Only a string is cached, as in `compile` (`docs/backlog-retired.md` A29).
6110
+ if (typeof expression !== 'string') {
6111
+ return compileAsync(this.parse(expression));
6112
+ }
6143
6113
  const cacheKey = this.generateCacheKey(expression);
6144
6114
  // Check cache first
6145
6115
  const cached = this._compilationCache.get(cacheKey);
@@ -6261,5 +6231,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
6261
6231
  * Generated bundle index. Do not edit.
6262
6232
  */
6263
6233
 
6264
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
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 };
6265
6235
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map