@zvenigora/ng-eval-core 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable } from '@angular/core';
2
+ import { Injectable, inject } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
4
  import { defaultOptions, parse as parse$1, version } from 'acorn';
5
5
  import * as walk from 'acorn-walk';
@@ -826,6 +826,22 @@ const getContextKey = (context, key, caseInsensitive) => {
826
826
  return undefined;
827
827
  };
828
828
 
829
+ /**
830
+ * Whether a context holds a key at all, regardless of the value bound to it.
831
+ *
832
+ * There is no `getContextValue` counterpart for this: that helper cannot
833
+ * distinguish an absent key from one bound to `undefined`, and `getContextKey`
834
+ * with `caseInsensitive: false` reports every key as present for a plain
835
+ * object. Own properties only - the scopes this is used on are object literals
836
+ * built by `evaluatePatterns`, and inherited names are not bindings.
837
+ */
838
+ const hasContextKey = (context, key) => {
839
+ if (context instanceof Registry) {
840
+ return context.has(key);
841
+ }
842
+ return context instanceof Object
843
+ && Object.prototype.hasOwnProperty.call(context, key);
844
+ };
829
845
  /**
830
846
  * Represents the evaluation context for the code execution.
831
847
  */
@@ -892,11 +908,12 @@ class EvalContext {
892
908
  * @returns The value associated with the key, or undefined if not found.
893
909
  */
894
910
  get(key) {
895
- for (const scope of this._scopes.asArray()) {
896
- const value = getContextValue(scope, key);
897
- if (value !== undefined) {
898
- return value;
899
- }
911
+ // Presence, not value: a scope that *binds* the key answers, even when the
912
+ // value bound is `undefined`. See {@link scopeHolding} for why the two are
913
+ // not the same question, and what reading the value instead let through.
914
+ const scope = this.scopeHolding(key);
915
+ if (scope) {
916
+ return getContextValue(scope, key);
900
917
  }
901
918
  if (this._original) {
902
919
  const value = getContextValue(this._original, key);
@@ -918,6 +935,105 @@ class EvalContext {
918
935
  }
919
936
  return undefined;
920
937
  }
938
+ /**
939
+ * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
940
+ * during this evaluation, innermost first.
941
+ *
942
+ * {@link get} calls this rather than inlining the loop, so that the read
943
+ * hooks' `scoped` flag and the resolution it describes are the *same*
944
+ * implementation. A second copy of the order would drift - `getKey` already
945
+ * shows what that looks like when it does.
946
+ *
947
+ * A binding whose value is `undefined` is **found** here, and no longer reads
948
+ * as absent - see {@link scopeHolding}.
949
+ *
950
+ * @param key - The key to retrieve the value for.
951
+ * @returns The value bound by the innermost scope holding the key, or
952
+ * undefined when no pushed scope holds it. The two cases are no longer
953
+ * distinguishable from the return value alone; ask {@link hasInScopes}.
954
+ */
955
+ getFromScopes(key) {
956
+ const scope = this.scopeHolding(key);
957
+ return scope ? getContextValue(scope, key) : undefined;
958
+ }
959
+ /**
960
+ * The innermost pushed scope that **binds** `key`, or undefined when none
961
+ * does. The single pass behind {@link get}'s step 1, {@link getFromScopes}
962
+ * and {@link hasInScopes}, so the three cannot disagree about what the scope
963
+ * stack holds.
964
+ *
965
+ * **Binding, not value, and that is the whole point.** Reading the value and
966
+ * treating `undefined` as absent - which is what this used to do - has two
967
+ * consequences that look unrelated and are the same bug:
968
+ *
969
+ * - `let x;` could not shadow. A scope binding `x` to `undefined` fell
970
+ * through to the caller's context, so a declared-but-unset name read
971
+ * whatever the consumer happened to have under it.
972
+ * - **A plain-object scope answered for every `Object.prototype` name.**
973
+ * `getContextValue` reads a plain record as `scope[key]`, which walks the
974
+ * prototype chain, so an *empty* scope resolved `toString`, `constructor`,
975
+ * `valueOf` and friends to the prototype's own members - shadowing
976
+ * `original`, `priorScopes` and `lookups`, all four of which come later in
977
+ * {@link get}'s order. Empty as a binding surface is not empty as a lookup
978
+ * surface. `hasContextKey` is own-properties-only, which closes it.
979
+ *
980
+ * The second was invisible while only `arrow-function-expression.ts` and
981
+ * `pattern.ts` pushed scopes, because a walk that pushed none could not hit
982
+ * it; a program-level scope on every evaluation made it reachable from every
983
+ * expression, which is how it was found.
984
+ *
985
+ * It also removes an asymmetry between the two scope shapes: `fromContext`
986
+ * copies a plain record into a `Registry` when `caseInsensitive` is set, and
987
+ * a `Registry` is Map-backed, so the prototype names leaked on the
988
+ * case-sensitive path and not on the case-insensitive one. Both now ask the
989
+ * same own-key question.
990
+ *
991
+ * **Public since Phase 2 step 3, and the reason is the write sites.**
992
+ * `assignment-expression.ts` and `update-expression.ts` need the *scope* and
993
+ * not a yes/no: `const` kinds are recorded against the scope object on
994
+ * `EvalState`, so a write has to know which scope it is about to land in
995
+ * before it can decide whether the binding is reassignable. Publishing the
996
+ * single pass is what keeps that question answered by the same code as
997
+ * {@link get}'s step 1. The alternative was a second copy of the
998
+ * innermost-scope walk at each write site, which is the defect
999
+ * `docs/backlog.md` A4 and A10 already describe - two copies of one
1000
+ * resolution order, drifting - reproduced on purpose.
1001
+ *
1002
+ * @param key - The key to look for.
1003
+ * @returns The innermost scope binding the key, or undefined.
1004
+ */
1005
+ scopeHolding(key) {
1006
+ for (const scope of this._scopes.asArray()) {
1007
+ if (hasContextKey(scope, key)) {
1008
+ return scope;
1009
+ }
1010
+ }
1011
+ return undefined;
1012
+ }
1013
+ /**
1014
+ * Whether any scope pushed during this evaluation *binds* the key - the
1015
+ * question the read hooks' `scoped` flag asks.
1016
+ *
1017
+ * Deliberately about binding rather than about value. It no longer parts
1018
+ * company with {@link getFromScopes} over it: both go through
1019
+ * {@link scopeHolding}, and `get` resolves a scope binding whatever its
1020
+ * value, which is the divergence this docblock used to record as deliberate.
1021
+ * Reading the flag off the value would make it depend on the *data* - the
1022
+ * same arrow function over `[{ name: 'a' }]` and over `[undefined]` would
1023
+ * report different bindings, and a dependency tracker's output would vary
1024
+ * between two recomputes of one expression. That is the failure this flag
1025
+ * exists to prevent, so presence is the correct predicate.
1026
+ *
1027
+ * Both queries iterate the same stack in the same direction, so neither is a
1028
+ * second copy of the four-step resolution order; they answer two different
1029
+ * questions about its first step.
1030
+ *
1031
+ * @param key - The key to look for.
1032
+ * @returns True when a pushed scope holds the key, whatever its value.
1033
+ */
1034
+ hasInScopes(key) {
1035
+ return this.scopeHolding(key) !== undefined;
1036
+ }
921
1037
  /**
922
1038
  * Retrieves the `this` value of the specified key from the evaluation context.
923
1039
  * The value is searched in the original context, prior scopes, and lookup functions.
@@ -990,6 +1106,50 @@ class EvalContext {
990
1106
  obj[key] = value;
991
1107
  }
992
1108
  }
1109
+ /**
1110
+ * Assigns to the innermost pushed scope that **binds** `key`, and reports
1111
+ * whether one did.
1112
+ *
1113
+ * The scope-aware half of the write path: `assignment-expression.ts` and
1114
+ * `update-expression.ts` try this first and fall back to {@link set}. Before
1115
+ * Phase 2 they only had {@link set}, which writes `_original` and consults no
1116
+ * scope at all - so `(x => (x = 99))(1)` wrote `99` into the *caller's*
1117
+ * object and left the arrow's parameter scope untouched.
1118
+ *
1119
+ * **Binding-presence, not scope-presence, and the fallback is load-bearing.**
1120
+ * `eval-signals` enforces a read-only policy by subclassing this class and
1121
+ * overriding {@link set} to throw, so every write that reaches the consumer's
1122
+ * data goes through the one method it overrides. An implementation that wrote
1123
+ * the innermost scope unconditionally - or created the binding when it was
1124
+ * absent - would route such a write around that override and silently disable
1125
+ * the policy of a published library, with every suite still green. Returning
1126
+ * false when nothing binds the key is what keeps {@link set} reachable.
1127
+ *
1128
+ * What it deliberately relaxes: a write to a binding the expression itself
1129
+ * created - an arrow parameter, or a `let` - no longer reaches {@link set},
1130
+ * because it mutates nothing the caller owns.
1131
+ *
1132
+ * The write dispatches through `setContextValue` rather than through the
1133
+ * prototype-pollution guard's `safeSetProperty`, and the difference is not
1134
+ * cosmetic: {@link push} normalises a plain record into a `Registry` when
1135
+ * `caseInsensitive` is set, and `Object.defineProperty` on a `Registry` would
1136
+ * define a property on the instance while inserting nothing into its map. No
1137
+ * guard is lost - this method only ever writes a key some scope already
1138
+ * *binds*, and a binding can only have been created through the guarded
1139
+ * declaration path, which rejects every blocklisted name.
1140
+ *
1141
+ * @param key - The key to assign to.
1142
+ * @param value - The value to assign.
1143
+ * @returns True when a pushed scope bound the key and received the write.
1144
+ */
1145
+ setInScope(key, value) {
1146
+ const scope = this.scopeHolding(key);
1147
+ if (!scope) {
1148
+ return false;
1149
+ }
1150
+ setContextValue(scope, key, value);
1151
+ return true;
1152
+ }
993
1153
  /**
994
1154
  * Pushes a context to the scope stack.
995
1155
  * @param context - The context to push.
@@ -1184,35 +1344,899 @@ class EvalResult {
1184
1344
  this._isError = true;
1185
1345
  this._isUndefined = false;
1186
1346
  }
1187
- }
1188
-
1189
- /**
1190
- * Represents the evaluation state, which includes the context, result, and options.
1191
- */
1192
- class EvalState {
1347
+ }
1348
+
1349
+ const DEFAULT_POLICY = 'collect';
1350
+ const POLICIES = ['collect', 'throw', 'ignore'];
1351
+ /**
1352
+ * The message carried by the error raised when a hook returns a promise.
1353
+ *
1354
+ * Hooks are synchronous by contract (§ 3.3): the walk is synchronous even under
1355
+ * `evaluateAsync`, so a returned promise is never awaited and whatever the hook
1356
+ * meant to do lands after the evaluation finished. The dispatcher reports it as
1357
+ * an error carrying this message, routed through the configured policy like any
1358
+ * other hook error - collected by default, and thrown into the visitor under
1359
+ * `'throw'`, which does fail the evaluation.
1360
+ *
1361
+ * Exported so a consumer inspecting `EvalState.hookErrors` can tell this
1362
+ * diagnostic apart from an error its own hook threw, without matching on
1363
+ * message text it would have to keep in sync by hand.
1364
+ */
1365
+ const ASYNC_HOOK_MESSAGE = 'async hook returned a promise; it will not be awaited';
1366
+ /**
1367
+ * The completion value of a statement that produced nothing.
1368
+ *
1369
+ * JavaScript's completion-value semantics keep the last **non-empty** value, and
1370
+ * empty is not the same as `undefined`: `{ 'a'; noop() }` is `undefined` because
1371
+ * the call genuinely produced one, while `{ 'a'; ; }` is `'a'` because the empty
1372
+ * statement produced nothing at all. A statement visitor that produced no value
1373
+ * therefore pushes this rather than `undefined`, and an enclosing block keeps the
1374
+ * last value that is not this.
1375
+ *
1376
+ * It never reaches an evaluation's return value: `evaluate` and `evaluateAsync`
1377
+ * convert it to `undefined` at the walk boundary, immediately after popping the
1378
+ * result. It **is** reachable in a hook event, because `afterVisitor` reads the
1379
+ * value positionally off the top of the result stack - so an 'after' hook on a
1380
+ * statement that produced nothing observes this sentinel. Hiding it there is not
1381
+ * available: the alternatives are calling `afterVisitor` before the push, which
1382
+ * reports the neighbour's value, or normalising inside `afterVisitor`, which puts
1383
+ * a per-node cost on the hot path for a case only statements produce.
1384
+ *
1385
+ * Exported for that reason, on the precedent of {@link ASYNC_HOOK_MESSAGE}: a
1386
+ * consumer whose hook receives it can recognise it by identity rather than by
1387
+ * guessing at a value it would have to keep in sync by hand.
1388
+ */
1389
+ const EMPTY_COMPLETION = Symbol('eval-core:empty-completion');
1390
+ /**
1391
+ * Reads the error policy out of the evaluation options. `EvalOptions` is a union
1392
+ * and does not index directly, so the read goes through a cast - the same one
1393
+ * `before-visitor.ts` performs.
1394
+ */
1395
+ const readPolicy = (options) => {
1396
+ const value = options?.['onHookError'];
1397
+ return POLICIES.includes(value)
1398
+ ? value
1399
+ : DEFAULT_POLICY;
1400
+ };
1401
+ const isPromiseLike = (value) => !!value &&
1402
+ (typeof value === 'object' || typeof value === 'function') &&
1403
+ typeof value.then === 'function';
1404
+ /**
1405
+ * A registry of node hooks, keyed by node type with wildcard support, and the
1406
+ * dispatcher that keeps `before` and `after` balanced when a visitor throws.
1407
+ *
1408
+ * It holds *registration* only. Everything whose lifetime is a single
1409
+ * evaluation - the open-node stack and the collected errors - lives on the
1410
+ * `EvalState` instead, because a consumer may hand one `EvalHooks` to several
1411
+ * evaluations and expect each to observe both.
1412
+ *
1413
+ * Hooks are synchronous by design: the walk in `evaluate` is synchronous even
1414
+ * under `evaluateAsync`, so there is no point at which a hook could be awaited.
1415
+ */
1416
+ class EvalHooks {
1417
+ /**
1418
+ * @param options The evaluation options; `onHookError` selects the error policy.
1419
+ */
1420
+ constructor(options) {
1421
+ this._before = new Map();
1422
+ this._after = new Map();
1423
+ this._read = [];
1424
+ this._size = 0;
1425
+ this._active = false;
1426
+ this._policy = readPolicy(options);
1427
+ }
1428
+ /**
1429
+ * True while no hook is registered. Read on the hot path, so it is a counter
1430
+ * rather than a walk of the registries.
1431
+ */
1432
+ get isEmpty() {
1433
+ return this._size === 0;
1434
+ }
1435
+ /**
1436
+ * The dispatch guard, behind `EvalState.hasHooks`.
1437
+ *
1438
+ * Unlike {@link isEmpty} this *latches*: it turns true on the first
1439
+ * registration and only `clear` turns it off again. The guard wraps the
1440
+ * open-node stack as well as the hooks themselves, so a value that changed
1441
+ * mid-walk would leave `enter` and `exit` unpaired - which is exactly what
1442
+ * one-shot and self-unsubscribing hooks would otherwise cause.
1443
+ *
1444
+ * Calling `clear` during a walk is therefore unsupported.
1445
+ */
1446
+ get isActive() {
1447
+ return this._active;
1448
+ }
1449
+ /**
1450
+ * True while at least one read hook is registered.
1451
+ *
1452
+ * The second half of the read-emission guard: `st.hasHooks` says a registry
1453
+ * exists and has been used, this says a *read* hook is there to observe the
1454
+ * event. Without it a consumer that registered only 'before'/'after' hooks
1455
+ * would pay `getKey` per identifier and `readPath` plus an object literal per
1456
+ * member for events it can never see - which the timing hook turns from
1457
+ * theoretical into routine, since it latches `hasHooks` for a whole walk.
1458
+ *
1459
+ * **Non-latching, unlike {@link isActive}.** That getter latches because it
1460
+ * wraps the open-node stack, so a value changing mid-walk would leave `enter`
1461
+ * and `exit` unpaired. `dispatchRead` touches no bookkeeping, so a read guard
1462
+ * that flips mid-walk can only drop read events - never unbalance anything.
1463
+ * A one-shot or self-unsubscribing read hook is therefore safe here, and the
1464
+ * guard can report the current registration count rather than history.
1465
+ */
1466
+ get hasReadHooks() {
1467
+ return this._read.length > 0;
1468
+ }
1469
+ /**
1470
+ * Registers a node hook.
1471
+ * @param phase Whether to fire before or after the visitor body.
1472
+ * @param type A concrete node type, or '*' for every node.
1473
+ * @param hook The hook to register.
1474
+ * @returns A function that removes this hook.
1475
+ */
1476
+ on(phase, type, hook) {
1477
+ const registry = this.registry(phase);
1478
+ const hooks = registry.get(type);
1479
+ if (hooks) {
1480
+ hooks.push(hook);
1481
+ }
1482
+ else {
1483
+ registry.set(type, [hook]);
1484
+ }
1485
+ this._size++;
1486
+ this._active = true;
1487
+ let unsubscribed = false;
1488
+ return () => {
1489
+ if (unsubscribed) {
1490
+ return;
1491
+ }
1492
+ unsubscribed = true;
1493
+ this.off(phase, type, hook);
1494
+ };
1495
+ }
1496
+ /**
1497
+ * Registers a read hook, fired once per resolved context read.
1498
+ *
1499
+ * Read hooks are not keyed by node type: there are only two emission points
1500
+ * and a consumer filters on {@link EvalReadEvent.kind} if it cares.
1501
+ *
1502
+ * Registration latches {@link isActive} exactly as {@link on} does, because
1503
+ * the visitors reach their emission points through the same
1504
+ * `EvalState.hasHooks` guard.
1505
+ *
1506
+ * @param hook The hook to register.
1507
+ * @returns A function that removes this hook.
1508
+ */
1509
+ onRead(hook) {
1510
+ this._read.push(hook);
1511
+ this._size++;
1512
+ this._active = true;
1513
+ let unsubscribed = false;
1514
+ return () => {
1515
+ if (unsubscribed) {
1516
+ return;
1517
+ }
1518
+ unsubscribed = true;
1519
+ this.offRead(hook);
1520
+ };
1521
+ }
1522
+ /**
1523
+ * Removes one read hook, or every read hook when `hook` is omitted.
1524
+ */
1525
+ offRead(hook) {
1526
+ if (hook === undefined) {
1527
+ this._size -= this._read.length;
1528
+ this._read = [];
1529
+ return;
1530
+ }
1531
+ const index = this._read.indexOf(hook);
1532
+ if (index < 0) {
1533
+ return;
1534
+ }
1535
+ this._read.splice(index, 1);
1536
+ this._size--;
1537
+ }
1538
+ /**
1539
+ * Removes one hook, or every hook registered for a key when `hook` is omitted.
1540
+ */
1541
+ off(phase, type, hook) {
1542
+ const registry = this.registry(phase);
1543
+ const hooks = registry.get(type);
1544
+ if (!hooks) {
1545
+ return;
1546
+ }
1547
+ if (hook === undefined) {
1548
+ registry.delete(type);
1549
+ this._size -= hooks.length;
1550
+ return;
1551
+ }
1552
+ const index = hooks.indexOf(hook);
1553
+ if (index < 0) {
1554
+ return;
1555
+ }
1556
+ hooks.splice(index, 1);
1557
+ this._size--;
1558
+ if (hooks.length === 0) {
1559
+ registry.delete(type);
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Removes every hook from both phases and unlatches {@link isActive}.
1564
+ *
1565
+ * Per-run bookkeeping is untouched: the open-node stack and the collected
1566
+ * errors belong to the `EvalState`, not to this registry. Errors in
1567
+ * particular are a record of what already happened.
1568
+ */
1569
+ clear() {
1570
+ this._before.clear();
1571
+ this._after.clear();
1572
+ this._read = [];
1573
+ this._size = 0;
1574
+ this._active = false;
1575
+ }
1576
+ /**
1577
+ * Fires the hooks registered for a node, keyed first and wildcard second.
1578
+ *
1579
+ * Bookkeeping runs before user code on both edges: 'before' pushes the node
1580
+ * onto the open-node stack and *then* emits, 'after' pops and *then* emits.
1581
+ * The shared rule is that hook code only ever runs once the stack already
1582
+ * tells the truth about this node, because `emit` can throw - under the
1583
+ * 'throw' policy a hook's error propagates out of it. Emitting first on the
1584
+ * 'before' edge would leave a node that some hooks had already been told
1585
+ * about missing from the stack, and therefore invisible to `unwindTo`.
1586
+ *
1587
+ * @param value The value the visitor pushed; meaningful on 'after' only.
1588
+ */
1589
+ dispatch(phase, node, state, value) {
1590
+ if (phase === 'after') {
1591
+ this.exit(state, node);
1592
+ this.emit({ phase, node, state, value, completed: true }, false);
1593
+ return;
1594
+ }
1595
+ this.enter(node, state);
1596
+ this.emit({ phase, node, state, completed: true }, false);
1597
+ }
1598
+ /**
1599
+ * Fires the read hooks for one resolved context read.
1600
+ *
1601
+ * The event is built by the caller rather than assembled from positional
1602
+ * arguments here, so the visitors allocate nothing on the no-hooks path: the
1603
+ * whole construction sits inside their `st.hasHooks` guard.
1604
+ *
1605
+ * Touches no bookkeeping. A read is not a frame - it happens *within* a
1606
+ * node's before/after pair, so the open-node stack is none of its business.
1607
+ */
1608
+ dispatchRead(event) {
1609
+ if (this._read.length === 0) {
1610
+ return;
1611
+ }
1612
+ // Iterated as a copy so a hook that unsubscribes itself does not shift the
1613
+ // list out from under the loop.
1614
+ for (const hook of this._read.slice()) {
1615
+ this.invokeRead(hook, event);
1616
+ }
1617
+ }
1618
+ /**
1619
+ * Records a node as open on the state. Called by the 'before' dispatcher
1620
+ * before its hooks fire.
1621
+ */
1622
+ enter(node, state) {
1623
+ state.hookBookkeeping.open.push(node);
1624
+ }
1625
+ /**
1626
+ * Closes `node`, matching it by **identity** rather than by position. Called
1627
+ * by the 'after' dispatcher before its hooks fire.
1628
+ *
1629
+ * Three cases:
1630
+ *
1631
+ * 1. `node` is on top - pop it. The ordinary path, one reference comparison.
1632
+ * 2. `node` is open but not on top - some visitor between here and there
1633
+ * never closed itself. Flush those frames innermost-first as
1634
+ * `completed: false`, then pop `node`.
1635
+ * 3. `node` is not open at all - pop nothing and emit nothing.
1636
+ *
1637
+ * Case 3 is what keeps a stray `exit` from draining the stack: the naive
1638
+ * "pop until you find it" would walk to the bottom, synthesise an event for
1639
+ * every genuinely-open enclosing frame, and leave a later real failure with
1640
+ * nothing to unwind.
1641
+ *
1642
+ * **"Open" means open in *this* walk.** Both routes below are bounded by the
1643
+ * current walk base ({@link EvalHookBookkeeping.walkBases}), so a node open
1644
+ * only in an enclosing walk falls into case 3 by either route - which is the
1645
+ * behaviour case 3 already specifies for "not open at all". `evaluate` is
1646
+ * re-entered with the same state from an arrow-function body, so without the
1647
+ * bound a nested walk closing a node it never opened would flush the
1648
+ * enclosing walk's frames under `completed: false` events a consumer reads as
1649
+ * ordinary completions, and leave that walk's own `unwindTo(mark)` with
1650
+ * nothing left to unwind.
1651
+ *
1652
+ * The bound is needed on the **identity fast path** as much as on the scan:
1653
+ * when a nested walk has opened nothing yet, the top of the stack *is* the
1654
+ * enclosing walk's node, so the cheap route crosses the boundary without ever
1655
+ * reaching the scan.
1656
+ *
1657
+ * Popping positionally instead would be correct only if every visitor
1658
+ * bracketed its body exactly. `await-expression.ts` does not - it catches a
1659
+ * child's synchronous throw and continues to its own `afterVisitor` - so a
1660
+ * positional pop closes the child's frame under the parent's name, drops the
1661
+ * child's `after` entirely, and leaks one frame onto the state for good.
1662
+ *
1663
+ * The synthesised events carry no `value` (the node never pushed one) and no
1664
+ * `error` (nothing threw; the frames are being closed because an enclosing
1665
+ * visitor moved on without them).
1666
+ *
1667
+ * They are emitted under the collect policy even when the consumer chose
1668
+ * 'throw'. That is required, not merely lenient: a rethrow here would escape
1669
+ * the flush loop before it finished popping, re-creating the leak this
1670
+ * identity check exists to prevent. A 'throw'-policy consumer sees these in
1671
+ * `state.hookErrors` instead.
1672
+ */
1673
+ exit(state, node) {
1674
+ const open = state.hookBookkeeping.open;
1675
+ const base = this.walkBase(state);
1676
+ if (open.length > base && open[open.length - 1] === node) {
1677
+ open.pop();
1678
+ return;
1679
+ }
1680
+ // The innermost occurrence is the one being closed: a node can legitimately
1681
+ // be open twice, since an arrow-function body is re-walked on every call.
1682
+ // `lastIndexOf` returns -1 when the node is absent, which the same
1683
+ // comparison rejects - "below this walk's base" and "not open at all" are
1684
+ // the same case here.
1685
+ const index = open.lastIndexOf(node);
1686
+ if (index < base) {
1687
+ return;
1688
+ }
1689
+ while (open.length > index + 1) {
1690
+ const stranded = open.pop();
1691
+ if (!stranded) {
1692
+ break;
1693
+ }
1694
+ this.emit({ phase: 'after', node: stranded, state, completed: false }, true);
1695
+ }
1696
+ open.pop();
1697
+ }
1698
+ /**
1699
+ * How many nodes the state has open. Captured as a mark before a walk, since
1700
+ * `evaluate` is re-entered with the same state from an arrow-function body.
1701
+ *
1702
+ * This is a method rather than a getter because the stack it measures lives
1703
+ * on the state, not on this registry.
1704
+ */
1705
+ depth(state) {
1706
+ return state.hookBookkeeping.open.length;
1707
+ }
1708
+ /**
1709
+ * Records that a walk is starting at the state's current open depth, and
1710
+ * returns that depth. Called by `evaluate` / `evaluateAsync` on entry, under
1711
+ * their `hasHooks` guard, and paired with {@link popWalkBase} in a `finally`.
1712
+ *
1713
+ * The returned value is the same mark those entry points hand to
1714
+ * {@link unwindTo}, so they capture it once rather than reading the depth
1715
+ * twice.
1716
+ */
1717
+ pushWalkBase(state) {
1718
+ const bookkeeping = state.hookBookkeeping;
1719
+ const base = bookkeeping.open.length;
1720
+ bookkeeping.walkBases.push(base);
1721
+ return base;
1722
+ }
1723
+ /**
1724
+ * Drops the innermost walk base. Called from the `finally` of the `evaluate`
1725
+ * that pushed it, so an entry point whose walk threw still restores the
1726
+ * enclosing walk's bound.
1727
+ */
1728
+ popWalkBase(state) {
1729
+ state.hookBookkeeping.walkBases.pop();
1730
+ }
1731
+ /**
1732
+ * The open depth the innermost walk in progress started at, and the floor
1733
+ * {@link exit} will not reach below.
1734
+ *
1735
+ * Zero when no base has been pushed, which leaves `exit` behaving exactly as
1736
+ * it did before the bound existed - the correct answer for a walk that began
1737
+ * before any hook was registered, since it pushed no base.
1738
+ */
1739
+ walkBase(state) {
1740
+ const bases = state.hookBookkeeping.walkBases;
1741
+ return bases.length > 0 ? bases[bases.length - 1] : 0;
1742
+ }
1743
+ /**
1744
+ * Fires 'after' for every node the state has open above `mark`, innermost
1745
+ * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
1746
+ * visitor which throws still leaves every 'before' matched by exactly one
1747
+ * 'after'.
1748
+ *
1749
+ * Unwinding to a mark rather than to the bottom is what keeps a nested
1750
+ * `evaluate` from draining the enclosing walk's open nodes when a host
1751
+ * function swallows the nested throw.
1752
+ *
1753
+ * Idempotent, so the sync and async entry points can both call it.
1754
+ *
1755
+ * A hook that throws here cannot stop the drain: while unwinding, the 'throw'
1756
+ * policy is downgraded to 'collect' - evaluation has already failed, and the
1757
+ * original error is the one worth propagating.
1758
+ */
1759
+ unwindTo(mark, error, state) {
1760
+ const open = state.hookBookkeeping.open;
1761
+ while (open.length > mark) {
1762
+ const node = open.pop();
1763
+ if (!node) {
1764
+ break;
1765
+ }
1766
+ this.emit({ phase: 'after', node, state, completed: false, error }, true);
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Drains the state's whole open-node stack. Equivalent to `unwindTo(0, ...)`,
1771
+ * for callers that own the entire walk.
1772
+ */
1773
+ unwind(error, state) {
1774
+ this.unwindTo(0, error, state);
1775
+ }
1776
+ registry(phase) {
1777
+ return phase === 'before' ? this._before : this._after;
1778
+ }
1779
+ emit(event, unwinding) {
1780
+ const registry = this.registry(event.phase);
1781
+ if (registry.size === 0) {
1782
+ return;
1783
+ }
1784
+ this.invokeAll(registry.get(event.node.type), event, unwinding);
1785
+ this.invokeAll(registry.get('*'), event, unwinding);
1786
+ }
1787
+ /**
1788
+ * Iterates a copy so that a hook which unsubscribes itself does not shift the
1789
+ * list out from under the loop.
1790
+ */
1791
+ invokeAll(hooks, event, unwinding) {
1792
+ if (!hooks || hooks.length === 0) {
1793
+ return;
1794
+ }
1795
+ for (const hook of hooks.slice()) {
1796
+ this.invoke(hook, event, unwinding);
1797
+ }
1798
+ }
1799
+ invoke(hook, event, unwinding) {
1800
+ let result;
1801
+ try {
1802
+ result = hook(event);
1803
+ }
1804
+ catch (error) {
1805
+ this.handleError(event.state, event.phase, event.node.type, error, unwinding);
1806
+ return;
1807
+ }
1808
+ if (isPromiseLike(result)) {
1809
+ this.handleError(event.state, event.phase, event.node.type, new Error(ASYNC_HOOK_MESSAGE), unwinding);
1810
+ }
1811
+ }
1812
+ /**
1813
+ * The read counterpart of {@link invoke}. There is no unwinding equivalent
1814
+ * for reads - a read never opens a frame - so the policy always applies in
1815
+ * full.
1816
+ */
1817
+ invokeRead(hook, event) {
1818
+ let result;
1819
+ try {
1820
+ result = hook(event);
1821
+ }
1822
+ catch (error) {
1823
+ this.handleError(event.state, 'read', event.node.type, error, false);
1824
+ return;
1825
+ }
1826
+ if (isPromiseLike(result)) {
1827
+ this.handleError(event.state, 'read', event.node.type, new Error(ASYNC_HOOK_MESSAGE), false);
1828
+ }
1829
+ }
1830
+ handleError(state, phase, nodeType, error, unwinding) {
1831
+ if (this._policy === 'ignore') {
1832
+ return;
1833
+ }
1834
+ if (this._policy === 'throw' && !unwinding) {
1835
+ throw error;
1836
+ }
1837
+ state.hookBookkeeping.errors.push({ phase, nodeType, error });
1838
+ }
1839
+ }
1840
+
1841
+ /**
1842
+ * Creates a timing hook that accumulates inclusive per-node-type totals.
1843
+ *
1844
+ * Replaces the `console.time` / `console.timeEnd` pair the old `trackTime`
1845
+ * emitted, which mismatched its labels and produced no readable figure. The
1846
+ * readings are `performance.now()`, and nothing is written to the console.
1847
+ *
1848
+ * ```ts
1849
+ * const state = evalService.createState(context);
1850
+ * const off = createTimingHook().install(state.hooks);
1851
+ * evalService.eval('a + b * c', state);
1852
+ * state.nodeTimings.get('BinaryExpression'); // { count: 2, total: 0.081 }
1853
+ * off();
1854
+ * ```
1855
+ *
1856
+ * Equivalent to passing `{ trackTime: true }`, which installs one of these on
1857
+ * the state's own registry.
1858
+ *
1859
+ * @returns A handle whose `install` registers the pair on a registry.
1860
+ */
1861
+ const createTimingHook = () => {
1862
+ /**
1863
+ * Start times for the nodes this handle currently has open, per state.
1864
+ *
1865
+ * Keyed by state because one handle may be installed on a registry that
1866
+ * several evaluations dispatch through, and a shared stack would interleave
1867
+ * them. Weak, so a finished evaluation's state is collectable while the
1868
+ * consumer holds the handle. Per *handle* rather than module-level, so two
1869
+ * handles installed on one state cannot pop each other's readings.
1870
+ *
1871
+ * A stack works because `EvalHooks` guarantees exactly one 'after' *frame*
1872
+ * per 'before' frame, innermost first, on every exit path - including the
1873
+ * synthesised events `exit` flushes for stranded frames and the ones
1874
+ * `unwindTo` emits when a visitor throws. It has to be a stack rather than a
1875
+ * map keyed by node: an arrow-function body is re-walked on every call, so
1876
+ * the same node can be open more than once.
1877
+ *
1878
+ * The guarantee is about frames, not about hook *invocations*. Under the
1879
+ * 'throw' policy an earlier hook can abort `dispatch`'s emit loop after
1880
+ * `enter` has already run, so this push is skipped while the frame stays
1881
+ * open; the `unwindTo` that follows then pops an enclosing node's reading and
1882
+ * attributes it to the wrong type. Pops never outnumber pushes, so nothing
1883
+ * strands into a later run on the same state - and the evaluation has failed
1884
+ * regardless, which is why the totals are left as they fall.
1885
+ */
1886
+ const starts = new WeakMap();
1887
+ const stackFor = (state) => {
1888
+ const existing = starts.get(state);
1889
+ if (existing) {
1890
+ return existing;
1891
+ }
1892
+ const created = [];
1893
+ starts.set(state, created);
1894
+ return created;
1895
+ };
1896
+ const before = (event) => {
1897
+ stackFor(event.state).push(performance.now());
1898
+ };
1899
+ const after = (event) => {
1900
+ const started = starts.get(event.state)?.pop();
1901
+ if (started === undefined) {
1902
+ // No matching 'before'. Reachable when this handle was installed midway
1903
+ // through a walk, or when a throwing hook skipped the push above;
1904
+ // recording a total from an unknown start would be worse than skipping.
1905
+ return;
1906
+ }
1907
+ record(event.state, event.node.type, performance.now() - started);
1908
+ };
1909
+ return {
1910
+ install(hooks) {
1911
+ const offBefore = hooks.on('before', '*', before);
1912
+ const offAfter = hooks.on('after', '*', after);
1913
+ return () => {
1914
+ offBefore();
1915
+ offAfter();
1916
+ };
1917
+ }
1918
+ };
1919
+ };
1920
+ const record = (state, type, elapsed) => {
1921
+ const timings = state.hookBookkeeping.timings;
1922
+ const current = timings.get(type);
1923
+ timings.set(type, current
1924
+ ? { count: current.count + 1, total: current.total + elapsed }
1925
+ : { count: 1, total: elapsed });
1926
+ };
1927
+
1928
+ /**
1929
+ * Reads a caller-supplied hook registry out of the evaluation options.
1930
+ *
1931
+ * `EvalOptions` is a union and does not index directly, so the read goes
1932
+ * through a cast - the same one `before-visitor.ts` performs. The registry is
1933
+ * adopted as-is and never cloned: the caller holds the unsubscribe closures
1934
+ * `on` returned, and a copy would leave those closures editing a registry that
1935
+ * is no longer the one being dispatched.
1936
+ */
1937
+ const adoptHooks = (options) => {
1938
+ const value = options?.['hooks'];
1939
+ return value instanceof EvalHooks ? value : undefined;
1940
+ };
1941
+ /**
1942
+ * Whether the caller asked for per-node timings. Same cast, same reason.
1943
+ */
1944
+ const readTrackTime = (options) => !!options?.['trackTime'];
1945
+ /**
1946
+ * The iteration budget one evaluation gets when the caller names no other.
1947
+ *
1948
+ * Sized in the Phase 2 plan's § 3.4 rather than picked: a loop iteration is
1949
+ * roughly three walks at the measured ~1.4 M simple walks per second, so
1950
+ * ~2 microseconds, and 100,000 of them is ~0.2 s before the throw. Short enough
1951
+ * that a Jest spec fails fast rather than timing out at five seconds, and short
1952
+ * enough that a browser tab stutters rather than freezes - and far above any
1953
+ * expression a rule author writes by hand.
1954
+ */
1955
+ const DEFAULT_MAX_ITERATIONS = 100000;
1956
+ /**
1957
+ * The iteration budget the options ask for, or the default.
1958
+ *
1959
+ * Same cast as the two readers above, same reason. A non-numeric or negative
1960
+ * value falls back rather than throwing: options are a permissive record that
1961
+ * nothing validates, and the budget exists to bound a runaway loop, so a
1962
+ * malformed one must not become a *smaller* bound than the default by accident.
1963
+ * `0` is honoured - a caller forbidding loops entirely is a coherent thing to
1964
+ * ask for - and `Infinity` opts out, which is why the test is not
1965
+ * `Number.isFinite`.
1966
+ */
1967
+ const readMaxIterations = (options) => {
1968
+ const value = options?.['maxIterations'];
1969
+ return typeof value === 'number' && !Number.isNaN(value) && value >= 0
1970
+ ? value
1971
+ : DEFAULT_MAX_ITERATIONS;
1972
+ };
1973
+ /**
1974
+ * Represents the evaluation state, which includes the context, result, and options.
1975
+ */
1976
+ class EvalState {
1977
+ /**
1978
+ * Gets the evaluation context.
1979
+ */
1980
+ get context() {
1981
+ return this._context;
1982
+ }
1983
+ /**
1984
+ * Gets the evaluation result.
1985
+ */
1986
+ get result() {
1987
+ return this._result;
1988
+ }
1989
+ /**
1990
+ * Gets the evaluation options.
1991
+ */
1992
+ get options() {
1993
+ return this._options;
1994
+ }
1995
+ /**
1996
+ * Gets whether the evaluation is asynchronous.
1997
+ */
1998
+ get isAsync() {
1999
+ return this._isAsync;
2000
+ }
2001
+ /**
2002
+ * Gets the hook registry for this evaluation, creating an empty one on first
2003
+ * access. A registry supplied through `options.hooks` is adopted instead.
2004
+ *
2005
+ * Merely reading this does not turn {@link hasHooks} on; registering does.
2006
+ */
2007
+ get hooks() {
2008
+ return (this._hooks ??= new EvalHooks(this._options));
2009
+ }
2010
+ /**
2011
+ * The dispatch guard read by `beforeVisitor` / `afterVisitor`. One field read
2012
+ * and no options lookup, so the no-hooks path stays cheap.
2013
+ */
2014
+ get hasHooks() {
2015
+ return !!this._hooks && this._hooks.isActive;
2016
+ }
2017
+ /**
2018
+ * Errors raised by hooks during this evaluation and collected under the
2019
+ * 'collect' policy.
2020
+ *
2021
+ * They live here rather than on {@link hooks} because an `EvalHooks` may be
2022
+ * shared across evaluations, and an error describes one run.
2023
+ *
2024
+ * The array is the live one, so a reference taken before evaluating fills as
2025
+ * errors arrive. Returning a shared empty array until the first collection
2026
+ * would be cheaper by one allocation and wrong: the reference would silently
2027
+ * stop tracking the moment anything was collected.
2028
+ */
2029
+ get hookErrors() {
2030
+ return this.hookBookkeeping.errors;
2031
+ }
2032
+ /**
2033
+ * Per-node-type timings for **this state**, keyed by node type. Empty unless
2034
+ * a timing hook was installed - by `options.trackTime`, or by the caller
2035
+ * through `createTimingHook().install(state.hooks)`.
2036
+ *
2037
+ * Accumulates for the life of the state, not per `evaluate` call: under the
2038
+ * `createState` + repeated `eval` style the counts are the running totals
2039
+ * across every run on this state, which is what makes them comparable. A
2040
+ * caller who wants per-run figures uses a fresh state, or drops these along
2041
+ * with the rest of the run record via {@link resetHookBookkeeping}.
2042
+ *
2043
+ * Here rather than on the handle `createTimingHook` returns for the same
2044
+ * reason {@link hookErrors} is: timings describe one run, and an `EvalHooks`
2045
+ * may be handed to several. It is also the only place a `trackTime` caller
2046
+ * could reach them, since that installation happens in this constructor and
2047
+ * hands the handle to nobody.
2048
+ *
2049
+ * Totals are inclusive of child nodes; see `EvalNodeTiming`.
2050
+ */
2051
+ get nodeTimings() {
2052
+ return this.hookBookkeeping.timings;
2053
+ }
2054
+ /**
2055
+ * The per-run bookkeeping `EvalHooks` reads and writes: the open-node stack
2056
+ * and the collected errors, grouped behind a single accessor.
2057
+ *
2058
+ * The state owns this storage and `eval-hooks.ts` only type-imports the
2059
+ * state, which keeps the runtime import graph acyclic. Holding it in a
2060
+ * module-private `WeakMap` inside `eval-hooks.ts` was the alternative and was
2061
+ * rejected: `hookErrors` would then need a *runtime* import of that module
2062
+ * while it already imports this one, and the resulting cycle is a hazard in
2063
+ * the ng-packagr build.
2064
+ *
2065
+ * @internal Not part of the published API.
2066
+ */
2067
+ get hookBookkeeping() {
2068
+ return (this._hookBookkeeping ??=
2069
+ { open: [], errors: [], timings: new Map(), walkBases: [] });
2070
+ }
2071
+ /**
2072
+ * How many `evaluate` / `evaluateAsync` calls on this state are currently on
2073
+ * the JavaScript stack: 0 between evaluations, 1 during an ordinary walk, and
2074
+ * more while a nested walk runs - an arrow-function body is re-entrant
2075
+ * `evaluate` on this same state.
2076
+ *
2077
+ * Maintained by {@link enterWalk} / {@link exitWalk}, which the entry points
2078
+ * pair around their walk, the exit in a `finally` so a throw still restores
2079
+ * the count.
2080
+ *
2081
+ * **Deliberately not merged with `EvalHookBookkeeping.walkBases`**, which
2082
+ * tracks the same nesting one level down. That stack is pushed only under
2083
+ * {@link hasHooks}, because bounding `EvalHooks.exit` is meaningless with no
2084
+ * hooks to dispatch; this counter must be maintained unconditionally, because
2085
+ * § 3.4's iteration budget refills on the outermost entry and a loop is
2086
+ * bounded whether or not anyone is listening. One field cannot be both
2087
+ * guarded and unguarded, so there are two.
2088
+ *
2089
+ * @internal Not part of the published API.
2090
+ */
2091
+ get walkDepth() {
2092
+ return this._walkDepth;
2093
+ }
2094
+ /**
2095
+ * Records that a walk is starting on this state and returns the new depth, so
2096
+ * a caller can recognise the outermost entry as `=== 1` without a second
2097
+ * read.
2098
+ *
2099
+ * **Refills {@link iterationsRemaining} on the outermost entry**, which is
2100
+ * what makes § 3.4's budget per-`evaluate` rather than per-state. It happens
2101
+ * here rather than at the entry points so that both of them - and any later
2102
+ * one - get it without a second copy of the 0 -> 1 test; the depth this
2103
+ * method already owns is the only thing the decision needs.
2104
+ *
2105
+ * @internal Not part of the published API.
2106
+ */
2107
+ enterWalk() {
2108
+ const depth = ++this._walkDepth;
2109
+ // § 3.4's refill, and the 0 -> 1 test is the whole of it. A nested walk -
2110
+ // an arrow-function body, which re-enters `evaluate` on this same state -
2111
+ // shares whatever the enclosing walk has left, so an escaped closure cannot
2112
+ // buy itself a fresh budget by being called again. The options are re-read
2113
+ // per outermost walk rather than in the constructor because they are a
2114
+ // mutable record the caller keeps a reference to.
2115
+ if (depth === 1) {
2116
+ this._iterationBudget = readMaxIterations(this._options);
2117
+ this._iterationsRemaining = this._iterationBudget;
2118
+ }
2119
+ return depth;
2120
+ }
2121
+ /**
2122
+ * Records that a walk has finished. Called from the entry point's `finally`.
2123
+ *
2124
+ * @internal Not part of the published API.
2125
+ */
2126
+ exitWalk() {
2127
+ this._walkDepth--;
2128
+ }
2129
+ /**
2130
+ * How many loop iterations this evaluation may still run.
2131
+ *
2132
+ * Refilled by {@link enterWalk} on the outermost entry from
2133
+ * `options.maxIterations`, defaulting to 100,000, and spent one at a time by
2134
+ * {@link chargeIteration}. `Infinity` when the caller opted out.
2135
+ *
2136
+ * Readable mainly so a spec can assert what a walk charged: nothing in the
2137
+ * library reads it except {@link chargeIteration}, and no expression without a
2138
+ * `for` in it moves it.
2139
+ *
2140
+ * @internal Not part of the published API.
2141
+ */
2142
+ get iterationsRemaining() {
2143
+ return this._iterationsRemaining;
2144
+ }
1193
2145
  /**
1194
- * Gets the evaluation context.
2146
+ * Charges one loop iteration against the budget, throwing when it is spent.
2147
+ *
2148
+ * Called from `for-statement.ts`'s iteration loop and **nowhere else**, which
2149
+ * is § 3.4's cost argument in its literal form: the no-loop path does not
2150
+ * execute a cheaper version of this check, it does not reach the call site at
2151
+ * all. The rejected alternative - a per-node fuel counter in `beforeVisitor` -
2152
+ * would have been on the hot path of every evaluation in the library, to bound
2153
+ * a recursion depth this phase does not introduce.
2154
+ *
2155
+ * The message names the **configured** budget rather than the default, since a
2156
+ * caller who set `maxIterations` needs to recognise their own number in it.
2157
+ *
2158
+ * @internal Not part of the published API.
1195
2159
  */
1196
- get context() {
1197
- return this._context;
2160
+ chargeIteration() {
2161
+ if (this._iterationsRemaining <= 0) {
2162
+ throw new Error(`Iteration budget exhausted after ${this._iterationBudget} iterations`);
2163
+ }
2164
+ this._iterationsRemaining--;
1198
2165
  }
1199
2166
  /**
1200
- * Gets the evaluation result.
2167
+ * Records that `key` was declared `const` in `scope`, so a later write to it
2168
+ * can be rejected.
2169
+ *
2170
+ * **Keyed by the scope *object*, and beside the scope rather than in it.** A
2171
+ * metadata key written onto the scope record would itself be resolvable as a
2172
+ * binding name - `getContextValue` reads the same surface a declaration binds
2173
+ * into - so `let __kind` would be readable from an expression. A `WeakMap`
2174
+ * hanging off the state has neither problem, and it is checked at the write
2175
+ * site only, so reads pay nothing.
2176
+ *
2177
+ * **The scope passed here must be the one on the stack**, not the record a
2178
+ * visitor built to push: `EvalContext.push` routes through `fromContext`,
2179
+ * which *copies* a plain record into a `Registry` when `caseInsensitive` is
2180
+ * set. Keying on the pre-push record would file every `const` under an object
2181
+ * the write site can never produce, and `caseInsensitive` alone would lose
2182
+ * const-ness silently. `EvalContext.scopeHolding` returns the stack's object,
2183
+ * which is what both sides use.
2184
+ *
2185
+ * The entries die with the scopes: scope objects are created per block entry
2186
+ * and dropped when the block exits, so nothing here outlives the walk even
2187
+ * though the state may.
2188
+ *
2189
+ * @internal Not part of the published API.
1201
2190
  */
1202
- get result() {
1203
- return this._result;
2191
+ declareConst(scope, key) {
2192
+ const bindings = (this._constBindings ??= new WeakMap());
2193
+ const keys = bindings.get(scope);
2194
+ if (keys) {
2195
+ keys.add(key);
2196
+ }
2197
+ else {
2198
+ bindings.set(scope, new Set([key]));
2199
+ }
1204
2200
  }
1205
2201
  /**
1206
- * Gets the evaluation options.
2202
+ * Whether `key` was declared `const` in `scope`.
2203
+ *
2204
+ * Asked by `assignment-expression.ts` and `update-expression.ts` of the scope
2205
+ * the write is about to land in, so an inner `let` of a name an outer scope
2206
+ * declared `const` stays writable - the kind belongs to the binding, not to
2207
+ * the name.
2208
+ *
2209
+ * @internal Not part of the published API.
1207
2210
  */
1208
- get options() {
1209
- return this._options;
2211
+ isConstBinding(scope, key) {
2212
+ return !!this._constBindings?.get(scope)?.has(key);
1210
2213
  }
1211
2214
  /**
1212
- * Gets whether the evaluation is asynchronous.
2215
+ * Drops every per-run record this state holds: the collected hook errors, the
2216
+ * open-node stack, the accumulated timings, and the walk bases bounding
2217
+ * `EvalHooks.exit`.
2218
+ *
2219
+ * It resets the whole record rather than only the errors, which is why it is
2220
+ * not named for them. `EvalHooks.clear` cannot reach any of this - the
2221
+ * bookkeeping belongs to the state - so without this method nothing drains
2222
+ * the open-node stack at all. Frames left on it keep their AST nodes
2223
+ * reachable for as long as the state is, and `EvalService` holds its states
2224
+ * in a strong `Set`.
2225
+ *
2226
+ * The errors matter for the same reason under the state-first style:
2227
+ * `createState` plus repeated `eval` on one state accumulates them for the
2228
+ * life of that state, and a thrown value can close over consumer objects.
2229
+ *
2230
+ * The record is replaced rather than emptied in place, so a caller still
2231
+ * holding the array {@link hookErrors} handed out keeps its own contents and
2232
+ * simply stops tracking - the alternative would mutate a collection the
2233
+ * caller owns a reference to.
2234
+ *
2235
+ * Calling this mid-walk is unsupported for the same reason `EvalHooks.clear`
2236
+ * is: it abandons frames the dispatcher expects to close.
1213
2237
  */
1214
- get isAsync() {
1215
- return this._isAsync;
2238
+ resetHookBookkeeping() {
2239
+ this._hookBookkeeping = undefined;
1216
2240
  }
1217
2241
  /**
1218
2242
  * Represents the state of an evaluation.
@@ -1222,10 +2246,28 @@ class EvalState {
1222
2246
  * @param isAsync Indicates whether the evaluation is asynchronous.
1223
2247
  */
1224
2248
  constructor(context, result, options, isAsync) {
2249
+ this._walkDepth = 0;
2250
+ this._iterationBudget = DEFAULT_MAX_ITERATIONS;
2251
+ this._iterationsRemaining = DEFAULT_MAX_ITERATIONS;
1225
2252
  this._context = context;
1226
2253
  this._result = result;
1227
2254
  this._options = options;
1228
2255
  this._isAsync = isAsync;
2256
+ this._hooks = adoptHooks(options);
2257
+ // Options configure the registry this state owns, never an adopted one -
2258
+ // the same rule `onHookError` follows, and for the same reason: an adopted
2259
+ // `EvalHooks` belongs to the caller, and installing into it would leave a
2260
+ // hook firing on every later evaluation they run through it, with the
2261
+ // unsubscribe this call discards as the only way off. A caller who wants
2262
+ // both passes their own registry and installs the hook on it themselves.
2263
+ if (!this._hooks && readTrackTime(options)) {
2264
+ // Registering here rather than lazily means `isActive` has latched before
2265
+ // the walk starts, so every node dispatches for its whole duration. That
2266
+ // is what was asked for: per-node-type totals cannot be had without
2267
+ // visiting each node, and `EvalResult.duration` already covers the
2268
+ // cheaper walk-level question.
2269
+ createTimingHook().install(this.hooks);
2270
+ }
1229
2271
  }
1230
2272
  /**
1231
2273
  * Creates an instance of EvalState from a given context, options, and async flag.
@@ -1273,24 +2315,41 @@ const popVisitorResultAsync = (node, st) => {
1273
2315
  return value;
1274
2316
  };
1275
2317
 
2318
+ /**
2319
+ * Opens a node: records it as open and fires the registered 'before' hooks.
2320
+ *
2321
+ * Called at the top of every visitor body. The guard is a single boolean field
2322
+ * read - no options lookup - so an evaluation with no hooks pays almost
2323
+ * nothing, and it wraps the open-node bookkeeping as well as the hooks
2324
+ * themselves so `enter` and `exit` cannot become unpaired mid-walk.
2325
+ */
1276
2326
  const beforeVisitor = (node, st) => {
1277
- const options = st.options;
1278
- if (options?.['trackTime']) {
1279
- const t = performance.now();
1280
- console.time('before: ' + node.type);
1281
- return t;
2327
+ if (!st.hasHooks) {
2328
+ return;
1282
2329
  }
1283
- return undefined;
2330
+ st.hooks.dispatch('before', node, st);
1284
2331
  };
1285
2332
 
2333
+ /**
2334
+ * Closes a node: pops it off the open-node stack and fires the registered
2335
+ * 'after' hooks.
2336
+ *
2337
+ * The event's `value` is read **positionally** - it is whatever sits on top of
2338
+ * the result stack right now, not something keyed to this node. Reading it here
2339
+ * is what makes the value available without changing any visitor's call
2340
+ * signature, and it is correct for every visitor that pushes its result
2341
+ * immediately before calling this. A visitor that reaches this without pushing
2342
+ * would report its *neighbour's* value, not `undefined`; the length check below
2343
+ * only guards the empty stack, since `Stack.peek` is non-destructive but does
2344
+ * not bounds-check.
2345
+ */
1286
2346
  const afterVisitor = (node, st) => {
1287
- const options = st.options;
1288
- if (options?.['trackTime']) {
1289
- const t = performance.now();
1290
- console.time('after: ' + node.type);
1291
- return t;
2347
+ if (!st.hasHooks) {
2348
+ return;
1292
2349
  }
1293
- return undefined;
2350
+ const stack = st.result?.stack;
2351
+ const value = stack && stack.length > 0 ? stack.peek() : undefined;
2352
+ st.hooks.dispatch('after', node, st, value);
1294
2353
  };
1295
2354
 
1296
2355
  var RecursiveVisitorResultType;
@@ -1305,24 +2364,75 @@ const literals = Registry.fromObject({
1305
2364
  'true': true,
1306
2365
  'false': false,
1307
2366
  }, { caseInsensitive: true });
2367
+ /**
2368
+ * Reports a resolved identifier read to the hook layer.
2369
+ *
2370
+ * The key is the one the context actually matched, so a case-insensitive
2371
+ * lookup reports the corrected spelling; `getKey` returns undefined for a name
2372
+ * the context does not hold - a literal-registry resolution, or a miss - and
2373
+ * the source name stands in. The path is always the source spelling, since it
2374
+ * is reconstructed statically.
2375
+ *
2376
+ * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
2377
+ * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
2378
+ * tests for the binding rather than for its value: a parameter bound to
2379
+ * `undefined` is still a parameter, and reading the flag off the resolved value
2380
+ * would make it vary with the data rather than with the expression.
2381
+ *
2382
+ * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
2383
+ * long-lived objects and are real dependencies, so the discriminator is
2384
+ * lifetime rather than `instanceof EvalScope`. The property is omitted rather
2385
+ * than set to false, so absent reads as "not scoped" the same way it does at
2386
+ * the member emission sites.
2387
+ *
2388
+ * The scope stack is empty for any expression without an arrow function, and
2389
+ * `Stack.asArray` allocates, so the common case is short-circuited on length.
2390
+ */
2391
+ const emitRead = (node, st, value) => {
2392
+ const key = st.context?.getKey(node.name) ?? node.name;
2393
+ const scoped = !!st.context
2394
+ && st.context.scopes.length > 0
2395
+ && st.context.hasInScopes(node.name);
2396
+ st.hooks.dispatchRead({
2397
+ kind: 'identifier',
2398
+ node,
2399
+ state: st,
2400
+ key,
2401
+ target: st.context,
2402
+ path: node.name,
2403
+ value,
2404
+ ...(scoped ? { scoped: true } : {})
2405
+ });
2406
+ };
1308
2407
  const identifierVisitor = (node, st) => {
1309
2408
  if (st.options?.caseInsensitive) {
1310
2409
  return identifierVisitorCaseInsensitive(node, st);
1311
2410
  }
1312
2411
  beforeVisitor(node, st);
1313
2412
  const context = st.context;
1314
- const value = node.name === 'this'
2413
+ const isThis = node.name === 'this';
2414
+ const value = isThis
1315
2415
  ? st.context
1316
2416
  : context?.get(node.name);
2417
+ // `this` resolves to the context object itself rather than to a key within
2418
+ // it, so it is not a read: reporting it would have a dependency tracker
2419
+ // record the whole context and re-fire on every change to it.
2420
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2421
+ emitRead(node, st, value);
2422
+ }
1317
2423
  pushVisitorResult(node, st, value);
1318
2424
  afterVisitor(node, st);
1319
2425
  };
1320
2426
  const identifierVisitorCaseInsensitive = (node, st) => {
1321
2427
  beforeVisitor(node, st);
1322
2428
  const context = st.context;
1323
- const value = equalIgnoreCase(node.name, 'this')
2429
+ const isThis = !!equalIgnoreCase(node.name, 'this');
2430
+ const value = isThis
1324
2431
  ? st.context
1325
2432
  : context?.get(node.name) ?? literals.get(node.name);
2433
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2434
+ emitRead(node, st, value);
2435
+ }
1326
2436
  pushVisitorResult(node, st, value);
1327
2437
  afterVisitor(node, st);
1328
2438
  };
@@ -1834,6 +2944,37 @@ function getPropertyLookupCacheStats() {
1834
2944
  }
1835
2945
 
1836
2946
  // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
2947
+ /**
2948
+ * Reconstructs the dotted source path of a member chain (`a.b.c`).
2949
+ *
2950
+ * Static only: a computed hop (`a[expr]`, `a["b"]`) leaves the path
2951
+ * unreconstructible and yields undefined, and a consumer falls back to
2952
+ * `target` + `key` identity - which is exact either way. The parts are source
2953
+ * spellings, so under `caseInsensitive` the path is not corrected even though
2954
+ * the reported key is; optional markers are not represented either, so `a?.b`
2955
+ * reconstructs as `a.b`. A chain rooted at anything but an `Identifier` - a
2956
+ * `this`, a call, a `super` - yields undefined.
2957
+ *
2958
+ * Walks the chain once per member read, so every call site sits behind
2959
+ * `st.hasHooks && st.hooks.hasReadHooks`: a consumer that registered only node
2960
+ * hooks must not pay for a path it can never observe.
2961
+ */
2962
+ const readPath = (node) => {
2963
+ const parts = [];
2964
+ let current = node;
2965
+ while (current.type === 'MemberExpression') {
2966
+ if (current.computed || current.property.type !== 'Identifier') {
2967
+ return undefined;
2968
+ }
2969
+ parts.unshift(current.property.name);
2970
+ current = current.object;
2971
+ }
2972
+ if (current.type !== 'Identifier') {
2973
+ return undefined;
2974
+ }
2975
+ parts.unshift(current.name);
2976
+ return parts.join('.');
2977
+ };
1837
2978
  const memberExpressionVisitor = (node, st, callback) => {
1838
2979
  beforeVisitor(node, st);
1839
2980
  // Disable visitor result caching for now due to context sensitivity issues
@@ -1877,17 +3018,42 @@ const evaluateMember = (node, st, callback) => {
1877
3018
  : key;
1878
3019
  const value = st.context.get(contextKey);
1879
3020
  const thisValue = st.context.getThis(contextKey);
3021
+ if (st.hasHooks && st.hooks.hasReadHooks) {
3022
+ st.hooks.dispatchRead({
3023
+ kind: 'member',
3024
+ node,
3025
+ state: st,
3026
+ key: contextKey ?? key,
3027
+ target: st.context,
3028
+ path: readPath(node),
3029
+ value
3030
+ });
3031
+ }
1880
3032
  return [thisValue ?? object, contextKey, value];
1881
3033
  }
1882
3034
  else if (object instanceof EvalScope) {
1883
3035
  // For scope objects, preserve original behavior (no getKey method)
1884
3036
  const value = object.get(key);
1885
3037
  const thisValue = object;
3038
+ if (st.hasHooks && st.hooks.hasReadHooks) {
3039
+ st.hooks.dispatchRead({
3040
+ kind: 'member',
3041
+ node,
3042
+ state: st,
3043
+ key,
3044
+ target: object,
3045
+ path: readPath(node),
3046
+ value
3047
+ });
3048
+ }
1886
3049
  return [thisValue ?? object, key, value];
1887
3050
  }
1888
3051
  else {
1889
3052
  // For regular objects, we need both case-insensitive lookup AND prototype pollution protection
1890
3053
  let value;
3054
+ // The key the lookup actually matched, reported to the read hooks. The
3055
+ // returned tuple keeps the original `key`; only the event is corrected.
3056
+ let resolvedKey = key;
1891
3057
  // Check if this is a primitive type (string, number, boolean) - these are safe for method access
1892
3058
  const isPrimitive = (typeof object === 'string' || typeof object === 'number' || typeof object === 'boolean');
1893
3059
  if (st.options?.caseInsensitive && typeof key === 'string') {
@@ -1947,6 +3113,9 @@ const evaluateMember = (node, st, callback) => {
1947
3113
  // For objects, use safe property access
1948
3114
  value = foundKey ? obj[foundKey] : safeGetProperty(object, key);
1949
3115
  }
3116
+ if (foundKey) {
3117
+ resolvedKey = foundKey;
3118
+ }
1950
3119
  }
1951
3120
  else {
1952
3121
  // Use safe property access for prototype pollution protection (but not for primitives)
@@ -1958,6 +3127,17 @@ const evaluateMember = (node, st, callback) => {
1958
3127
  value = safeGetProperty(object, key);
1959
3128
  }
1960
3129
  }
3130
+ if (st.hasHooks && st.hooks.hasReadHooks) {
3131
+ st.hooks.dispatchRead({
3132
+ kind: 'member',
3133
+ node,
3134
+ state: st,
3135
+ key: resolvedKey,
3136
+ target: object,
3137
+ path: readPath(node),
3138
+ value
3139
+ });
3140
+ }
1961
3141
  return [object, key, value];
1962
3142
  }
1963
3143
  };
@@ -2523,9 +3703,374 @@ const getDefaultVisitors = () => {
2523
3703
  visitors['AssignmentExpression'] = assignmentExpressionVisitor;
2524
3704
  visitors['UpdateExpression'] = updateExpressionVisitor;
2525
3705
  visitors['ArrowFunctionExpression'] = arrowFunctionExpressionVisitor;
3706
+ // The statement family. `Program` is the root of every walk that arrives
3707
+ // through `EvalService`, whose parser options leave `extractExpressions` off.
3708
+ visitors['Program'] = programVisitor;
3709
+ visitors['ExpressionStatement'] = expressionStatementVisitor;
3710
+ visitors['EmptyStatement'] = emptyStatementVisitor;
3711
+ visitors['BlockStatement'] = blockStatementVisitor;
3712
+ visitors['VariableDeclaration'] = variableDeclarationVisitor;
3713
+ visitors['IfStatement'] = ifStatementVisitor;
3714
+ visitors['ForStatement'] = forStatementVisitor;
2526
3715
  return visitors;
2527
3716
  };
2528
3717
 
3718
+ // based on evalArrowContext
3719
+ // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
3720
+ /**
3721
+ * The one answer this module gives to a binding target it does not implement.
3722
+ *
3723
+ * Both entry points used to fall out of their `switch` and return an empty
3724
+ * context - `evaluatePatterns` past a `case`-less type, `evaluatePattern` past
3725
+ * the `return {}` at the end - so `let { a = 1 } = o` and `((a = 1) => a)(x)`
3726
+ * bound nothing, threw nothing, and left the caller to read the miss as a
3727
+ * value. That is the shape `docs/backlog.md` A2 records three instances of in
3728
+ * the two write visitors, and Phase 2 requires a throwing `default:` in every
3729
+ * new statement dispatcher; a phase that promises not to add a fourth member of
3730
+ * that family cannot leave this one open either.
3731
+ *
3732
+ * `AssignmentPattern` is the reachable case - it is commented out below - and
3733
+ * the message names the node type so a consumer can tell which form was
3734
+ * rejected.
3735
+ */
3736
+ const unsupportedBindingTarget = (type) => {
3737
+ throw new Error(`${type} is not supported as a binding target.`);
3738
+ };
3739
+ const evaluatePatterns = (patterns, st, callback, args) => {
3740
+ let context = {};
3741
+ patterns.map((pattern, i) => {
3742
+ switch (pattern.type) {
3743
+ case 'Identifier':
3744
+ {
3745
+ const object = evaluateIdentifier(pattern, st, args[i]);
3746
+ context = { ...context, ...object };
3747
+ }
3748
+ break;
3749
+ case 'MemberExpression':
3750
+ {
3751
+ const object = evaluateMemberExpression(pattern);
3752
+ context = { ...context, ...object };
3753
+ }
3754
+ break;
3755
+ case 'ObjectPattern':
3756
+ {
3757
+ const object = evaluateObjectPattern(pattern, st, callback, args[i]);
3758
+ context = { ...context, ...object };
3759
+ }
3760
+ break;
3761
+ case 'ArrayPattern':
3762
+ {
3763
+ const object = evaluateArrayPattern(pattern, st, callback, args[i]);
3764
+ context = { ...context, ...object };
3765
+ }
3766
+ break;
3767
+ case 'RestElement':
3768
+ {
3769
+ const object = evaluateRestElement(pattern, st, callback, args.slice(i));
3770
+ context = { ...context, ...object };
3771
+ }
3772
+ break;
3773
+ // case 'AssignmentPattern': {
3774
+ // const object = evaluateAssignmentPattern(pattern, st, callback, args[i]);
3775
+ // context = {...context, ...object};
3776
+ // }
3777
+ // break;
3778
+ default:
3779
+ unsupportedBindingTarget(pattern.type);
3780
+ }
3781
+ });
3782
+ return context;
3783
+ };
3784
+ const evaluatePattern = (pattern, st, callback, arg) => {
3785
+ switch (pattern.type) {
3786
+ case 'Identifier':
3787
+ return evaluateIdentifier(pattern, st, arg);
3788
+ case 'MemberExpression':
3789
+ return evaluateMemberExpression(pattern);
3790
+ case 'ObjectPattern':
3791
+ return evaluateObjectPattern(pattern, st, callback, arg);
3792
+ case 'ArrayPattern':
3793
+ return evaluateArrayPattern(pattern, st, callback, arg);
3794
+ case 'RestElement':
3795
+ return evaluateRestElement(pattern, st, callback, arg);
3796
+ // case 'AssignmentPattern':
3797
+ // return evaluateAssignmentPattern(pattern, st, callback, arg);
3798
+ }
3799
+ return unsupportedBindingTarget(pattern.type);
3800
+ };
3801
+ // The binding write goes through the prototype-pollution guard, for the reason
3802
+ // the other three guarded visitors do: on a plain record `__proto__` is a
3803
+ // setter, so `let __proto__ = { … }` and `({ __proto__ }) => …` would replace
3804
+ // this object's prototype instead of naming a binding. Declarations are a new
3805
+ // way to reach this line - before Phase 2 only an arrow parameter did - so the
3806
+ // surface widened and the guard is what keeps the blocklist covering it.
3807
+ const evaluateIdentifier = (pattern, st, arg) => {
3808
+ const object = {};
3809
+ safeSetProperty(object, pattern.name, arg);
3810
+ return object;
3811
+ };
3812
+ // Module-private, and down to the one parameter it reads: deleting the log
3813
+ // below left `st`, `callback` and `arg` unused, and the two call sites are both
3814
+ // in this file.
3815
+ const evaluateMemberExpression = (pattern) => {
3816
+ if (pattern.type === 'MemberExpression') {
3817
+ // The node type is the only part of this a caller could act on. What stood
3818
+ // here before was `console.log(pattern, st, callback, arg)` - `st` being the
3819
+ // whole EvalState, i.e. the caller's entire evaluation context dumped to the
3820
+ // console of any application whose user wrote that pattern. Unreachable
3821
+ // today because acorn rejects a MemberExpression binding target in a
3822
+ // parameter list, and deleted ahead of the work that widens what reaches
3823
+ // here. See docs/backlog.md B2.
3824
+ throw new Error(`${pattern.type} is not supported as a binding target.`);
3825
+ }
3826
+ return {};
3827
+ };
3828
+ const evaluateObjectPattern = (pattern, st, callback, arg) => {
3829
+ let context = {};
3830
+ pattern.properties.map((pattern) => {
3831
+ switch (pattern.type) {
3832
+ case 'Property':
3833
+ {
3834
+ let key;
3835
+ if (pattern.key.type === 'Identifier') {
3836
+ key = pattern.key.name;
3837
+ }
3838
+ else if (pattern.key.type === 'Literal') {
3839
+ key = pattern.key.value;
3840
+ }
3841
+ else {
3842
+ callback(pattern.key, st);
3843
+ key = popVisitorResult(pattern, st);
3844
+ if (typeof key !== 'string' && typeof key !== 'number')
3845
+ throw new Error(`Unsupported property key type: ${pattern.key.type}`);
3846
+ }
3847
+ // **Where `let { a = 1 } = o` actually lands**, which is not where
3848
+ // it was expected to. A default in an object pattern is parsed as
3849
+ // `Property.value` of type `AssignmentPattern` - so it is handed to
3850
+ // `callback` below and walked as an *expression*, and reaches neither
3851
+ // of this module's two `switch` defaults. Rejecting it there would
3852
+ // have left the object form of the very example that names the
3853
+ // divergence still binding silently; the array form
3854
+ // (`let [a = 1] = arr`) and the parameter form (`(a = 1) => a`) do go
3855
+ // through `evaluatePatterns`, and are covered there.
3856
+ if (pattern.value.type === 'AssignmentPattern') {
3857
+ unsupportedBindingTarget(pattern.value.type);
3858
+ }
3859
+ const ctx = arg;
3860
+ // `finally`, for the reason given at the other push site in
3861
+ // arrow-function-expression.ts: the scope stack is on EvalContext,
3862
+ // which outlives this walk, so a scope left behind here shadows a
3863
+ // source key on every later evaluation against the same context.
3864
+ // The `try` opens after the push, never around it.
3865
+ st.context?.push(ctx);
3866
+ let value;
3867
+ try {
3868
+ callback(pattern.value, st);
3869
+ value = popVisitorResult(pattern, st);
3870
+ }
3871
+ finally {
3872
+ st.context?.pop();
3873
+ }
3874
+ // Guarded for the same reason `evaluateIdentifier` is: the key comes
3875
+ // from the *pattern*, so `let { __proto__: p } = o` names `__proto__`
3876
+ // here and a raw assignment would set this record's prototype.
3877
+ const pair = {};
3878
+ safeSetProperty(pair, key, value);
3879
+ context = { ...context, ...pair };
3880
+ }
3881
+ break;
3882
+ case 'RestElement':
3883
+ {
3884
+ const object = evaluateRestElement(pattern, st, callback, arg);
3885
+ context = { ...context, ...object };
3886
+ }
3887
+ break;
3888
+ }
3889
+ });
3890
+ return context;
3891
+ };
3892
+ const evaluateArrayPattern = (pattern, st, callback, args) => {
3893
+ const patterns = pattern.elements.filter(s => !!s);
3894
+ const object = evaluatePatterns(patterns, st, callback, args);
3895
+ return object;
3896
+ };
3897
+ const evaluateRestElement = (pattern, st, callback, args) => {
3898
+ const argument = pattern.argument;
3899
+ const object = evaluatePattern(argument, st, callback, args);
3900
+ return object;
3901
+ };
3902
+ // const evaluateAssignmentPattern = (pattern: AssignmentPattern, st: EvalState, callback: walk.WalkerCallback<EvalState>, args: unknown) => {
3903
+ // const left = evaluatePattern(pattern.left, st, callback, args);
3904
+ // callback(pattern.right, st);
3905
+ // const value = popVisitorResult(pattern, st);
3906
+ // const object = {...left};
3907
+ // return object;
3908
+ // }
3909
+
3910
+ /**
3911
+ * The scope a declaration binds into: the innermost one on the stack.
3912
+ *
3913
+ * Read back from the stack rather than kept as a reference by whoever pushed
3914
+ * it, and that is the load-bearing half. `EvalContext.push` routes through
3915
+ * `fromContext`, which **copies** a plain record into a `Registry` when
3916
+ * `caseInsensitive` is set - so the object a visitor handed to `push` is not
3917
+ * always the object on the stack, and a binding written through the pre-push
3918
+ * record would be written into something nothing ever reads. It is also the
3919
+ * object `EvalState.declareConst` keys on, so both sides have to agree about
3920
+ * which one it is.
3921
+ *
3922
+ * Every route into a declaration pushes one first - `Program` for the top level,
3923
+ * `BlockStatement` for a block - so the absent case means the caller walked a
3924
+ * bare declaration node. Throwing is the answer rather than falling back to
3925
+ * `EvalContext.set`, which would write the caller's own context object: a `let`
3926
+ * that mutates the consumer's data is the behaviour this step exists to remove,
3927
+ * and doing it on an unsupported entry path would be the one place it survived.
3928
+ */
3929
+ const bindingScope = (st) => {
3930
+ const scope = st.context && st.context.scopes.length > 0
3931
+ ? st.context.scopes.peek()
3932
+ : undefined;
3933
+ if (!scope) {
3934
+ throw new Error('A variable declaration requires an enclosing scope.');
3935
+ }
3936
+ return scope;
3937
+ };
3938
+ /**
3939
+ * Binds one declarator's names into `scope`.
3940
+ *
3941
+ * The names come from `evaluatePattern`, which is the binder arrow-function
3942
+ * parameters already use - `Identifier` for the plain form, and the
3943
+ * `ObjectPattern` / `ArrayPattern` / `RestElement` forms for the destructuring
3944
+ * ones. Reusing it is what makes `let [p, q] = arr` work without a second
3945
+ * pattern implementation, and what makes a form it does not implement throw
3946
+ * (`AssignmentPattern`, i.e. `let { a = 1 } = o`) rather than bind nothing.
3947
+ *
3948
+ * The keys are re-checked against the pollution blocklist even though
3949
+ * `evaluatePattern` already wrote them through `safeSetProperty`. One line for
3950
+ * a guard that cannot be reasoned away from this call site: the record arrives
3951
+ * as a `BaseContext`, and the binder's own coverage of it is a property of
3952
+ * `pattern.ts` rather than of this module's contract with it.
3953
+ *
3954
+ * The write itself dispatches through `setContextValue`, not through
3955
+ * `safeSetProperty`. `safeSetProperty` finishes with `Object.defineProperty`,
3956
+ * which suits the plain records `pattern.ts` builds and **not** a scope: a
3957
+ * `caseInsensitive` scope is a Map-backed `Registry`, and defining a property
3958
+ * on the instance inserts nothing into its map. The binding would be written
3959
+ * and then not found, silently, for that option only.
3960
+ */
3961
+ const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
3962
+ const bindings = evaluatePattern(declarator.id, st, callback, value);
3963
+ for (const key of Object.keys(bindings)) {
3964
+ if (isDangerousProperty(key)) {
3965
+ throw new Error(`Access to dangerous property "${key}" is blocked for security reasons`);
3966
+ }
3967
+ setContextValue(scope, key, bindings[key]);
3968
+ if (kind === 'const') {
3969
+ st.declareConst(scope, key);
3970
+ }
3971
+ }
3972
+ };
3973
+ /**
3974
+ * Evaluates a variable declaration: `let` and `const`, in the plain and
3975
+ * destructuring forms.
3976
+ *
3977
+ * Pushes {@link EMPTY_COMPLETION} on every exit path - a declaration produces no
3978
+ * completion value in JavaScript, and the sentinel rather than `undefined` is
3979
+ * what keeps `let x = 1` from winning over an earlier statement's value inside a
3980
+ * block. Pops one value per declarator that has an initialiser, and none for one
3981
+ * that does not, which is the arithmetic § 3.1's table states for this visitor.
3982
+ *
3983
+ * **No hoisting.** A binding exists from the point its declaration is reached,
3984
+ * so a read before it resolves the enclosing context rather than raising a
3985
+ * temporal-dead-zone error. An uninitialised `let` binds `undefined` and still
3986
+ * *shadows*, because `EvalContext.get` resolves a pushed scope by presence
3987
+ * rather than by value.
3988
+ *
3989
+ * **`var` is rejected here, not by the statement dispatcher.** The dispatcher
3990
+ * switches on node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
3991
+ * `let x = 1` is - so registering this visitor is what stopped `var` reaching the
3992
+ * throwing `default:`. Function-scoped hoisting is a second scoping model beside
3993
+ * block scoping and is out of scope for this phase, so the rejection had to move
3994
+ * rather than disappear.
3995
+ *
3996
+ * No scope is pushed here: a declaration binds into the scope its enclosing
3997
+ * statement list already pushed, so there is no `try`/`finally` to pair and
3998
+ * nothing this visitor can leave behind on `EvalContext`.
3999
+ */
4000
+ const variableDeclarationVisitor = (node, st, callback) => {
4001
+ // Above `beforeVisitor`, deliberately. Four paths through this visitor throw,
4002
+ // and three of them have to throw from inside the bracket - they need the
4003
+ // walk to have started. This one reads `node.kind` and nothing else, so
4004
+ // rejecting before the hook dispatch keeps the most reachable of the four
4005
+ // from opening a frame it never closes. The others are covered the way every
4006
+ // throwing visitor in this library is: `evaluate`'s `catch` unwinds the open
4007
+ // nodes to its walk base.
4008
+ if (node.kind !== 'let' && node.kind !== 'const') {
4009
+ throw new Error(`Unsupported variable declaration kind: ${node.kind}`);
4010
+ }
4011
+ beforeVisitor(node, st);
4012
+ const scope = bindingScope(st);
4013
+ for (const declarator of node.declarations) {
4014
+ let value = undefined;
4015
+ if (declarator.init) {
4016
+ callback(declarator.init, st);
4017
+ value = popVisitorResult(node, st);
4018
+ }
4019
+ bindDeclarator(declarator, value, node.kind, scope, st, callback);
4020
+ }
4021
+ pushVisitorResult(node, st, EMPTY_COMPLETION);
4022
+ afterVisitor(node, st);
4023
+ };
4024
+ /**
4025
+ * Assigns to `key`, preferring a binding the evaluation itself created.
4026
+ *
4027
+ * The shared write path for `assignment-expression.ts` and
4028
+ * `update-expression.ts`. It lives in this module rather than one of its own on
4029
+ * the precedent `dispatchStatement` set in `program.ts`: the `const` kinds it
4030
+ * enforces are recorded here, and two importers is not yet a utility module. A
4031
+ * third is when it earns one.
4032
+ *
4033
+ * Order matters, and both steps are one lookup:
4034
+ *
4035
+ * 1. `scopeHolding` finds the innermost pushed scope that **binds** the key, or
4036
+ * nothing. This is the same pass `EvalContext.get` resolves through, which is
4037
+ * why it is asked of the context rather than re-walked here.
4038
+ * 2. A `const` in that scope is rejected before anything is written.
4039
+ * 3. Otherwise `setInScope` writes it - and when no scope bound the key at all,
4040
+ * `set` does, which is the fallback `eval-signals` overrides to enforce its
4041
+ * read-only policy. Routing around it would disable that policy silently.
4042
+ *
4043
+ * **The scope is resolved twice - here, and again inside `setInScope` - and that
4044
+ * is a cost, not a free abstraction.** `scopeHolding` goes through
4045
+ * `Stack.asArray()`, which copies and reverses, so each pass allocates. An
4046
+ * identifier write therefore costs two short scans plus two small arrays where
4047
+ * the pre-Phase-2 `set` cost none.
4048
+ *
4049
+ * Kept because `setInScope` is the single place that knows how to write a scope
4050
+ * - a `Registry` under `caseInsensitive`, a plain record otherwise - and
4051
+ * writing directly from here would put that dispatch in two modules, which is
4052
+ * the one mistake in this area that is silent when made wrong. The honest
4053
+ * alternative is to let `setInScope` take an already-resolved scope; that widens
4054
+ * a signature this phase has published and is step 5's call, not this step's,
4055
+ * because step 5 is where the cost multiplies: `for (let i = 0; i < n; i++)`
4056
+ * runs this path once per iteration, on top of the `get` in the test and the
4057
+ * `get` in the update. Recorded in the plan's step 5 rather than left here.
4058
+ */
4059
+ const assignToBinding = (st, key, value, name) => {
4060
+ if (!st.context) {
4061
+ throw new Error(`Context is not set.`);
4062
+ }
4063
+ const scope = st.context.scopeHolding(key);
4064
+ if (!scope) {
4065
+ st.context.set(key, value);
4066
+ return;
4067
+ }
4068
+ if (st.isConstBinding(scope, key)) {
4069
+ throw new Error(`Assignment to constant variable "${name}".`);
4070
+ }
4071
+ st.context.setInScope(key, value);
4072
+ };
4073
+
2529
4074
  const assignmentOperators = {
2530
4075
  '=': (left, value) => { return left = value; },
2531
4076
  '+=': (left, value) => { return left += value; },
@@ -2562,7 +4107,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
2562
4107
  ? st.context.getKey(node.left.name)
2563
4108
  : node.left.name;
2564
4109
  const value = func(left, right);
2565
- st.context.set(key, value);
4110
+ // Scope first, the caller's object second. Before Phase 2 this was
4111
+ // `st.context.set(key, value)`, which consults no scope at all - so
4112
+ // `(x => (x = 99))(1)` wrote `99` into the caller's own object and left the
4113
+ // arrow's parameter untouched. See `assignToBinding` for why the fallback
4114
+ // to `set` is load-bearing rather than tidy.
4115
+ assignToBinding(st, key, value, node.left.name);
2566
4116
  pushVisitorResult(node, st, value);
2567
4117
  }
2568
4118
  else if (node.left.type === 'MemberExpression') {
@@ -2590,7 +4140,11 @@ const updateExpressionVisitor = (node, st, callback) => {
2590
4140
  : node.argument.name;
2591
4141
  const value = st.context?.get(key);
2592
4142
  const newValue = updateOperators[node.operator](value);
2593
- st.context?.set(key, newValue);
4143
+ // The same redirection as `assignment-expression.ts`, and the site that
4144
+ // matters for `for (let i = 0; …; i++)`: without it every loop counter this
4145
+ // library runs would be written into the consumer's context object, and
4146
+ // left there.
4147
+ assignToBinding(st, key, newValue, node.argument.name);
2594
4148
  pushVisitorResult(node, st, node.prefix ? newValue : value);
2595
4149
  }
2596
4150
  else if (node.argument.type === 'MemberExpression') {
@@ -2633,6 +4187,59 @@ const extractExpression = (program) => {
2633
4187
  return undefined;
2634
4188
  };
2635
4189
 
4190
+ /**
4191
+ * Applies § 3.1's rule 4: the empty-completion sentinel never leaves an
4192
+ * evaluation's return value.
4193
+ *
4194
+ * It is converted here, at the walk boundary, rather than in the `Program`
4195
+ * visitor. `arrow-function-expression.ts` calls `evaluate` on a
4196
+ * `BlockStatement` for a block-bodied arrow, so a conversion sited in `Program`
4197
+ * would let `x => { }` hand the sentinel straight to a consumer. Converting
4198
+ * where the walk ends covers both entry points by construction.
4199
+ */
4200
+ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : value;
4201
+ /**
4202
+ * The merged visitor table every walk dispatches through: this library's
4203
+ * visitors laid over `acorn-walk`'s base walker, built once.
4204
+ *
4205
+ * **`walk.recursive` merges per call, and the merge is not cheap.** Handed a
4206
+ * `funcs` object it calls `walk.make(funcs, base)`, which allocates an object
4207
+ * and copies every entry onto it - once per `evaluate`, not once per node.
4208
+ * Measured on the built bundle, walking a single `Literal`, which visits one
4209
+ * node and so is almost entirely this fixed cost:
4210
+ *
4211
+ * | visitor entries | per-call merge | merged once |
4212
+ * | --------------- | -------------- | ----------- |
4213
+ * | 19 (before statements) | 0.422 us | - |
4214
+ * | 22 (with statements) | 1.045 us | 0.226 us |
4215
+ *
4216
+ * Three more entries more than doubled it, which is a cliff rather than a
4217
+ * slope - the copy crosses a threshold where the engine stops treating the
4218
+ * result as a fast-property object. Merging once removes the whole class of
4219
+ * problem: it is faster than the pre-statement baseline, and it stops the
4220
+ * remaining statement visitors of this phase from making it worse again.
4221
+ *
4222
+ * `{}` is still passed as `funcs` at the call sites so that `make` has nothing
4223
+ * to copy; the per-walk object is then an empty `Object.create(DEFAULT_VISITORS)`
4224
+ * and every lookup is a prototype hit.
4225
+ *
4226
+ * Frozen, and lazily built, for two different reasons:
4227
+ *
4228
+ * - **Frozen** because this table is shared by every walk in the process -
4229
+ * `EvalService` is `providedIn: 'root'` - so a visitor that wrote to it would
4230
+ * reach every later evaluation, including other consumers'. Nothing writes to
4231
+ * it today; freezing is what keeps that true, turning a silent cross-walk
4232
+ * mutation into a throw. `getDefaultVisitors()` still returns a **fresh,
4233
+ * mutable** object to anyone who calls it, so no caller loses anything.
4234
+ * - **Lazily** because a module-level `const` deadlocks the flattened bundle:
4235
+ * `arrow-function-expression.ts` imports `evaluate`, so this module is
4236
+ * initialised first and `getDefaultVisitors()` at module scope reads that
4237
+ * visitor before its binding exists. Measured, not guessed - the built
4238
+ * package threw `Cannot access 'arrowFunctionExpressionVisitor' before
4239
+ * initialization` on import.
4240
+ */
4241
+ let defaultVisitors;
4242
+ const mergedVisitors = () => (defaultVisitors ??= Object.freeze(walk.make(getDefaultVisitors())));
2636
4243
  /**
2637
4244
  * Evaluates the given node and returns the result.
2638
4245
  *
@@ -2643,19 +4250,57 @@ const extractExpression = (program) => {
2643
4250
  const evaluate = (node, state) => {
2644
4251
  if (node) {
2645
4252
  state.result.start();
4253
+ // Captured inside the `if (node)` block on purpose: callers reach the early
4254
+ // return above with a bare state that has no hooks to read. Do not hoist.
4255
+ //
4256
+ // The mark is recorded on the state as well as held here, so that
4257
+ // `EvalHooks.exit` - called from a visitor, which has no route to this
4258
+ // local - can tell a node open in this walk from one open only in an
4259
+ // enclosing walk. Pushed under the same guard the mark is read under, and
4260
+ // the local `hooked` keeps the pair symmetric if a hook is registered
4261
+ // mid-walk.
4262
+ const hooked = state.hasHooks;
4263
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4264
+ // Unguarded, unlike the walk base above: the iteration budget refills on
4265
+ // the outermost entry whether or not hooks are registered. See
4266
+ // `EvalState.walkDepth` on why these are two fields and not one.
4267
+ state.enterWalk();
2646
4268
  try {
2647
- const visitors = getDefaultVisitors();
2648
- walk.recursive(node, state, visitors);
2649
- const value = popVisitorResult(node, state);
4269
+ walk.recursive(node, state, {}, mergedVisitors());
4270
+ const value = completionValue(popVisitorResult(node, state));
2650
4271
  state.result.stop();
2651
4272
  state.result.setSuccess(value);
2652
4273
  return value;
2653
4274
  }
2654
4275
  catch (error) {
2655
4276
  state.result.stop();
4277
+ // A visitor that throws skips its afterVisitor, so close whatever this
4278
+ // walk left open. Unwinding to the mark rather than to the bottom is what
4279
+ // stops a nested evaluate - the arrow-function body runs on this same
4280
+ // state - from draining the enclosing walk's open nodes.
4281
+ // Reads `state.hasHooks` rather than the `hooked` local captured above,
4282
+ // and the difference is deliberate but narrow: if a hook was registered
4283
+ // *during* this walk then `hooked` is false, no base was pushed, `mark`
4284
+ // is 0, and this unwinds the whole stack - including an enclosing walk's
4285
+ // frames, which is the boundary crossing the walk base exists to stop.
4286
+ // Left as it was rather than tightened here, because narrowing it would
4287
+ // change what a mid-walk registration observes on an already-published
4288
+ // path, which is not this step's to decide.
4289
+ if (state.hasHooks) {
4290
+ state.hooks.unwindTo(mark, error, state);
4291
+ }
2656
4292
  state.result.setFailure(error);
2657
4293
  throw error;
2658
4294
  }
4295
+ finally {
4296
+ // Both in a `finally`: a walk that threw still has to restore the
4297
+ // enclosing walk's bound and depth, or every later evaluation on this
4298
+ // state carries this one's nesting.
4299
+ state.exitWalk();
4300
+ if (hooked) {
4301
+ state.hooks.popWalkBase(state);
4302
+ }
4303
+ }
2659
4304
  }
2660
4305
  return undefined;
2661
4306
  };
@@ -2722,10 +4367,29 @@ const evaluateAsync = async (ast, state) => {
2722
4367
  return undefined;
2723
4368
  }
2724
4369
  state.result.start();
4370
+ // Captured after the `!ast` early return above, for the same reason the sync
4371
+ // entry point captures inside its `if (node)` block. Do not hoist.
4372
+ const hooked = state.hasHooks;
4373
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4374
+ state.enterWalk();
2725
4375
  try {
2726
- const visitors = getDefaultVisitors();
2727
- walk.recursive(ast, state, visitors);
2728
- let value = popVisitorResult(ast, state);
4376
+ let value;
4377
+ // The walk bookkeeping is released here rather than in a `finally` on the
4378
+ // outer try, because the walk ends here: everything below this block is
4379
+ // promise resolution on an already-finished traversal. Holding the walk
4380
+ // base and the depth across the `await` would leave an independent
4381
+ // evaluation that interleaved on this state looking like a nested walk -
4382
+ // and § 3.4's budget refills only on the outermost entry.
4383
+ try {
4384
+ walk.recursive(ast, state, {}, mergedVisitors());
4385
+ value = completionValue(popVisitorResult(ast, state));
4386
+ }
4387
+ finally {
4388
+ state.exitWalk();
4389
+ if (hooked) {
4390
+ state.hooks.popWalkBase(state);
4391
+ }
4392
+ }
2729
4393
  // Enhanced promise handling - recursively await all promises
2730
4394
  try {
2731
4395
  value = await awaitAllPromises(value);
@@ -2743,6 +4407,14 @@ const evaluateAsync = async (ast, state) => {
2743
4407
  }
2744
4408
  catch (error) {
2745
4409
  state.result.stop();
4410
+ // The walk here is synchronous too, so it strands open nodes on a throw
4411
+ // exactly as the sync entry point does. This catch also receives the
4412
+ // rethrow from the awaitAllPromises handler above; in that case the walk
4413
+ // had already closed every node it opened, the depth is back at the mark,
4414
+ // and unwindTo correctly synthesises nothing.
4415
+ if (state.hasHooks) {
4416
+ state.hooks.unwindTo(mark, error, state);
4417
+ }
2746
4418
  state.result.setFailure(error);
2747
4419
  throw error;
2748
4420
  }
@@ -2811,145 +4483,408 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
2811
4483
  beforeVisitor(node, st);
2812
4484
  const fn = (...arrowArgs) => {
2813
4485
  const newContext = evaluatePatterns(node.params, st, callback, arrowArgs);
4486
+ // The scope stack lives on EvalContext, not on the per-walk EvalState, and
4487
+ // one EvalContext can back any number of evaluations - so a scope this
4488
+ // closure fails to pop outlives the walk and is read first by every later
4489
+ // evaluation on the same context. The body is re-entrant `evaluate`, which
4490
+ // rethrows, so the pop needs `finally`.
4491
+ //
4492
+ // The `try` opens *after* the push, never around it. `push` is optionally
4493
+ // chained: bringing it inside would pair a `finally` pop with a push that
4494
+ // the same optional chain had skipped, and would swallow a throw from
4495
+ // evaluatePatterns into a pop as well.
2814
4496
  st.context?.push(newContext);
2815
- const value = evaluate(node.body, st);
2816
- st.context?.pop();
2817
- return value;
4497
+ try {
4498
+ return evaluate(node.body, st);
4499
+ }
4500
+ finally {
4501
+ st.context?.pop();
4502
+ }
2818
4503
  };
2819
4504
  pushVisitorResult(node, st, fn);
2820
4505
  afterVisitor(node, st);
2821
4506
  };
2822
4507
 
2823
- // based on evalArrowContext
2824
- // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
2825
- const evaluatePatterns = (patterns, st, callback, args) => {
2826
- let context = {};
2827
- patterns.map((pattern, i) => {
2828
- switch (pattern.type) {
2829
- case 'Identifier':
2830
- {
2831
- const object = evaluateIdentifier(pattern, st, args[i]);
2832
- context = { ...context, ...object };
2833
- }
2834
- break;
2835
- case 'MemberExpression':
2836
- {
2837
- const object = evaluateMemberExpression(pattern, st, callback, args[i]);
2838
- context = { ...context, ...object };
2839
- }
2840
- break;
2841
- case 'ObjectPattern':
2842
- {
2843
- const object = evaluateObjectPattern(pattern, st, callback, args[i]);
2844
- context = { ...context, ...object };
2845
- }
2846
- break;
2847
- case 'ArrayPattern':
2848
- {
2849
- const object = evaluateArrayPattern(pattern, st, callback, args[i]);
2850
- context = { ...context, ...object };
2851
- }
2852
- break;
2853
- case 'RestElement':
2854
- {
2855
- const object = evaluateRestElement(pattern, st, callback, args.slice(i));
2856
- context = { ...context, ...object };
2857
- }
2858
- break;
2859
- // case 'AssignmentPattern': {
2860
- // const object = evaluateAssignmentPattern(pattern, st, callback, args[i]);
2861
- // context = {...context, ...object};
2862
- // }
2863
- // break;
2864
- }
2865
- });
2866
- return context;
4508
+ /**
4509
+ * Walks one statement and returns its completion value.
4510
+ *
4511
+ * The statement dispatcher for the whole family, and the single place § 3.1's
4512
+ * rule 2 - one `popVisitorResult` per `callback` - is discharged for every
4513
+ * caller. Four visitors import it: `Program` and `BlockStatement` walk a
4514
+ * statement list, `IfStatement` a branch, and `ForStatement` an `init` and a
4515
+ * body.
4516
+ *
4517
+ * **It is explicit, and its `default` throws.** A node type this library does
4518
+ * not implement raises rather than falling through to `acorn-walk`'s base
4519
+ * walker, which would visit the subtree as an expression and strand whatever it
4520
+ * pushed - `while (false) { 1 }` used to evaluate to `1` that way. Three
4521
+ * visitors in this library already push nothing on one path of an `if`/`else if`
4522
+ * chain over node types (`docs/backlog.md` A2); a `switch` whose `default`
4523
+ * throws is how this family gains no fourth member.
4524
+ *
4525
+ * **Why this module exists.** It lived in `program.ts` for steps 1 to 5, on the
4526
+ * rule that a shared helper earns its own file at its *third* importer -
4527
+ * otherwise a visitor module has quietly become a utility module that also
4528
+ * happens to export a visitor. `if-statement.ts` met that condition in step 4,
4529
+ * which recorded it MET AND DEFERRED rather than unmet: no step's file list
4530
+ * admitted creating a module and rewriting three imports, and step 4 was not the
4531
+ * place to widen its own scope. The plan named step 6 as the date so that
4532
+ * `ForStatement` would not arrive in step 5 as a *fourth* importer against a
4533
+ * rule that had declined to fire twice. This is that move. The rejection surface
4534
+ * did not change with it - a pure relocation, gated by the existing suite.
4535
+ *
4536
+ * @returns the statement's completion value, which is `EMPTY_COMPLETION`
4537
+ * (`../classes/eval`) for a statement that produced nothing. The sentinel is not
4538
+ * imported here: this module never compares against it, and an import kept only
4539
+ * for a doc link is an unused binding the lint config rejects.
4540
+ */
4541
+ const dispatchStatement = (statement, st, callback) => {
4542
+ switch (statement.type) {
4543
+ // `VariableDeclaration` covers `var` as well, and cannot not: this `switch`
4544
+ // reads the node *type*, and `var x = 1` is a `VariableDeclaration` exactly
4545
+ // as `let x = 1` is. Listing it here is therefore what stopped `var`
4546
+ // reaching the `default:` below; the rejection moved into the visitor,
4547
+ // which can read `kind`.
4548
+ //
4549
+ // `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4550
+ // `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct
4551
+ // node types and stay out of the phase (§ 2), so they reach the `default`
4552
+ // below unchanged - unlike `var`, which shares a type with `let` and had to
4553
+ // be rejected one level down.
4554
+ case 'ExpressionStatement':
4555
+ case 'EmptyStatement':
4556
+ case 'BlockStatement':
4557
+ case 'VariableDeclaration':
4558
+ case 'IfStatement':
4559
+ case 'ForStatement':
4560
+ callback(statement, st);
4561
+ return popVisitorResult(statement, st);
4562
+ default:
4563
+ throw new Error(`Unsupported statement type: ${statement.type}`);
4564
+ }
2867
4565
  };
2868
- const evaluatePattern = (pattern, st, callback, arg) => {
2869
- switch (pattern.type) {
2870
- case 'Identifier':
2871
- return evaluateIdentifier(pattern, st, arg);
2872
- case 'MemberExpression':
2873
- return evaluateMemberExpression(pattern, st, callback, arg);
2874
- case 'ObjectPattern':
2875
- return evaluateObjectPattern(pattern, st, callback, arg);
2876
- case 'ArrayPattern':
2877
- return evaluateArrayPattern(pattern, st, callback, arg);
2878
- case 'RestElement':
2879
- return evaluateRestElement(pattern, st, callback, arg);
2880
- // case 'AssignmentPattern':
2881
- // return evaluateAssignmentPattern(pattern, st, callback, arg);
4566
+
4567
+ /**
4568
+ * Evaluates a program: the root node of every walk that reaches this library
4569
+ * through `EvalService`, since its parser options leave `extractExpressions`
4570
+ * off and so hand `evaluate` the whole `Program`.
4571
+ *
4572
+ * Keeps the last **non-empty** completion value, per JavaScript's
4573
+ * completion-value semantics, and pushes exactly one value however many
4574
+ * statements the body holds. A program whose statements all produced nothing -
4575
+ * `;`, or a source that is only whitespace - pushes {@link EMPTY_COMPLETION},
4576
+ * which the walk boundary in `evaluate` converts to `undefined`. The conversion
4577
+ * is deliberately not done here: `arrow-function-expression.ts` calls
4578
+ * `evaluate` on a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4579
+ * conversion would leave that entry point handing the sentinel to a consumer.
4580
+ *
4581
+ * **The program-level scope is required.** It is the only scope a top-level
4582
+ * `let` can bind into; without it a declaration would have nowhere to go but
4583
+ * `EvalContext.set`, which writes the caller's own context object - and is the
4584
+ * method `eval-signals` overrides to enforce its read-only policy. `get`
4585
+ * searches `scopes` first and falls through on a miss, so an empty program
4586
+ * scope costs no outer resolution.
4587
+ *
4588
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4589
+ * on the per-walk `EvalState`, and one context can back any number of
4590
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4591
+ * read first by every later evaluation on that context. The `try` opens *after*
4592
+ * the push, never around it - `push` is optionally chained, so bringing it
4593
+ * inside would pair a `finally` pop with a push the same optional chain had
4594
+ * skipped.
4595
+ */
4596
+ const programVisitor = (node, st, callback) => {
4597
+ beforeVisitor(node, st);
4598
+ let completion = EMPTY_COMPLETION;
4599
+ st.context?.push({}, st.options);
4600
+ try {
4601
+ for (const statement of node.body) {
4602
+ const value = dispatchStatement(statement, st, callback);
4603
+ if (value !== EMPTY_COMPLETION) {
4604
+ completion = value;
4605
+ }
4606
+ }
2882
4607
  }
2883
- return {};
4608
+ finally {
4609
+ st.context?.pop();
4610
+ }
4611
+ pushVisitorResult(node, st, completion);
4612
+ afterVisitor(node, st);
2884
4613
  };
2885
- const evaluateIdentifier = (pattern, st, arg) => {
2886
- const object = {};
2887
- object[pattern.name] = arg;
2888
- return object;
4614
+
4615
+ /**
4616
+ * Evaluates an expression statement: its completion value is its expression's.
4617
+ *
4618
+ * A pass-through, and registered rather than left to `acorn-walk`'s base walker
4619
+ * for two reasons. The base walker fires no hooks, so a statement would be
4620
+ * invisible to a consumer watching the walk; and § 3.1's rule that every
4621
+ * statement visitor pushes exactly one value would have an exception whose only
4622
+ * justification is that this one happens to be cheap.
4623
+ */
4624
+ const expressionStatementVisitor = (node, st, callback) => {
4625
+ beforeVisitor(node, st);
4626
+ callback(node.expression, st);
4627
+ const value = popVisitorResult(node, st);
4628
+ pushVisitorResult(node, st, value);
4629
+ afterVisitor(node, st);
2889
4630
  };
2890
- const evaluateMemberExpression = (pattern, st, callback, arg) => {
2891
- if (pattern.type === 'MemberExpression') {
2892
- console.log(pattern, st, callback, arg);
2893
- throw new Error('evaluateMemberExpression is not implemented.');
2894
- }
2895
- return {};
4631
+
4632
+ /**
4633
+ * Evaluates an empty statement: it produces nothing, so it pushes
4634
+ * {@link EMPTY_COMPLETION} and an enclosing statement list keeps whatever
4635
+ * preceded it.
4636
+ *
4637
+ * One line of behaviour, and it exists because the statement dispatcher's
4638
+ * `default` throws: without it `a;;b` and `if (x) ;` would start raising
4639
+ * "unsupported statement type", which is a divergence from JavaScript nobody
4640
+ * chose.
4641
+ */
4642
+ const emptyStatementVisitor = (node, st) => {
4643
+ beforeVisitor(node, st);
4644
+ pushVisitorResult(node, st, EMPTY_COMPLETION);
4645
+ afterVisitor(node, st);
2896
4646
  };
2897
- const evaluateObjectPattern = (pattern, st, callback, arg) => {
2898
- let context = {};
2899
- pattern.properties.map((pattern) => {
2900
- switch (pattern.type) {
2901
- case 'Property':
2902
- {
2903
- let key;
2904
- if (pattern.key.type === 'Identifier') {
2905
- key = pattern.key.name;
2906
- }
2907
- else if (pattern.key.type === 'Literal') {
2908
- key = pattern.key.value;
2909
- }
2910
- else {
2911
- callback(pattern.key, st);
2912
- key = popVisitorResult(pattern, st);
2913
- if (typeof key !== 'string' && typeof key !== 'number')
2914
- throw new Error(`Unsupported property key type: ${pattern.key.type}`);
2915
- }
2916
- const ctx = arg;
2917
- st.context?.push(ctx);
2918
- callback(pattern.value, st);
2919
- const value = popVisitorResult(pattern, st);
2920
- st.context?.pop();
2921
- const pair = {};
2922
- pair[key] = value;
2923
- context = { ...context, ...pair };
2924
- }
2925
- break;
2926
- case 'RestElement':
2927
- {
2928
- const object = evaluateRestElement(pattern, st, callback, arg);
2929
- context = { ...context, ...object };
2930
- }
2931
- break;
4647
+
4648
+ /**
4649
+ * Evaluates a block statement: a scope, a statement list, and one completion
4650
+ * value.
4651
+ *
4652
+ * Keeps the last **non-empty** completion value, per JavaScript's
4653
+ * completion-value semantics, and pushes exactly one value however many
4654
+ * statements the body holds. A block whose statements all produced nothing -
4655
+ * `{ }`, or `{ ; }` - pushes {@link EMPTY_COMPLETION} for its enclosing
4656
+ * statement list to skip over. The sentinel is converted to `undefined` at the
4657
+ * walk boundary in `evaluate`, which is why this visitor may return it to a
4658
+ * caller that is itself a walk root: `arrow-function-expression.ts` calls
4659
+ * `evaluate` on this node for a block-bodied arrow, so `x => { }` reaches a
4660
+ * consumer through the same conversion a `Program` does.
4661
+ *
4662
+ * **The block scope is unobservable in this step, and is pushed anyway.**
4663
+ * Nothing binds into it until `VariableDeclaration` lands, and an empty scope
4664
+ * shadows nothing now that `EvalContext.get` resolves a scope by presence
4665
+ * rather than by value. Pushing it here rather than with the first binding
4666
+ * keeps the scope arithmetic in one place: the depth a nested block reports is
4667
+ * a property of the block, not of whether its body happened to declare
4668
+ * anything.
4669
+ *
4670
+ * `st.options` is passed to `push` because `fromContext` copies a plain record
4671
+ * into a `Registry` when `caseInsensitive` is set. Omitting them would make a
4672
+ * block's bindings case-**sensitive** inside an otherwise case-insensitive
4673
+ * evaluation - a silent wrong answer rather than an error, and one no assertion
4674
+ * in this step can reach, since a scope nothing binds into resolves nothing
4675
+ * either way.
4676
+ *
4677
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4678
+ * on the per-walk `EvalState`, and one context can back any number of
4679
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4680
+ * read first by every later evaluation on that context. The `try` opens *after*
4681
+ * the push, never around it - `push` is optionally chained, so bringing it
4682
+ * inside would pair a `finally` pop with a push the same optional chain had
4683
+ * skipped.
4684
+ */
4685
+ const blockStatementVisitor = (node, st, callback) => {
4686
+ beforeVisitor(node, st);
4687
+ let completion = EMPTY_COMPLETION;
4688
+ st.context?.push({}, st.options);
4689
+ try {
4690
+ for (const statement of node.body) {
4691
+ const value = dispatchStatement(statement, st, callback);
4692
+ if (value !== EMPTY_COMPLETION) {
4693
+ completion = value;
4694
+ }
2932
4695
  }
2933
- });
2934
- return context;
4696
+ }
4697
+ finally {
4698
+ st.context?.pop();
4699
+ }
4700
+ pushVisitorResult(node, st, completion);
4701
+ afterVisitor(node, st);
2935
4702
  };
2936
- const evaluateArrayPattern = (pattern, st, callback, args) => {
2937
- const patterns = pattern.elements.filter(s => !!s);
2938
- const object = evaluatePatterns(patterns, st, callback, args);
2939
- return object;
4703
+
4704
+ /**
4705
+ * Evaluates an `if` statement: one test, and **exactly one branch or neither**.
4706
+ *
4707
+ * The behavioural fix in the plan's § 1.1 table. `acorn-walk`'s base walker
4708
+ * visits both branches regardless of the test, so `if (a) { 1 } else { 2 }` with
4709
+ * `a` true measured `2` - the `else` value was pushed last and won - and any
4710
+ * call or assignment in the untaken branch had already run. The value was the
4711
+ * smaller half of that: a visitor that walked both branches and then *selected*
4712
+ * by the test would return `1` and still run them both, which is why the specs
4713
+ * assert on an uncalled `jest.fn` and an unwritten source key beside the value.
4714
+ *
4715
+ * Completion value, per § 3.1: the branch's own, unchanged. A taken branch that
4716
+ * produced nothing propagates {@link EMPTY_COMPLETION} - `if (true) { }` pushes
4717
+ * the sentinel exactly as `if (false) { 1 }` does, by two different routes - and
4718
+ * a branch that genuinely produced `undefined` pushes that, so an enclosing
4719
+ * statement list keeps it over an earlier value. Mapping either onto the other
4720
+ * here would collapse the distinction the sentinel exists for.
4721
+ *
4722
+ * Arithmetic: pops 1 for the test, plus 1 for the branch when one runs; pushes
4723
+ * exactly 1 on both exit paths.
4724
+ *
4725
+ * **The branches go through `dispatchStatement`, not a raw `callback`.** A
4726
+ * branch is a `Statement`, and a raw callback would hand a type this library
4727
+ * does not implement to the base walker, which walks it as an expression and
4728
+ * strands whatever it pushed. That is the silent fall-through family § 1.7
4729
+ * names and § 3.1 promises to add no member to.
4730
+ *
4731
+ * **The margin is narrower than it first looks, and the specs say so where an
4732
+ * earlier draft of this docblock did not.** Every registered statement type -
4733
+ * `BlockStatement`, `ExpressionStatement`, `IfStatement` itself for an
4734
+ * `else if` chain, `VariableDeclaration` - is reached by a raw `callback` just
4735
+ * as well, because `acorn-walk` finds the registered visitor before it reaches
4736
+ * its base walker. So neither `if (a) { while (false) { 1 } }` nor an `else if`
4737
+ * chain discriminates: the block re-dispatches, and the chain arrives back here
4738
+ * either way. The one position that does is a **bare** branch body of an
4739
+ * unregistered type - `if (a) function f() { }` - where nothing stands between
4740
+ * this visitor and the base walker. Measured: swapping in a raw callback reddens
4741
+ * that case alone.
4742
+ *
4743
+ * It is still the right call, for the reason `dispatch-statement.ts` gives rather
4744
+ * than for a reason the suite can show: rule 2's single `callback`/`pop` pair
4745
+ * lives in one place, so the guarantee holds for whatever bare statement type a
4746
+ * later phase registers without this visitor being revisited.
4747
+ *
4748
+ * This visitor was `dispatchStatement`'s **third** importer, which is the
4749
+ * condition for giving it a module of its own. **Step 6 made that move**: the
4750
+ * dispatcher now lives in `dispatch-statement.ts`, with the rule and its history
4751
+ * in that module's docblock.
4752
+ *
4753
+ * **It pushes no scope, and there is no `try`/`finally` to pair.** Four routes a
4754
+ * binding could arrive by, all closed: a block body gets its scope from
4755
+ * `blockStatementVisitor`; `if (a) let x = 1` does not parse, since a lexical
4756
+ * declaration is not a legal bare statement body; `if (a) var x = 1` does parse,
4757
+ * reaches the dispatcher as a `VariableDeclaration`, and is rejected on `kind`
4758
+ * inside `variableDeclarationVisitor`; and `if (a) function f() { }` parses
4759
+ * under Annex B and is rejected by `dispatchStatement`'s throwing `default`.
4760
+ *
4761
+ * **The fourth is closed by the dispatcher and not by anything here**, which is
4762
+ * the one a later phase can reopen: a phase that registers `FunctionDeclaration`
4763
+ * gives this visitor a bare binding form with no enclosing block, and the
4764
+ * no-scope argument has to be re-made rather than inherited. `if (a) label: var
4765
+ * x = 1` is the same family. As of this step this visitor touches `EvalContext`
4766
+ * not at all, and the balance its specs assert on a reused context is the
4767
+ * enclosing visitors' to keep.
4768
+ */
4769
+ const ifStatementVisitor = (node, st, callback) => {
4770
+ beforeVisitor(node, st);
4771
+ callback(node.test, st);
4772
+ const test = popVisitorResult(node, st);
4773
+ let completion = EMPTY_COMPLETION;
4774
+ if (test) {
4775
+ completion = dispatchStatement(node.consequent, st, callback);
4776
+ }
4777
+ else if (node.alternate) {
4778
+ completion = dispatchStatement(node.alternate, st, callback);
4779
+ }
4780
+ pushVisitorResult(node, st, completion);
4781
+ afterVisitor(node, st);
2940
4782
  };
2941
- const evaluateRestElement = (pattern, st, callback, args) => {
2942
- const argument = pattern.argument;
2943
- const object = evaluatePattern(argument, st, callback, args);
2944
- return object;
4783
+
4784
+ /**
4785
+ * Evaluates a classic three-part `for` statement.
4786
+ *
4787
+ * § 1.1's row measured **`NaN`** with three stranded values before Phase 2: the
4788
+ * base walker handed the declarator's `id` to `identifierVisitor`, so `i`
4789
+ * resolved against the context rather than binding, and `i < 3` compared
4790
+ * `undefined`. Since step 1 the row throws from `dispatchStatement`'s `default`;
4791
+ * this visitor is what returns `2`.
4792
+ *
4793
+ * `for…of`, `for…in`, `while` and `do…while` stay out of the phase (§ 2) and
4794
+ * keep throwing - they are separate node types and reach the dispatcher's
4795
+ * `default` unchanged.
4796
+ *
4797
+ * **One scope for the loop, not one per iteration.** A draft of the plan
4798
+ * specified a fresh scope per iteration, seeded from the head and copied back
4799
+ * after `update`, on the reasoning that this is what makes a closure capture its
4800
+ * own iteration's binding. It makes **no observable difference here**: the
4801
+ * closure `arrow-function-expression.ts` builds captures `st`, not a scope
4802
+ * chain, and resolves its free variables against `st.context` *as it is when the
4803
+ * closure is called* - by which time this loop has popped everything it pushed.
4804
+ * So the per-iteration design would have allocated a scope and copied bindings
4805
+ * twice per iteration to buy a property no spec can assert (§ 3.6.5). Giving
4806
+ * closures a captured scope chain is real work in
4807
+ * `arrow-function-expression.ts` and is what a later phase would have to do
4808
+ * first.
4809
+ *
4810
+ * **`init` has two node shapes and they take two routes.** `for (let i = 0; …)`
4811
+ * parses `init` as a `VariableDeclaration`, which is a `Statement` and goes
4812
+ * through `dispatchStatement`; `for (i = 0; …)` parses it as an `Expression` and
4813
+ * takes a raw `callback`. Both pop exactly one - the declaration's `EMPTY`, or
4814
+ * the expression's value - so § 3.1's arithmetic is identical for the two and
4815
+ * the split is invisible to it. What depends on the split is the throwing
4816
+ * `default`: only the `dispatchStatement` route has one, so an `init` that is a
4817
+ * statement type this library does not implement is rejected rather than handed
4818
+ * to the base walker. `body` is a `Statement` and dispatches for the same
4819
+ * reason; `test` and `update` are expressions and do not.
4820
+ *
4821
+ * Arithmetic (§ 3.1): pops 1 for `init` when present, then per iteration 1 for
4822
+ * `test` (when present), 1 for `body` and 1 for `update` (when present) - one
4823
+ * per `callback` or `dispatchStatement`, as rule 2 requires. Pushes exactly one
4824
+ * value on every exit path: the last **non-empty** body value, or
4825
+ * {@link EMPTY_COMPLETION} when the loop ran zero iterations or every iteration
4826
+ * produced nothing. An absent `test` is `true`.
4827
+ *
4828
+ * **The budget is the only terminator for `for (;;)`** - with no `break`,
4829
+ * `continue` or `return` in this phase (§ 2) there is no other way out, and a
4830
+ * runaway loop that silently returned a partial value is the failure § 3.4
4831
+ * exists to prevent. `chargeIteration` throws when the budget is spent; it is
4832
+ * called from this loop and nowhere else in the library, which is why an
4833
+ * expression with no `for` in it pays nothing for the bound.
4834
+ *
4835
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4836
+ * on the per-walk `EvalState`, and one context can back any number of
4837
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4838
+ * read first by every later evaluation on that context. This is the visitor with
4839
+ * the **highest push multiplicity** in the family and the shape of A9's own
4840
+ * precondition argument - a `for` body throwing on iteration 3 - so every exit
4841
+ * path matters: `init`, `test`, `body` and `update` can each throw, the
4842
+ * dispatcher can reject the body, and the budget can end the loop from inside
4843
+ * the `try`. The `try` opens *after* the push, never around it - `push` is
4844
+ * optionally chained, so bringing it inside would pair a `finally` pop with a
4845
+ * push the same optional chain had skipped.
4846
+ */
4847
+ const forStatementVisitor = (node, st, callback) => {
4848
+ beforeVisitor(node, st);
4849
+ let completion = EMPTY_COMPLETION;
4850
+ st.context?.push({}, st.options);
4851
+ try {
4852
+ if (node.init) {
4853
+ if (node.init.type === 'VariableDeclaration') {
4854
+ dispatchStatement(node.init, st, callback);
4855
+ }
4856
+ else {
4857
+ callback(node.init, st);
4858
+ popVisitorResult(node, st);
4859
+ }
4860
+ }
4861
+ for (;;) {
4862
+ if (node.test) {
4863
+ callback(node.test, st);
4864
+ if (!popVisitorResult(node, st)) {
4865
+ break;
4866
+ }
4867
+ }
4868
+ // Charged once the test has admitted the iteration, so a loop that runs
4869
+ // `n` bodies charges `n` - which is what `iterationsRemaining` is asserted
4870
+ // against - and a loop whose test is false at the top charges nothing.
4871
+ st.chargeIteration();
4872
+ const value = dispatchStatement(node.body, st, callback);
4873
+ if (value !== EMPTY_COMPLETION) {
4874
+ completion = value;
4875
+ }
4876
+ if (node.update) {
4877
+ callback(node.update, st);
4878
+ popVisitorResult(node, st);
4879
+ }
4880
+ }
4881
+ }
4882
+ finally {
4883
+ st.context?.pop();
4884
+ }
4885
+ pushVisitorResult(node, st, completion);
4886
+ afterVisitor(node, st);
2945
4887
  };
2946
- // const evaluateAssignmentPattern = (pattern: AssignmentPattern, st: EvalState, callback: walk.WalkerCallback<EvalState>, args: unknown) => {
2947
- // const left = evaluatePattern(pattern.left, st, callback, args);
2948
- // callback(pattern.right, st);
2949
- // const value = popVisitorResult(pattern, st);
2950
- // const object = {...left};
2951
- // return object;
2952
- // }
2953
4888
 
2954
4889
  const defaultEvalScopeOptions = {
2955
4890
  global: false,
@@ -3035,6 +4970,100 @@ class EvalScope {
3035
4970
  }
3036
4971
  }
3037
4972
 
4973
+ /** The first segment of a dotted path: `a.b.c` -> `a`. */
4974
+ const rootOf = (path) => {
4975
+ const dot = path.indexOf('.');
4976
+ return dot < 0 ? path : path.slice(0, dot);
4977
+ };
4978
+ /**
4979
+ * Creates a dependency tracker.
4980
+ *
4981
+ * `reads` keeps everything. `dependencies` is the filtered view, and three
4982
+ * rules do the filtering:
4983
+ *
4984
+ * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
4985
+ * from a scope pushed during the walk - an arrow-function parameter. Only
4986
+ * the walker can tell one from a real context read, which is why the flag
4987
+ * exists; a consumer using this tracker inherits the filtering for free.
4988
+ * 2. **Nor is anything reached *through* one.** `item` being a binding makes
4989
+ * `item.name` one too, and that read carries no flag of its own: `scoped` is
4990
+ * set at identifier resolution, and the member hop resolves against the
4991
+ * bound object rather than against a scope. So the bound names are
4992
+ * remembered and any path rooted at one is dropped.
4993
+ * 3. **A method reached through a member hop is a call target, not data.**
4994
+ * `list.map` in `list.map(item => item.name)` resolves to
4995
+ * `Array.prototype.map`; recording it would put a built-in in the dependency
4996
+ * set, while `list` - already recorded - is the thing whose change actually
4997
+ * matters. Bare identifiers are exempt, function-valued or not: a
4998
+ * context-level callable was named directly rather than reached through an
4999
+ * object, and there is no already-recorded object standing in for it.
5000
+ *
5001
+ * Two limits, both consequences of keying on path strings:
5002
+ *
5003
+ * - **A computed member contributes nothing.** `obj[expr]` has no
5004
+ * reconstructible path, and its resolved key alone is not a usable key
5005
+ * without one. It is in `reads` with an exact `key` and `target`, for a
5006
+ * consumer willing to key on identity.
5007
+ * - **Names collide.** Rule 2 keys on the *name*, so once `item` has been an
5008
+ * arrow parameter anywhere in the expression, a genuine `item.x` elsewhere in
5009
+ * it is dropped too. Path strings from different arrow bodies collide the
5010
+ * same way. § 9 hands the identity-versus-paths question to Phase 3; this is
5011
+ * the paths half of it.
5012
+ *
5013
+ * ```ts
5014
+ * const tracker = createDependencyTracker();
5015
+ * const state = evalService.createState({ a: { b: 1 }, c: 2 });
5016
+ * const off = tracker.install(state.hooks);
5017
+ *
5018
+ * evalService.eval('a.b + c', state);
5019
+ * tracker.dependencies; // Set { 'a', 'a.b', 'c' }
5020
+ *
5021
+ * tracker.reset();
5022
+ * off();
5023
+ * ```
5024
+ *
5025
+ * @returns A tracker; nothing is collected until {@link EvalDependencyTracker.install}
5026
+ * is called.
5027
+ */
5028
+ const createDependencyTracker = () => {
5029
+ const dependencies = new Set();
5030
+ const reads = [];
5031
+ const bindings = new Set();
5032
+ const record = (event) => {
5033
+ reads.push(event);
5034
+ const path = event.path;
5035
+ if (event.scoped) {
5036
+ // Rule 1, and the source of rule 2's name set.
5037
+ if (path !== undefined) {
5038
+ bindings.add(path);
5039
+ }
5040
+ return;
5041
+ }
5042
+ if (path === undefined) {
5043
+ return;
5044
+ }
5045
+ if (bindings.has(rootOf(path))) {
5046
+ return; // rule 2
5047
+ }
5048
+ if (event.kind === 'member' && typeof event.value === 'function') {
5049
+ return; // rule 3
5050
+ }
5051
+ dependencies.add(path);
5052
+ };
5053
+ return {
5054
+ install(hooks) {
5055
+ return hooks.onRead(record);
5056
+ },
5057
+ dependencies,
5058
+ reads,
5059
+ reset() {
5060
+ dependencies.clear();
5061
+ reads.length = 0;
5062
+ bindings.clear();
5063
+ }
5064
+ };
5065
+ };
5066
+
3038
5067
  /**
3039
5068
  * Base class for evaluation.
3040
5069
  */
@@ -3207,10 +5236,10 @@ class ParserService {
3207
5236
  }
3208
5237
  return undefined;
3209
5238
  }
3210
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
3211
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, providedIn: 'root' }); }
5239
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
5240
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, providedIn: 'root' }); }
3212
5241
  }
3213
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, decorators: [{
5242
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, decorators: [{
3214
5243
  type: Injectable,
3215
5244
  args: [{
3216
5245
  providedIn: 'root'
@@ -3223,14 +5252,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImpor
3223
5252
  class EvalService extends BaseEval {
3224
5253
  /**
3225
5254
  * Constructs a new instance of the EvalService class.
3226
- * @param parserService The parser service used for parsing expressions.
3227
5255
  */
3228
- constructor(parserService) {
3229
- super(parserService);
3230
- this.parserService = parserService;
5256
+ constructor() {
5257
+ super(inject(ParserService));
3231
5258
  this._isDestroyed = false;
3232
5259
  this._activeContexts = new Set();
3233
5260
  this._activeStates = new Set();
5261
+ this.parserService = inject(ParserService);
3234
5262
  this.parserOptions = defaultParserOptions;
3235
5263
  }
3236
5264
  /**
@@ -3275,6 +5303,23 @@ class EvalService extends BaseEval {
3275
5303
  if (state.context && typeof state.context === 'object' && 'clear' in state.context && typeof state.context.clear === 'function') {
3276
5304
  state.context.clear();
3277
5305
  }
5306
+ // Drop hook registrations so a long-lived closure cannot pin a
5307
+ // destroyed state. This matters most for a registry the caller passed
5308
+ // through `options.hooks` and still holds: one that outlives the
5309
+ // service keeps every state its closures captured reachable. A
5310
+ // state-owned registry would die with its state regardless.
5311
+ //
5312
+ // Guarded on `hasHooks` rather than reading `state.hooks`, because that
5313
+ // getter builds a registry on first access - allocating inside the
5314
+ // method whose job is releasing memory. The guard is exact for this
5315
+ // purpose: it is false only when no hook is registered, and clearing an
5316
+ // empty registry does nothing.
5317
+ if (state.hasHooks) {
5318
+ state.hooks.clear();
5319
+ }
5320
+ // Bookkeeping lives on the state and `clear` cannot reach it, so the
5321
+ // open-node stack and collected errors need dropping separately.
5322
+ state.resetHookBookkeeping();
3278
5323
  }
3279
5324
  catch (error) {
3280
5325
  console.warn('Error cleaning up EvalState:', error);
@@ -3398,31 +5443,31 @@ class EvalService extends BaseEval {
3398
5443
  }
3399
5444
  }
3400
5445
  }
3401
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3402
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, providedIn: 'root' }); }
5446
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
5447
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, providedIn: 'root' }); }
3403
5448
  }
3404
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, decorators: [{
5449
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, decorators: [{
3405
5450
  type: Injectable,
3406
5451
  args: [{
3407
5452
  providedIn: 'root'
3408
5453
  }]
3409
- }], ctorParameters: () => [{ type: ParserService }] });
5454
+ }], ctorParameters: () => [] });
3410
5455
 
3411
5456
  /**
3412
5457
  * CompilerService class that extends BaseEval.
3413
5458
  * Provides methods for compiling and evaluating expressions with performance caching.
3414
5459
  */
3415
5460
  class CompilerService extends BaseEval {
3416
- constructor(parserService, evalService) {
3417
- super(parserService);
3418
- this.parserService = parserService;
3419
- this.evalService = evalService;
5461
+ constructor() {
5462
+ super(inject(ParserService));
3420
5463
  // Compilation cache with LRU eviction
3421
5464
  this._compilationCache = new Map();
3422
5465
  this._maxCacheSize = 200;
3423
5466
  this._cacheTTL = 10 * 60 * 1000; // 10 minutes
3424
5467
  this._accessOrder = new Set();
3425
5468
  this._isDestroyed = false;
5469
+ this.parserService = inject(ParserService);
5470
+ this.evalService = inject(EvalService);
3426
5471
  this.parserOptions = defaultParserOptions;
3427
5472
  this.setupCacheCleanup();
3428
5473
  }
@@ -3700,15 +5745,15 @@ class CompilerService extends BaseEval {
3700
5745
  }
3701
5746
  return undefined;
3702
5747
  }
3703
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, deps: [{ token: ParserService }, { token: EvalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3704
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
5748
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
5749
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
3705
5750
  }
3706
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, decorators: [{
5751
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, decorators: [{
3707
5752
  type: Injectable,
3708
5753
  args: [{
3709
5754
  providedIn: 'root'
3710
5755
  }]
3711
- }], ctorParameters: () => [{ type: ParserService }, { type: EvalService }] });
5756
+ }], ctorParameters: () => [] });
3712
5757
 
3713
5758
  /**
3714
5759
  * Service responsible for discovering nodes in an abstract syntax tree (AST).
@@ -3716,11 +5761,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImpor
3716
5761
  class DiscoveryService extends BaseEval {
3717
5762
  /**
3718
5763
  * Creates a new instance of the DiscoveryService class.
3719
- * @param parserService The parser service to be used.
3720
5764
  */
3721
- constructor(parserService) {
3722
- super(parserService);
3723
- this.parserService = parserService;
5765
+ constructor() {
5766
+ super(inject(ParserService));
5767
+ this.parserService = inject(ParserService);
3724
5768
  this.parserOptions = {
3725
5769
  ...defaultParserOptions,
3726
5770
  cacheSize: undefined
@@ -3749,19 +5793,19 @@ class DiscoveryService extends BaseEval {
3749
5793
  }
3750
5794
  }
3751
5795
  }
3752
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3753
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
5796
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
5797
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
3754
5798
  }
3755
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, decorators: [{
5799
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, decorators: [{
3756
5800
  type: Injectable,
3757
5801
  args: [{
3758
5802
  providedIn: 'root'
3759
5803
  }]
3760
- }], ctorParameters: () => [{ type: ParserService }] });
5804
+ }], ctorParameters: () => [] });
3761
5805
 
3762
5806
  /**
3763
5807
  * Generated bundle index. Do not edit.
3764
5808
  */
3765
5809
 
3766
- export { BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EvalContext, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
5810
+ 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 };
3767
5811
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map