@zvenigora/ng-eval-core 0.2.2 → 0.3.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.
@@ -548,13 +548,6 @@ declare class Cache<TValue> implements CacheType<TValue> {
548
548
  [Symbol.iterator](): IterableIterator<[string, TValue]>;
549
549
  }
550
550
 
551
- /**
552
- * Represents the options for evaluating expressions.
553
- */
554
- type EvalOptions = Record<string, unknown> | {
555
- caseInsensitive: false;
556
- };
557
-
558
551
  type EvalLookup = (key: unknown, thisArg?: unknown, options?: EvalOptions) => unknown;
559
552
 
560
553
  interface EvalScopeOptions {
@@ -657,6 +650,44 @@ declare class EvalContext {
657
650
  * @returns The value associated with the key, or undefined if not found.
658
651
  */
659
652
  get(key: unknown): unknown | undefined;
653
+ /**
654
+ * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
655
+ * during this evaluation, innermost first.
656
+ *
657
+ * {@link get} calls this rather than inlining the loop, so that the read
658
+ * hooks' `scoped` flag and the resolution it describes are the *same*
659
+ * implementation. A second copy of the order would drift - `getKey` already
660
+ * shows what that looks like when it does.
661
+ *
662
+ * A binding whose value is `undefined` reads as absent here, exactly as it
663
+ * does in {@link get}, which falls through to the original context for it.
664
+ *
665
+ * @param key - The key to retrieve the value for.
666
+ * @returns The value bound by the innermost scope holding the key, or
667
+ * undefined when no pushed scope holds it.
668
+ */
669
+ getFromScopes(key: unknown): unknown | undefined;
670
+ /**
671
+ * Whether any scope pushed during this evaluation *binds* the key - the
672
+ * question the read hooks' `scoped` flag asks.
673
+ *
674
+ * Deliberately about binding rather than about value, which is where it parts
675
+ * company with {@link getFromScopes}: a parameter bound to `undefined` is
676
+ * still a parameter, but `get` falls through past it to the original context.
677
+ * Reading the flag off the value would make it depend on the *data* - the
678
+ * same arrow function over `[{ name: 'a' }]` and over `[undefined]` would
679
+ * report different bindings, and a dependency tracker's output would vary
680
+ * between two recomputes of one expression. That is the failure this flag
681
+ * exists to prevent, so presence is the correct predicate.
682
+ *
683
+ * Both queries iterate the same stack in the same direction, so neither is a
684
+ * second copy of the four-step resolution order; they answer two different
685
+ * questions about its first step.
686
+ *
687
+ * @param key - The key to look for.
688
+ * @returns True when a pushed scope holds the key, whatever its value.
689
+ */
690
+ hasInScopes(key: unknown): boolean;
660
691
  /**
661
692
  * Retrieves the `this` value of the specified key from the evaluation context.
662
693
  * The value is searched in the original context, prior scopes, and lookup functions.
@@ -827,6 +858,8 @@ declare class EvalState {
827
858
  private _result;
828
859
  private _options;
829
860
  private _isAsync;
861
+ private _hooks;
862
+ private _hookBookkeeping;
830
863
  /**
831
864
  * Gets the evaluation context.
832
865
  */
@@ -843,6 +876,89 @@ declare class EvalState {
843
876
  * Gets whether the evaluation is asynchronous.
844
877
  */
845
878
  get isAsync(): boolean | undefined;
879
+ /**
880
+ * Gets the hook registry for this evaluation, creating an empty one on first
881
+ * access. A registry supplied through `options.hooks` is adopted instead.
882
+ *
883
+ * Merely reading this does not turn {@link hasHooks} on; registering does.
884
+ */
885
+ get hooks(): EvalHooks;
886
+ /**
887
+ * The dispatch guard read by `beforeVisitor` / `afterVisitor`. One field read
888
+ * and no options lookup, so the no-hooks path stays cheap.
889
+ */
890
+ get hasHooks(): boolean;
891
+ /**
892
+ * Errors raised by hooks during this evaluation and collected under the
893
+ * 'collect' policy.
894
+ *
895
+ * They live here rather than on {@link hooks} because an `EvalHooks` may be
896
+ * shared across evaluations, and an error describes one run.
897
+ *
898
+ * The array is the live one, so a reference taken before evaluating fills as
899
+ * errors arrive. Returning a shared empty array until the first collection
900
+ * would be cheaper by one allocation and wrong: the reference would silently
901
+ * stop tracking the moment anything was collected.
902
+ */
903
+ get hookErrors(): readonly EvalHookError[];
904
+ /**
905
+ * Per-node-type timings for **this state**, keyed by node type. Empty unless
906
+ * a timing hook was installed - by `options.trackTime`, or by the caller
907
+ * through `createTimingHook().install(state.hooks)`.
908
+ *
909
+ * Accumulates for the life of the state, not per `evaluate` call: under the
910
+ * `createState` + repeated `eval` style the counts are the running totals
911
+ * across every run on this state, which is what makes them comparable. A
912
+ * caller who wants per-run figures uses a fresh state, or drops these along
913
+ * with the rest of the run record via {@link resetHookBookkeeping}.
914
+ *
915
+ * Here rather than on the handle `createTimingHook` returns for the same
916
+ * reason {@link hookErrors} is: timings describe one run, and an `EvalHooks`
917
+ * may be handed to several. It is also the only place a `trackTime` caller
918
+ * could reach them, since that installation happens in this constructor and
919
+ * hands the handle to nobody.
920
+ *
921
+ * Totals are inclusive of child nodes; see `EvalNodeTiming`.
922
+ */
923
+ get nodeTimings(): ReadonlyMap<AnyNodeTypes, EvalNodeTiming>;
924
+ /**
925
+ * The per-run bookkeeping `EvalHooks` reads and writes: the open-node stack
926
+ * and the collected errors, grouped behind a single accessor.
927
+ *
928
+ * The state owns this storage and `eval-hooks.ts` only type-imports the
929
+ * state, which keeps the runtime import graph acyclic. Holding it in a
930
+ * module-private `WeakMap` inside `eval-hooks.ts` was the alternative and was
931
+ * rejected: `hookErrors` would then need a *runtime* import of that module
932
+ * while it already imports this one, and the resulting cycle is a hazard in
933
+ * the ng-packagr build.
934
+ *
935
+ * @internal Not part of the published API.
936
+ */
937
+ get hookBookkeeping(): EvalHookBookkeeping;
938
+ /**
939
+ * Drops every per-run record this state holds: the collected hook errors, the
940
+ * open-node stack, and the accumulated timings.
941
+ *
942
+ * It resets the whole record rather than only the errors, which is why it is
943
+ * not named for them. `EvalHooks.clear` cannot reach any of this - the
944
+ * bookkeeping belongs to the state - so without this method nothing drains
945
+ * the open-node stack at all. Frames left on it keep their AST nodes
946
+ * reachable for as long as the state is, and `EvalService` holds its states
947
+ * in a strong `Set`.
948
+ *
949
+ * The errors matter for the same reason under the state-first style:
950
+ * `createState` plus repeated `eval` on one state accumulates them for the
951
+ * life of that state, and a thrown value can close over consumer objects.
952
+ *
953
+ * The record is replaced rather than emptied in place, so a caller still
954
+ * holding the array {@link hookErrors} handed out keeps its own contents and
955
+ * simply stops tracking - the alternative would mutate a collection the
956
+ * caller owns a reference to.
957
+ *
958
+ * Calling this mid-walk is unsupported for the same reason `EvalHooks.clear`
959
+ * is: it abandons frames the dispatcher expects to close.
960
+ */
961
+ resetHookBookkeeping(): void;
846
962
  /**
847
963
  * Represents the state of an evaluation.
848
964
  * @param context The evaluation context.
@@ -862,8 +978,576 @@ declare class EvalState {
862
978
  static fromContext(context?: EvalContext | Context, options?: EvalOptions, isAsync?: boolean): EvalState;
863
979
  }
864
980
 
981
+ /**
982
+ * The two points at which a visitor brackets its body.
983
+ */
984
+ type EvalHookPhase = 'before' | 'after';
985
+ /**
986
+ * Payload handed to a node hook.
987
+ */
988
+ interface EvalNodeHookEvent {
989
+ readonly phase: EvalHookPhase;
990
+ readonly node: AnyNode;
991
+ readonly state: EvalState;
992
+ /** Value pushed by the visitor; only present on 'after'. */
993
+ readonly value?: unknown;
994
+ /** False when this 'after' event was synthesised rather than dispatched by a visitor. */
995
+ readonly completed: boolean;
996
+ /**
997
+ * The error that aborted evaluation.
998
+ *
999
+ * Present only on events synthesised by `unwindTo`, where evaluation really
1000
+ * did fail. Frames closed by `exit` - because an enclosing visitor moved on
1001
+ * without them - also carry `completed: false`, but no error: nothing threw,
1002
+ * and the evaluation may well succeed. Test for the property rather than
1003
+ * assuming `completed: false` implies one.
1004
+ */
1005
+ readonly error?: unknown;
1006
+ }
1007
+ /**
1008
+ * A node hook. Hooks are observers: they are called for their side effects and
1009
+ * their return value is discarded. A hook that returns a promise is *not*
1010
+ * awaited - see {@link ASYNC_HOOK_MESSAGE}.
1011
+ */
1012
+ type EvalNodeHook = (event: EvalNodeHookEvent) => void;
1013
+ /**
1014
+ * Which resolution produced a read event.
1015
+ */
1016
+ type EvalReadKind = 'identifier' | 'member';
1017
+ /**
1018
+ * Payload handed to a read hook: one resolved context read.
1019
+ *
1020
+ * Node hooks cannot report *which key* an expression read - the AST node alone
1021
+ * is not enough once case correction and computed members are in play - so this
1022
+ * is the event a dependency tracker actually needs.
1023
+ */
1024
+ interface EvalReadEvent {
1025
+ readonly kind: EvalReadKind;
1026
+ readonly node: AnyNode;
1027
+ readonly state: EvalState;
1028
+ /** The key as resolved against the context (case-corrected when caseInsensitive). */
1029
+ readonly key: string | number | symbol;
1030
+ /** The object the key was read from - the context, an EvalScope, or a plain object. */
1031
+ readonly target: unknown;
1032
+ /**
1033
+ * Dotted path when statically reconstructible (`a.b.c`), else undefined.
1034
+ *
1035
+ * Reconstructed from the source spelling, so it is *not* case-corrected even
1036
+ * when {@link key} is. Computed members (`obj[expr]`) yield undefined; their
1037
+ * `key` is still exact.
1038
+ */
1039
+ readonly path?: string;
1040
+ readonly value: unknown;
1041
+ /**
1042
+ * True when the key resolved from a scope pushed *during this evaluation* -
1043
+ * `EvalContext.scopes`, the stack `arrow-function-expression.ts` pushes and
1044
+ * pops around a call. Such a read is an arrow-function parameter binding,
1045
+ * not a dependency, and a tracker should skip it.
1046
+ *
1047
+ * The definition is **lifetime, not type**: caller-registered `priorScopes`
1048
+ * are `EvalScope` instances holding long-lived objects and are real
1049
+ * dependencies, so they are never flagged. Absent reads as "not scoped",
1050
+ * which is right for every member emission site.
1051
+ */
1052
+ readonly scoped?: boolean;
1053
+ }
1054
+ /**
1055
+ * A read hook. Like a node hook it is an observer: its return value is
1056
+ * discarded and a returned promise is not awaited.
1057
+ */
1058
+ type EvalReadHook = (event: EvalReadEvent) => void;
1059
+ /**
1060
+ * Removes the hook that returned it. Calling it more than once is a no-op.
1061
+ */
1062
+ type Unsubscribe = () => void;
1063
+ /**
1064
+ * What to do with an error raised by a hook.
1065
+ *
1066
+ * - `collect` (default) - wrap it, append it to `state.hookErrors`, keep evaluating.
1067
+ * - `throw` - rethrow it into the visitor, failing the evaluation.
1068
+ * - `ignore` - swallow it silently.
1069
+ */
1070
+ type EvalHookErrorPolicy = 'collect' | 'throw' | 'ignore';
1071
+ /**
1072
+ * An error raised by a hook, recorded under the 'collect' policy.
1073
+ *
1074
+ * `phase` is `'read'` for an error raised by a read hook: a read is neither of
1075
+ * the two node phases, and reporting one as 'before' or 'after' would mislead a
1076
+ * consumer reading the log.
1077
+ */
1078
+ interface EvalHookError {
1079
+ readonly phase: EvalHookPhase | 'read';
1080
+ readonly nodeType: AnyNodeTypes;
1081
+ readonly error: unknown;
1082
+ }
1083
+ /**
1084
+ * How long one node type took over an evaluation, accumulated by the timing
1085
+ * hook and read back as `EvalState.nodeTimings`.
1086
+ *
1087
+ * `total` is *inclusive*: a node's children are counted in its own elapsed
1088
+ * time, so the totals of nested types overlap and summing them exceeds the
1089
+ * walk's duration. Per-type comparison is what this supports; a breakdown that
1090
+ * adds up is not.
1091
+ */
1092
+ interface EvalNodeTiming {
1093
+ /** How many nodes of this type were visited. */
1094
+ readonly count: number;
1095
+ /** Inclusive elapsed milliseconds across all of them. */
1096
+ readonly total: number;
1097
+ }
1098
+ /**
1099
+ * The bookkeeping an `EvalHooks` accumulates over a single evaluation.
1100
+ *
1101
+ * It is grouped behind one accessor on `EvalState` rather than spread across
1102
+ * several members, and it lives on the state rather than on the registry: an
1103
+ * `EvalHooks` is consumer-owned and may be handed to several evaluations, so
1104
+ * anything whose lifetime is one run belongs to the run.
1105
+ *
1106
+ * @internal Not part of the published API; `EvalHooks` is its only writer.
1107
+ */
1108
+ interface EvalHookBookkeeping {
1109
+ /** Nodes whose 'before' has fired but whose 'after' has not, outermost first. */
1110
+ readonly open: AnyNode[];
1111
+ /** Hook errors recorded under the 'collect' policy. */
1112
+ readonly errors: EvalHookError[];
1113
+ /**
1114
+ * Per-node-type timings, written by the timing hook when one is installed and
1115
+ * left empty otherwise.
1116
+ *
1117
+ * It lives here rather than on the handle `createTimingHook` returns for two
1118
+ * reasons. A registry may be shared across evaluations, so totals held on the
1119
+ * handle would bleed one run into the next - the same argument that moved the
1120
+ * error list here. And `trackTime` installs the hook from inside the
1121
+ * `EvalState` constructor, where no caller ever sees the handle: totals on it
1122
+ * would be unreachable, which is a dead option rather than a feature.
1123
+ */
1124
+ readonly timings: Map<AnyNodeTypes, EvalNodeTiming>;
1125
+ }
1126
+ /**
1127
+ * The message carried by the error raised when a hook returns a promise.
1128
+ *
1129
+ * Hooks are synchronous by contract (§ 3.3): the walk is synchronous even under
1130
+ * `evaluateAsync`, so a returned promise is never awaited and whatever the hook
1131
+ * meant to do lands after the evaluation finished. The dispatcher reports it as
1132
+ * an error carrying this message, routed through the configured policy like any
1133
+ * other hook error - collected by default, and thrown into the visitor under
1134
+ * `'throw'`, which does fail the evaluation.
1135
+ *
1136
+ * Exported so a consumer inspecting `EvalState.hookErrors` can tell this
1137
+ * diagnostic apart from an error its own hook threw, without matching on
1138
+ * message text it would have to keep in sync by hand.
1139
+ */
1140
+ declare const ASYNC_HOOK_MESSAGE = "async hook returned a promise; it will not be awaited";
1141
+ /**
1142
+ * A registry of node hooks, keyed by node type with wildcard support, and the
1143
+ * dispatcher that keeps `before` and `after` balanced when a visitor throws.
1144
+ *
1145
+ * It holds *registration* only. Everything whose lifetime is a single
1146
+ * evaluation - the open-node stack and the collected errors - lives on the
1147
+ * `EvalState` instead, because a consumer may hand one `EvalHooks` to several
1148
+ * evaluations and expect each to observe both.
1149
+ *
1150
+ * Hooks are synchronous by design: the walk in `evaluate` is synchronous even
1151
+ * under `evaluateAsync`, so there is no point at which a hook could be awaited.
1152
+ */
1153
+ declare class EvalHooks {
1154
+ private readonly _before;
1155
+ private readonly _after;
1156
+ private _read;
1157
+ private readonly _policy;
1158
+ private _size;
1159
+ private _active;
1160
+ /**
1161
+ * @param options The evaluation options; `onHookError` selects the error policy.
1162
+ */
1163
+ constructor(options?: EvalOptions);
1164
+ /**
1165
+ * True while no hook is registered. Read on the hot path, so it is a counter
1166
+ * rather than a walk of the registries.
1167
+ */
1168
+ get isEmpty(): boolean;
1169
+ /**
1170
+ * The dispatch guard, behind `EvalState.hasHooks`.
1171
+ *
1172
+ * Unlike {@link isEmpty} this *latches*: it turns true on the first
1173
+ * registration and only `clear` turns it off again. The guard wraps the
1174
+ * open-node stack as well as the hooks themselves, so a value that changed
1175
+ * mid-walk would leave `enter` and `exit` unpaired - which is exactly what
1176
+ * one-shot and self-unsubscribing hooks would otherwise cause.
1177
+ *
1178
+ * Calling `clear` during a walk is therefore unsupported.
1179
+ */
1180
+ get isActive(): boolean;
1181
+ /**
1182
+ * True while at least one read hook is registered.
1183
+ *
1184
+ * The second half of the read-emission guard: `st.hasHooks` says a registry
1185
+ * exists and has been used, this says a *read* hook is there to observe the
1186
+ * event. Without it a consumer that registered only 'before'/'after' hooks
1187
+ * would pay `getKey` per identifier and `readPath` plus an object literal per
1188
+ * member for events it can never see - which the timing hook turns from
1189
+ * theoretical into routine, since it latches `hasHooks` for a whole walk.
1190
+ *
1191
+ * **Non-latching, unlike {@link isActive}.** That getter latches because it
1192
+ * wraps the open-node stack, so a value changing mid-walk would leave `enter`
1193
+ * and `exit` unpaired. `dispatchRead` touches no bookkeeping, so a read guard
1194
+ * that flips mid-walk can only drop read events - never unbalance anything.
1195
+ * A one-shot or self-unsubscribing read hook is therefore safe here, and the
1196
+ * guard can report the current registration count rather than history.
1197
+ */
1198
+ get hasReadHooks(): boolean;
1199
+ /**
1200
+ * Registers a node hook.
1201
+ * @param phase Whether to fire before or after the visitor body.
1202
+ * @param type A concrete node type, or '*' for every node.
1203
+ * @param hook The hook to register.
1204
+ * @returns A function that removes this hook.
1205
+ */
1206
+ on(phase: EvalHookPhase, type: AnyNodeTypes | '*', hook: EvalNodeHook): Unsubscribe;
1207
+ /**
1208
+ * Registers a read hook, fired once per resolved context read.
1209
+ *
1210
+ * Read hooks are not keyed by node type: there are only two emission points
1211
+ * and a consumer filters on {@link EvalReadEvent.kind} if it cares.
1212
+ *
1213
+ * Registration latches {@link isActive} exactly as {@link on} does, because
1214
+ * the visitors reach their emission points through the same
1215
+ * `EvalState.hasHooks` guard.
1216
+ *
1217
+ * @param hook The hook to register.
1218
+ * @returns A function that removes this hook.
1219
+ */
1220
+ onRead(hook: EvalReadHook): Unsubscribe;
1221
+ /**
1222
+ * Removes one read hook, or every read hook when `hook` is omitted.
1223
+ */
1224
+ offRead(hook?: EvalReadHook): void;
1225
+ /**
1226
+ * Removes one hook, or every hook registered for a key when `hook` is omitted.
1227
+ */
1228
+ off(phase: EvalHookPhase, type: AnyNodeTypes | '*', hook?: EvalNodeHook): void;
1229
+ /**
1230
+ * Removes every hook from both phases and unlatches {@link isActive}.
1231
+ *
1232
+ * Per-run bookkeeping is untouched: the open-node stack and the collected
1233
+ * errors belong to the `EvalState`, not to this registry. Errors in
1234
+ * particular are a record of what already happened.
1235
+ */
1236
+ clear(): void;
1237
+ /**
1238
+ * Fires the hooks registered for a node, keyed first and wildcard second.
1239
+ *
1240
+ * Bookkeeping runs before user code on both edges: 'before' pushes the node
1241
+ * onto the open-node stack and *then* emits, 'after' pops and *then* emits.
1242
+ * The shared rule is that hook code only ever runs once the stack already
1243
+ * tells the truth about this node, because `emit` can throw - under the
1244
+ * 'throw' policy a hook's error propagates out of it. Emitting first on the
1245
+ * 'before' edge would leave a node that some hooks had already been told
1246
+ * about missing from the stack, and therefore invisible to `unwindTo`.
1247
+ *
1248
+ * @param value The value the visitor pushed; meaningful on 'after' only.
1249
+ */
1250
+ dispatch(phase: EvalHookPhase, node: AnyNode, state: EvalState, value?: unknown): void;
1251
+ /**
1252
+ * Fires the read hooks for one resolved context read.
1253
+ *
1254
+ * The event is built by the caller rather than assembled from positional
1255
+ * arguments here, so the visitors allocate nothing on the no-hooks path: the
1256
+ * whole construction sits inside their `st.hasHooks` guard.
1257
+ *
1258
+ * Touches no bookkeeping. A read is not a frame - it happens *within* a
1259
+ * node's before/after pair, so the open-node stack is none of its business.
1260
+ */
1261
+ dispatchRead(event: EvalReadEvent): void;
1262
+ /**
1263
+ * Records a node as open on the state. Called by the 'before' dispatcher
1264
+ * before its hooks fire.
1265
+ */
1266
+ enter(node: AnyNode, state: EvalState): void;
1267
+ /**
1268
+ * Closes `node`, matching it by **identity** rather than by position. Called
1269
+ * by the 'after' dispatcher before its hooks fire.
1270
+ *
1271
+ * Three cases:
1272
+ *
1273
+ * 1. `node` is on top - pop it. The ordinary path, one reference comparison.
1274
+ * 2. `node` is open but not on top - some visitor between here and there
1275
+ * never closed itself. Flush those frames innermost-first as
1276
+ * `completed: false`, then pop `node`.
1277
+ * 3. `node` is not open at all - pop nothing and emit nothing.
1278
+ *
1279
+ * Case 3 is what keeps a stray `exit` from draining the stack: the naive
1280
+ * "pop until you find it" would walk to the bottom, synthesise an event for
1281
+ * every genuinely-open enclosing frame, and leave a later real failure with
1282
+ * nothing to unwind.
1283
+ *
1284
+ * Popping positionally instead would be correct only if every visitor
1285
+ * bracketed its body exactly. `await-expression.ts` does not - it catches a
1286
+ * child's synchronous throw and continues to its own `afterVisitor` - so a
1287
+ * positional pop closes the child's frame under the parent's name, drops the
1288
+ * child's `after` entirely, and leaks one frame onto the state for good.
1289
+ *
1290
+ * The synthesised events carry no `value` (the node never pushed one) and no
1291
+ * `error` (nothing threw; the frames are being closed because an enclosing
1292
+ * visitor moved on without them).
1293
+ *
1294
+ * They are emitted under the collect policy even when the consumer chose
1295
+ * 'throw'. That is required, not merely lenient: a rethrow here would escape
1296
+ * the flush loop before it finished popping, re-creating the leak this
1297
+ * identity check exists to prevent. A 'throw'-policy consumer sees these in
1298
+ * `state.hookErrors` instead.
1299
+ */
1300
+ exit(state: EvalState, node: AnyNode): void;
1301
+ /**
1302
+ * How many nodes the state has open. Captured as a mark before a walk, since
1303
+ * `evaluate` is re-entered with the same state from an arrow-function body.
1304
+ *
1305
+ * This is a method rather than a getter because the stack it measures lives
1306
+ * on the state, not on this registry.
1307
+ */
1308
+ depth(state: EvalState): number;
1309
+ /**
1310
+ * Fires 'after' for every node the state has open above `mark`, innermost
1311
+ * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
1312
+ * visitor which throws still leaves every 'before' matched by exactly one
1313
+ * 'after'.
1314
+ *
1315
+ * Unwinding to a mark rather than to the bottom is what keeps a nested
1316
+ * `evaluate` from draining the enclosing walk's open nodes when a host
1317
+ * function swallows the nested throw.
1318
+ *
1319
+ * Idempotent, so the sync and async entry points can both call it.
1320
+ *
1321
+ * A hook that throws here cannot stop the drain: while unwinding, the 'throw'
1322
+ * policy is downgraded to 'collect' - evaluation has already failed, and the
1323
+ * original error is the one worth propagating.
1324
+ */
1325
+ unwindTo(mark: number, error: unknown, state: EvalState): void;
1326
+ /**
1327
+ * Drains the state's whole open-node stack. Equivalent to `unwindTo(0, ...)`,
1328
+ * for callers that own the entire walk.
1329
+ */
1330
+ unwind(error: unknown, state: EvalState): void;
1331
+ private registry;
1332
+ private emit;
1333
+ /**
1334
+ * Iterates a copy so that a hook which unsubscribes itself does not shift the
1335
+ * list out from under the loop.
1336
+ */
1337
+ private invokeAll;
1338
+ private invoke;
1339
+ /**
1340
+ * The read counterpart of {@link invoke}. There is no unwinding equivalent
1341
+ * for reads - a read never opens a frame - so the policy always applies in
1342
+ * full.
1343
+ */
1344
+ private invokeRead;
1345
+ private handleError;
1346
+ }
1347
+
1348
+ /**
1349
+ * Represents the options for evaluating expressions.
1350
+ *
1351
+ * Deliberately a permissive record: callers pass their own keys through it, and
1352
+ * `EvalContext` / `EvalScope` forward the same object around. Narrowing it to
1353
+ * {@link EvalKnownOptions} would break every caller holding a
1354
+ * `Record<string, unknown>`, since `unknown` is not assignable to a declared
1355
+ * `boolean | undefined`. The keys the evaluator itself recognises are documented
1356
+ * on {@link EvalKnownOptions} instead, and read through a cast at the point of
1357
+ * use because a union does not index directly.
1358
+ */
1359
+ type EvalOptions = Record<string, unknown> | {
1360
+ caseInsensitive: false;
1361
+ };
1362
+ /**
1363
+ * The option keys `eval-core` itself recognises.
1364
+ *
1365
+ * Documentation with types attached rather than a constraint: an
1366
+ * {@link EvalOptions} value is *not* required to conform to this, and nothing
1367
+ * validates against it. Its purpose is to give the recognised keys one
1368
+ * discoverable declaration, and to let a caller who wants checking write
1369
+ * `const options: EvalKnownOptions = { … }` and have a typo caught.
1370
+ *
1371
+ * A type alias rather than an interface, and that is load-bearing: an interface
1372
+ * gets no implicit index signature, so it would not be assignable to
1373
+ * {@link EvalOptions}'s `Record<string, unknown>` arm and the annotated form
1374
+ * above - its only reason to exist - would not compile.
1375
+ */
1376
+ type EvalKnownOptions = {
1377
+ /**
1378
+ * Resolve context keys and property names without regard to case.
1379
+ */
1380
+ caseInsensitive?: boolean;
1381
+ /**
1382
+ * Accumulate per-node-type timings for the evaluation, readable afterwards as
1383
+ * `EvalState.nodeTimings`.
1384
+ *
1385
+ * **Turning this on makes the walk dispatch per node.** Registering the
1386
+ * timing hook from options constructs the hook registry eagerly, and
1387
+ * `EvalHooks.isActive` latches on that registration, so every node dispatches
1388
+ * for the whole evaluation. That cost is inherent to the feature - per-node
1389
+ * -type totals cannot be derived without visiting each node - and it is not
1390
+ * the zero-cost-when-unused guarantee being eroded: that guarantee is about
1391
+ * the *default* path. If a single walk-level total is all that is wanted,
1392
+ * `EvalResult.duration` already provides one for free on every evaluation.
1393
+ *
1394
+ * Honoured only when no registry is supplied through {@link hooks}; see that
1395
+ * key.
1396
+ */
1397
+ trackTime?: boolean;
1398
+ /**
1399
+ * A caller-owned {@link EvalHooks} to dispatch through, instead of the empty
1400
+ * one the state creates on first access.
1401
+ *
1402
+ * Adopted as-is and never cloned, so the unsubscribe closures `on` returned
1403
+ * keep working. **Because the registry belongs to the caller, options never
1404
+ * configure it**: {@link onHookError} and {@link trackTime} apply to a
1405
+ * registry the state built, and are silently ignored when one is adopted. A
1406
+ * caller who wants either alongside their own registry sets it there -
1407
+ * `new EvalHooks({ onHookError: 'throw' })`, or `createTimingHook().install`.
1408
+ *
1409
+ * The one thing the library does *to* an adopted registry is clear it:
1410
+ * `EvalService.ngOnDestroy` empties the registries of the states it created,
1411
+ * this one included, so that a registry outliving the service cannot keep
1412
+ * those states and their AST nodes reachable. Registrations cannot be dropped
1413
+ * selectively - the closures that captured a dead state are indistinguishable
1414
+ * from the rest - so do not share one registry with a state whose lifetime is
1415
+ * meant to outlast the service.
1416
+ */
1417
+ hooks?: EvalHooks;
1418
+ /**
1419
+ * What to do with an error raised by a hook. Defaults to `'collect'`.
1420
+ *
1421
+ * Honoured only when no registry is supplied through {@link hooks}; see that
1422
+ * key.
1423
+ */
1424
+ onHookError?: EvalHookErrorPolicy;
1425
+ };
1426
+
865
1427
  declare const defaultParserOptions: ParserOptions;
866
1428
 
1429
+ /**
1430
+ * A timing hook, ready to install on a registry.
1431
+ *
1432
+ * It carries no totals of its own: they are written to the `EvalState` being
1433
+ * evaluated and read back as `EvalState.nodeTimings`. That is what lets the
1434
+ * `trackTime` option install one from inside the `EvalState` constructor, where
1435
+ * the caller never sees this handle - and it is what keeps two evaluations
1436
+ * through a shared registry from accumulating into each other.
1437
+ */
1438
+ interface EvalTimingHook {
1439
+ /**
1440
+ * Registers the 'before'/'after' pair on `hooks`.
1441
+ *
1442
+ * @param hooks The registry to register on.
1443
+ * @returns A function that removes both halves of the pair.
1444
+ */
1445
+ install(hooks: EvalHooks): Unsubscribe;
1446
+ }
1447
+ /**
1448
+ * Creates a timing hook that accumulates inclusive per-node-type totals.
1449
+ *
1450
+ * Replaces the `console.time` / `console.timeEnd` pair the old `trackTime`
1451
+ * emitted, which mismatched its labels and produced no readable figure. The
1452
+ * readings are `performance.now()`, and nothing is written to the console.
1453
+ *
1454
+ * ```ts
1455
+ * const state = evalService.createState(context);
1456
+ * const off = createTimingHook().install(state.hooks);
1457
+ * evalService.eval('a + b * c', state);
1458
+ * state.nodeTimings.get('BinaryExpression'); // { count: 2, total: 0.081 }
1459
+ * off();
1460
+ * ```
1461
+ *
1462
+ * Equivalent to passing `{ trackTime: true }`, which installs one of these on
1463
+ * the state's own registry.
1464
+ *
1465
+ * @returns A handle whose `install` registers the pair on a registry.
1466
+ */
1467
+ declare const createTimingHook: () => EvalTimingHook;
1468
+
1469
+ /**
1470
+ * Collects the context reads an evaluation made, as a set of dotted paths.
1471
+ *
1472
+ * This is Phase 3's input: install it, evaluate, and read {@link dependencies}
1473
+ * back in the same synchronous turn - which is what wrapping a `computed()`
1474
+ * needs. Hooks are synchronous by design, so that ordering always holds.
1475
+ */
1476
+ interface EvalDependencyTracker {
1477
+ /**
1478
+ * Registers the read hook on `hooks`.
1479
+ *
1480
+ * @param hooks The registry to register on.
1481
+ * @returns A function that removes it.
1482
+ */
1483
+ install(hooks: EvalHooks): Unsubscribe;
1484
+ /**
1485
+ * The dotted paths this tracker considers dependencies, filtered per the
1486
+ * rules on {@link createDependencyTracker}. Live: it fills as reads arrive.
1487
+ */
1488
+ readonly dependencies: ReadonlySet<string>;
1489
+ /**
1490
+ * Every read seen, unfiltered and in emission order - including the scope
1491
+ * bindings, method references and computed members {@link dependencies}
1492
+ * drops. A consumer that wants to key on `target` identity rather than on
1493
+ * path strings works from here.
1494
+ */
1495
+ readonly reads: EvalReadEvent[];
1496
+ /** Empties {@link dependencies}, {@link reads} and the scope-binding names. */
1497
+ reset(): void;
1498
+ }
1499
+ /**
1500
+ * Creates a dependency tracker.
1501
+ *
1502
+ * `reads` keeps everything. `dependencies` is the filtered view, and three
1503
+ * rules do the filtering:
1504
+ *
1505
+ * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
1506
+ * from a scope pushed during the walk - an arrow-function parameter. Only
1507
+ * the walker can tell one from a real context read, which is why the flag
1508
+ * exists; a consumer using this tracker inherits the filtering for free.
1509
+ * 2. **Nor is anything reached *through* one.** `item` being a binding makes
1510
+ * `item.name` one too, and that read carries no flag of its own: `scoped` is
1511
+ * set at identifier resolution, and the member hop resolves against the
1512
+ * bound object rather than against a scope. So the bound names are
1513
+ * remembered and any path rooted at one is dropped.
1514
+ * 3. **A method reached through a member hop is a call target, not data.**
1515
+ * `list.map` in `list.map(item => item.name)` resolves to
1516
+ * `Array.prototype.map`; recording it would put a built-in in the dependency
1517
+ * set, while `list` - already recorded - is the thing whose change actually
1518
+ * matters. Bare identifiers are exempt, function-valued or not: a
1519
+ * context-level callable was named directly rather than reached through an
1520
+ * object, and there is no already-recorded object standing in for it.
1521
+ *
1522
+ * Two limits, both consequences of keying on path strings:
1523
+ *
1524
+ * - **A computed member contributes nothing.** `obj[expr]` has no
1525
+ * reconstructible path, and its resolved key alone is not a usable key
1526
+ * without one. It is in `reads` with an exact `key` and `target`, for a
1527
+ * consumer willing to key on identity.
1528
+ * - **Names collide.** Rule 2 keys on the *name*, so once `item` has been an
1529
+ * arrow parameter anywhere in the expression, a genuine `item.x` elsewhere in
1530
+ * it is dropped too. Path strings from different arrow bodies collide the
1531
+ * same way. § 9 hands the identity-versus-paths question to Phase 3; this is
1532
+ * the paths half of it.
1533
+ *
1534
+ * ```ts
1535
+ * const tracker = createDependencyTracker();
1536
+ * const state = evalService.createState({ a: { b: 1 }, c: 2 });
1537
+ * const off = tracker.install(state.hooks);
1538
+ *
1539
+ * evalService.eval('a.b + c', state);
1540
+ * tracker.dependencies; // Set { 'a', 'a.b', 'c' }
1541
+ *
1542
+ * tracker.reset();
1543
+ * off();
1544
+ * ```
1545
+ *
1546
+ * @returns A tracker; nothing is collected until {@link EvalDependencyTracker.install}
1547
+ * is called.
1548
+ */
1549
+ declare const createDependencyTracker: () => EvalDependencyTracker;
1550
+
867
1551
  type BaseContext = Record<string | number | symbol, unknown>;
868
1552
  type Context = Registry<unknown, unknown> | BaseContext;
869
1553
  declare function isRegistryContext(context?: Context): boolean;
@@ -902,6 +1586,25 @@ interface CacheType<TValue> extends RegistryType<string, TValue> {
902
1586
  getHashKey: (namespace: string, value: string) => string;
903
1587
  }
904
1588
 
1589
+ /**
1590
+ * @deprecated Use `EvalHooks` and `EvalState` instead. Nothing in the library
1591
+ * implements this interface, and no code path reads its `beforeVisitors` /
1592
+ * `afterVisitors` entries; the evaluator's state type is `EvalState` and hooks
1593
+ * are registered through `EvalState.hooks`.
1594
+ *
1595
+ * **Its two hook entries are the last published trace of a signature no
1596
+ * function in the library has any more.** They are typed to return
1597
+ * `number | undefined` because the real `beforeVisitor` / `afterVisitor` once
1598
+ * returned a timing stub - a start timestamp handed back to the closing call.
1599
+ * That stub was deleted when those functions became hook dispatchers and their
1600
+ * return type widened to `void`, which is also what `EvalNodeHook` mandates, so
1601
+ * the shape recorded here is now contradicted by every hook the library
1602
+ * actually dispatches. A reader who finds these lines has no way to discover
1603
+ * that from the code, since there is no implementation left to compare against.
1604
+ *
1605
+ * Retained so this release stays purely additive; removal is a follow-up for
1606
+ * the next breaking version.
1607
+ */
905
1608
  interface RecursiveVisitorState {
906
1609
  scope: Registry<unknown, unknown>;
907
1610
  result: RecursiveVisitorResult<unknown | undefined>;
@@ -920,6 +1623,15 @@ declare enum RecursiveVisitorResultType {
920
1623
  Stack = 0,
921
1624
  Registry = 1
922
1625
  }
1626
+ /**
1627
+ * @deprecated Use `EvalResult` instead. This exists only as the `result` member
1628
+ * of the deprecated {@link RecursiveVisitorState}; the evaluator carries its
1629
+ * value stack and trace on `EvalResult`, which is what visitors actually push
1630
+ * to and what `EvalState.result` returns.
1631
+ *
1632
+ * Retained so this release stays purely additive; removal is a follow-up for
1633
+ * the next breaking version.
1634
+ */
923
1635
  type RecursiveVisitorResult<TValue> = RecursiveVisitorStackResult<TValue> | RecursiveVisitorRegistryResult<TValue>;
924
1636
  interface RecursiveVisitorStackResult<TValue> {
925
1637
  type: 'stack';
@@ -1029,15 +1741,14 @@ declare abstract class BaseEval {
1029
1741
  * Service for evaluating and parsing expressions with proper memory management.
1030
1742
  */
1031
1743
  declare class EvalService extends BaseEval implements OnDestroy {
1032
- protected parserService: ParserService;
1033
1744
  private _isDestroyed;
1034
1745
  private _activeContexts;
1035
1746
  private _activeStates;
1747
+ protected parserService: ParserService;
1036
1748
  /**
1037
1749
  * Constructs a new instance of the EvalService class.
1038
- * @param parserService The parser service used for parsing expressions.
1039
1750
  */
1040
- constructor(parserService: ParserService);
1751
+ constructor();
1041
1752
  /**
1042
1753
  * Override createState to track active contexts and states for cleanup
1043
1754
  */
@@ -1160,15 +1871,15 @@ declare const extract: (node: AnyNode | undefined, searchType: AnyNodeTypes) =>
1160
1871
  * Provides methods for compiling and evaluating expressions with performance caching.
1161
1872
  */
1162
1873
  declare class CompilerService extends BaseEval implements OnDestroy {
1163
- protected parserService: ParserService;
1164
- protected evalService: EvalService;
1165
1874
  private readonly _compilationCache;
1166
1875
  private readonly _maxCacheSize;
1167
1876
  private readonly _cacheTTL;
1168
1877
  private readonly _accessOrder;
1169
1878
  private _cacheCleanupInterval?;
1170
1879
  private _isDestroyed;
1171
- constructor(parserService: ParserService, evalService: EvalService);
1880
+ protected parserService: ParserService;
1881
+ protected evalService: EvalService;
1882
+ constructor();
1172
1883
  /**
1173
1884
  * OnDestroy lifecycle hook for cleanup
1174
1885
  */
@@ -1250,9 +1961,8 @@ declare class DiscoveryService extends BaseEval {
1250
1961
  protected parserService: ParserService;
1251
1962
  /**
1252
1963
  * Creates a new instance of the DiscoveryService class.
1253
- * @param parserService The parser service to be used.
1254
1964
  */
1255
- constructor(parserService: ParserService);
1965
+ constructor();
1256
1966
  /**
1257
1967
  * Finds all nodes in the AST that match the given expression and search type.
1258
1968
  * @param expression The expression to search for. Can be a string or an AST node.
@@ -1266,5 +1976,5 @@ declare class DiscoveryService extends BaseEval {
1266
1976
  static ɵprov: i0.ɵɵInjectableDeclaration<DiscoveryService>;
1267
1977
  }
1268
1978
 
1269
- 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 };
1270
- export type { AggregateType, AnyNodeTypes, BaseContext, CacheType, Context, EvalLookup, EvalOptions, EvalScopeOptions, EvalTraceItem, ParserOptions, QueueType, RecursiveAggregateVisitor, RecursiveVisitor, RecursiveVisitorContext, RecursiveVisitorOptions, RecursiveVisitorRegistryResult, RecursiveVisitorResult, RecursiveVisitorStackResult, RecursiveVisitorState, RegistryEntries, RegistryOptionType, RegistryType, ScopeOptions, ScopeType, StackType, stateCallback, stateCallbackAsync };
1979
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, 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 };
1980
+ export type { AggregateType, AnyNodeTypes, BaseContext, CacheType, Context, EvalDependencyTracker, EvalHookError, EvalHookErrorPolicy, EvalHookPhase, EvalKnownOptions, EvalLookup, EvalNodeHook, EvalNodeHookEvent, EvalNodeTiming, EvalOptions, EvalReadEvent, EvalReadHook, EvalReadKind, EvalScopeOptions, EvalTimingHook, EvalTraceItem, ParserOptions, QueueType, RecursiveAggregateVisitor, RecursiveVisitor, RecursiveVisitorContext, RecursiveVisitorOptions, RecursiveVisitorRegistryResult, RecursiveVisitorResult, RecursiveVisitorStackResult, RecursiveVisitorState, RegistryEntries, RegistryOptionType, RegistryType, ScopeOptions, ScopeType, StackType, Unsubscribe, stateCallback, stateCallbackAsync };