@zvenigora/ng-eval-core 0.11.0 → 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.
package/CHANGELOG.md CHANGED
@@ -14,7 +14,45 @@ Versions 0.1.104–0.1.107 are on npm without entries here.
14
14
 
15
15
  ---
16
16
 
17
- ## [0.11.0] - 2026-10-04
17
+ ## [0.11.1] - 2026-10-10
18
+
19
+ **Two cache fixes: `CompilerService` no longer returns one AST's compiled function for another, and
20
+ under `caseInsensitive` a member read no longer resolves another object's spelling.** A patch. Both
21
+ caches came in with 0.2.1, so every version since is affected. No exported symbol changes shape: the
22
+ `.d.ts` differs from 0.11.0 in documentation comments only — `compile`'s and `compileAsync`'s, which
23
+ now say an AST is compiled on every call, and the four [A28](../../docs/backlog-retired.md#a28)
24
+ corrected. `eval-signals` 0.4.0–0.5.0 and `eval-forms` 0.4.x admit it: their peer range is
25
+ `>=0.11.0 <0.12.0`.
26
+
27
+ ### Changed
28
+ - `EvalReadEvent.scoped`'s JSDoc no longer says the flag marks a scope pushed during the
29
+ evaluation: it is set when any scope on the context's scope stack binds the name, one the caller
30
+ pushed with `EvalContext.push` before the walk included, and `hasInScopes`', `getFromScopes`'
31
+ and `createDependencyTracker`'s say the same ([A28](../../docs/backlog-retired.md#a28)). So does
32
+ the README's `onRead` example, whose comment said `event.scoped` was true for arrow-function
33
+ parameters. The flag's behaviour is unchanged.
34
+
35
+ ### Fixed
36
+ - **`CompilerService` no longer returns one AST's compiled function for another —
37
+ [A29](../../docs/backlog-retired.md#a29).** `compile` and `compileAsync` cached an AST under its
38
+ type, start and end and `toString()`, which is `[object Object]` for every node, so two different
39
+ expressions of one shape and span shared a function: `compile(ast('a * b'))` then
40
+ `compile(ast('c * d'))` returned `a * b`'s, which over `{ a: 1, b: 3, c: 3, d: 4 }` answered `3`,
41
+ not `12`, for as long as the cache kept it. An AST is now compiled on every call and never cached.
42
+ Affected 0.2.1–0.11.0, 0.10.1 included. A string input was never affected, and is cached as before.
43
+ - **Under `caseInsensitive`, a member read no longer resolves another object's spelling —
44
+ [A31](../../docs/backlog-retired.md#a31).** The cache of which own key a case variant names was
45
+ keyed by the object's own-key count and its first five key names, once for the whole process, so
46
+ objects that shared their first five key names could resolve each other's spelling: a read could
47
+ return the wrong property or `undefined`, and a case-variant read of a blocked name, such as
48
+ `x.CONSTRUCTOR`, could return `undefined` instead of throwing. No blocked property was ever read.
49
+ The cache is now keyed by the object itself, and a cached key is used only while it is still the
50
+ object's own. Affected 0.2.1–0.11.0, 0.10.1 included, from the same commit as A29; a read without
51
+ `caseInsensitive` never was.
52
+
53
+ ---
54
+
55
+ ## [0.11.0] - 2026-10-07
18
56
 
19
57
  **A security fix: an expression no longer resolves a name on the prototype-pollution blocklist
20
58
  against its context. Also, the member-write policy is asked about built-in methods that write,
@@ -99,7 +137,7 @@ what it sees. `eval-signals` 0.4.0 builds on the change and requires this versio
99
137
 
100
138
  ---
101
139
 
102
- ## [0.10.1] - 2026-10-05
140
+ ## [0.10.1] - 2026-10-07
103
141
 
104
142
  **A security fix: an expression no longer resolves a name on the prototype-pollution blocklist
105
143
  against its context.** A patch for every version up to 0.10.0, with no exported symbol changed.
package/README.md CHANGED
@@ -205,7 +205,9 @@ state.hooks.onRead((event) => {
205
205
  event.kind; // 'identifier' | 'member'
206
206
  event.key; // the resolved key
207
207
  event.path; // 'a.b' when statically reconstructible, else undefined
208
- event.scoped; // true for arrow-function parameters - not dependencies
208
+ event.scoped; // true when a scope on the context's stack binds the name - an
209
+ // arrow parameter, a let or const, or a scope pushed with
210
+ // EvalContext.push - so not a dependency
209
211
  });
210
212
  ```
211
213
 
@@ -1119,8 +1119,13 @@ const literals = Registry.fromObject({
1119
1119
  * the source name stands in. The path is always the source spelling, since it
1120
1120
  * is reconstructed statically.
1121
1121
  *
1122
- * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
1123
- * 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
1124
1129
  * tests for the binding rather than for its value: a parameter bound to
1125
1130
  * `undefined` is still a parameter, and reading the flag off the resolved value
1126
1131
  * would make it vary with the data rather than with the expression.
@@ -1131,8 +1136,10 @@ const literals = Registry.fromObject({
1131
1136
  * than set to false, so absent reads as "not scoped" the same way it does at
1132
1137
  * the member emission sites.
1133
1138
  *
1134
- * The scope stack is empty for any expression without an arrow function, and
1135
- * `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.
1136
1143
  */
1137
1144
  const emitRead = (node, st, value) => {
1138
1145
  const key = st.context?.getKey(node.name) ?? node.name;
@@ -1414,144 +1421,67 @@ const binaryExpressionVisitor = (node, st, callback) => {
1414
1421
  /**
1415
1422
  * Property Lookup Cache
1416
1423
  *
1417
- * Provides efficient caching for case-insensitive property lookups
1418
- * 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.
1419
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;
1420
1438
  /**
1421
- * 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.
1422
1447
  */
1423
- class PropertyLookupCache {
1424
- constructor(maxSize = 1000, expirationTimeMs = 5 * 60 * 1000) {
1425
- this._cache = new Map();
1426
- this._maxSize = maxSize;
1427
- this._expirationTime = expirationTimeMs;
1428
- }
1429
- /**
1430
- * Generates a simple hash for an object based on its own property names
1431
- */
1432
- generateObjectHash(obj) {
1433
- try {
1434
- const keys = Object.getOwnPropertyNames(obj);
1435
- return keys.length.toString() + '_' + keys.slice(0, 5).join('_');
1436
- }
1437
- catch {
1438
- return 'unknown_hash';
1439
- }
1440
- }
1441
- /**
1442
- * Generates a cache key for a property lookup
1443
- */
1444
- generateCacheKey(objectHash, searchKey) {
1445
- return `${objectHash}:${searchKey.toLowerCase()}`;
1446
- }
1447
- /**
1448
- * Checks if a cache entry is still valid
1449
- */
1450
- isEntryValid(entry, objectHash) {
1451
- const now = Date.now();
1452
- return (entry.objectHash === objectHash &&
1453
- (now - entry.lastAccessed) < this._expirationTime);
1454
- }
1455
- /**
1456
- * Cleans up expired entries and maintains cache size
1457
- */
1458
- cleanup() {
1459
- const now = Date.now();
1460
- const entries = Array.from(this._cache.entries());
1461
- // Remove expired entries
1462
- for (const [key, entry] of entries) {
1463
- if ((now - entry.lastAccessed) >= this._expirationTime) {
1464
- this._cache.delete(key);
1465
- }
1466
- }
1467
- // If still too large, remove oldest entries
1468
- if (this._cache.size > this._maxSize) {
1469
- const sortedEntries = Array.from(this._cache.entries())
1470
- .sort(([, a], [, b]) => a.lastAccessed - b.lastAccessed);
1471
- const entriesToRemove = sortedEntries.slice(0, this._cache.size - this._maxSize);
1472
- for (const [key] of entriesToRemove) {
1473
- this._cache.delete(key);
1474
- }
1475
- }
1476
- }
1477
- /**
1478
- * Gets a cached property lookup result
1479
- */
1480
- get(obj, searchKey) {
1481
- const objectHash = this.generateObjectHash(obj);
1482
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1483
- const entry = this._cache.get(cacheKey);
1484
- if (entry && this.isEntryValid(entry, objectHash)) {
1485
- // Update access time
1486
- entry.lastAccessed = Date.now();
1487
- return entry.foundKey;
1488
- }
1489
- return undefined; // Cache miss
1448
+ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1449
+ if (!obj || typeof obj !== 'object') {
1450
+ return null;
1490
1451
  }
1491
- /**
1492
- * Sets a cached property lookup result
1493
- */
1494
- set(obj, searchKey, foundKey) {
1495
- // Perform cleanup periodically
1496
- if (this._cache.size > this._maxSize * 0.8) {
1497
- this.cleanup();
1498
- }
1499
- const objectHash = this.generateObjectHash(obj);
1500
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1501
- this._cache.set(cacheKey, {
1502
- foundKey,
1503
- lastAccessed: Date.now(),
1504
- objectHash
1505
- });
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;
1506
1457
  }
1507
- /**
1508
- * Clears the entire cache
1509
- */
1510
- clear() {
1511
- 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++;
1512
1463
  }
1513
- /**
1514
- * Gets current cache size
1515
- */
1516
- get size() {
1517
- return this._cache.size;
1464
+ else if (cached === null) {
1465
+ return null;
1518
1466
  }
1519
- }
1520
- // Global property lookup cache instance
1521
- const propertyLookupCache = new PropertyLookupCache();
1522
- /**
1523
- * Performs optimized case-insensitive property lookup with caching
1524
- */
1525
- function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1526
- // Try to get from cache first
1527
- const cachedResult = propertyLookupCache.get(obj, searchKey);
1528
- if (cachedResult !== undefined) {
1529
- return cachedResult;
1530
- }
1531
- // Cache miss - perform actual lookup
1532
- let foundKey = null;
1533
- if (obj && typeof obj === 'object') {
1534
- const ownKeys = Object.getOwnPropertyNames(obj);
1535
- const matchingKey = ownKeys.find(k => equalIgnoreCase(k, searchKey));
1536
- foundKey = matchingKey || null;
1537
- }
1538
- // Cache the result
1539
- propertyLookupCache.set(obj, searchKey, foundKey);
1467
+ const foundKey = ownKeys.find(k => equalIgnoreCase(k, searchKey)) || null;
1468
+ entry.found.set(lowered, foundKey);
1540
1469
  return foundKey;
1541
1470
  }
1542
1471
  /**
1543
1472
  * Clears the property lookup cache (for testing or memory management)
1544
1473
  */
1545
1474
  function clearPropertyLookupCache() {
1546
- propertyLookupCache.clear();
1475
+ propertyLookupCache = new WeakMap();
1476
+ entriesCreated = 0;
1547
1477
  }
1548
1478
  /**
1549
- * 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.
1550
1481
  */
1551
1482
  function getPropertyLookupCacheStats() {
1552
1483
  return {
1553
- size: propertyLookupCache.size,
1554
- maxSize: 1000 // This should match the maxSize in constructor
1484
+ size: entriesCreated
1555
1485
  };
1556
1486
  }
1557
1487
 
@@ -4062,8 +3992,8 @@ class EvalContext {
4062
3992
  return resolve(this, key)?.value;
4063
3993
  }
4064
3994
  /**
4065
- * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
4066
- * 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.
4067
3997
  *
4068
3998
  * {@link get} calls this rather than inlining the loop, so that the read
4069
3999
  * hooks' `scoped` flag and the resolution it describes are the *same*
@@ -4137,8 +4067,11 @@ class EvalContext {
4137
4067
  return undefined;
4138
4068
  }
4139
4069
  /**
4140
- * Whether any scope pushed during this evaluation *binds* the key - the
4141
- * 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.
4142
4075
  *
4143
4076
  * Deliberately about binding rather than about value. It no longer parts
4144
4077
  * company with {@link getFromScopes} over it: both go through
@@ -5616,9 +5549,11 @@ const rootOf = (path) => {
5616
5549
  * rules do the filtering:
5617
5550
  *
5618
5551
  * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
5619
- * from a scope pushed during the walk - an arrow-function parameter. Only
5620
- * the walker can tell one from a real context read, which is why the flag
5621
- * 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.
5622
5557
  * 2. **Nor is anything reached *through* one.** `item` being a binding makes
5623
5558
  * `item.name` one too, and that read carries no flag of its own: `scoped` is
5624
5559
  * set at identifier resolution, and the member hop resolves against the
@@ -6064,21 +5999,11 @@ class CompilerService extends BaseEval {
6064
5999
  }
6065
6000
  }
6066
6001
  /**
6067
- * Generate cache key for expression
6002
+ * Generate cache key for expression. Only a string is cached, so only a
6003
+ * string has a key.
6068
6004
  */
6069
6005
  generateCacheKey(expression) {
6070
- if (typeof expression === 'string') {
6071
- return `str:${expression}`;
6072
- }
6073
- else if (expression && typeof expression === 'object') {
6074
- // Use a simplified hash for AST nodes to avoid deep serialization overhead
6075
- return `ast:${expression.type}:${JSON.stringify({
6076
- type: expression.type,
6077
- start: expression.start,
6078
- end: expression.end
6079
- })}:${expression.toString()}`;
6080
- }
6081
- return 'undefined';
6006
+ return `str:${expression}`;
6082
6007
  }
6083
6008
  /**
6084
6009
  * Update access order for LRU cache
@@ -6088,7 +6013,8 @@ class CompilerService extends BaseEval {
6088
6013
  this._accessOrder.add(key);
6089
6014
  }
6090
6015
  /**
6091
- * 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.
6092
6018
  * @param expression - The expression to compile.
6093
6019
  * @returns The compiled state callback function.
6094
6020
  * @throws Error if there is an error during compilation.
@@ -6098,6 +6024,14 @@ class CompilerService extends BaseEval {
6098
6024
  // thrown. Each used to raise a bare `Error` carrying only the message in its
6099
6025
  // place, or a fixed message for a thrown non-`Error`
6100
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
+ }
6101
6035
  const cacheKey = this.generateCacheKey(expression);
6102
6036
  // Check cache first
6103
6037
  const cached = this._compilationCache.get(cacheKey);
@@ -6164,12 +6098,18 @@ class CompilerService extends BaseEval {
6164
6098
  return undefined;
6165
6099
  }
6166
6100
  /**
6167
- * 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.
6168
6104
  * @param expression - The expression to compile.
6169
6105
  * @returns The compiled asynchronous state callback function.
6170
6106
  * @throws Error if there is an error during compilation.
6171
6107
  */
6172
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
+ }
6173
6113
  const cacheKey = this.generateCacheKey(expression);
6174
6114
  // Check cache first
6175
6115
  const cached = this._compilationCache.get(cacheKey);