@zvenigora/ng-eval-core 0.5.0 → 0.6.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.
package/README.md CHANGED
@@ -141,7 +141,41 @@ try {
141
141
 
142
142
  The budget is refilled per outermost `eval` call, not per state — so the `createState` + repeated `eval` style does not erode one budget across independent evaluations, and an arrow function that outlives the walk that created it does not carry that walk's spent budget into a later call.
143
143
 
144
- **It bounds time, not memory.** `state.result.trace` gains an entry per pushed value and is never reset, so a long-running loop's trace grows as iterations × nodes and that allocation is paid before the throw. With `maxIterations: Infinity` there is no bound at all; prefer a large finite number.
144
+ **It bounds time; `maxTraceItems` bounds the memory.** `state.result.trace` gains an entry per pushed value, so before that bound a long-running loop's trace grew as iterations × nodes — 700,007 entries and ~36 MB for a 100,000-iteration loop evaluated through `eval`. That loop is *not* stopped by the default budget: it charges exactly 100,000 and completes. Where the budget does stop a loop, the whole allocation was paid before the throw.
145
+
146
+ ### Bounding the trace
147
+
148
+ `state.result.trace` records every value the evaluator pushes, and it spans **every evaluation run on one state**, not just the last. `maxTraceItems` bounds how many entries it keeps. It defaults to **10,000** — roughly 0.5 MB, and three orders of magnitude above anything a hand-written expression produces.
149
+
150
+ ```javascript
151
+ const state = service.createState({ a: 10 });
152
+ service.eval('2 + 3 * a', state);
153
+
154
+ state.result.trace.length; // 7
155
+ state.result.traceTruncated; // false
156
+ state.result.tracePushCount; // 7
157
+ ```
158
+
159
+ The **head** is kept, in order, so `trace[0]` is still the first thing evaluated. Once a push is actually dropped:
160
+
161
+ - **`state.result.traceTruncated`** turns `true` and stays true — no entry is appended to the trace to say so, because every row in it describes a real node. A walk of exactly `maxTraceItems` pushes leaves it `false`; nothing was lost.
162
+ - **`state.result.tracePushCount`** goes on counting every push, which is the number the trace no longer tells you.
163
+
164
+ ```javascript
165
+ const state = service.createState({}, { maxIterations: Infinity });
166
+ service.eval('for (let i = 0; i < 100000; i++) { i }', state);
167
+
168
+ state.result.trace.length; // 10000
169
+ state.result.traceTruncated; // true
170
+ state.result.tracePushCount; // 700007
171
+ ```
172
+
173
+ Two values are special, and both are honoured rather than treated as falsy:
174
+
175
+ - **`0`** disables tracing — `trace.length` stays `0` and `traceTruncated` stays `false`, while `tracePushCount` stays accurate, so a caller who turns tracing off for the allocation keeps the walk-size figure.
176
+ - **`Infinity`** restores the unbounded behaviour exactly.
177
+
178
+ **`state.result.clearTrace()`** is the only reset. It empties the trace and both counters, in place — the array `state.result.trace` returns is the same instance for the life of the result, so a reference you are holding stays live across the call. Under the `createState` + repeated `eval` style, call it before an evaluation to make the trace describe only that walk.
145
179
 
146
180
  ### Evaluation hooks
147
181
 
@@ -242,7 +276,7 @@ Two things to know about it:
242
276
  const state = service.createState(context, { hooks });
243
277
  ```
244
278
 
245
- One thing the library *does* do to a registry you own: `EvalService.ngOnDestroy()` clears the registries of the states it created, adopted ones included, so that a registry outliving the service cannot keep those states and their AST nodes reachable. Do not share one registry with a state whose lifetime is meant to outlast the service.
279
+ The library never clears a registry you own. `EvalService.ngOnDestroy()` does not touch it, whichever method you passed it to, and up to 0.5.0 it cleared the registries of the states `createState` built. So a hook that keeps a state, by capturing it or by storing `event.state`, keeps that state and its context reachable for as long as the registry is. Release them in the teardown that owns the registry, such as your component's `ngOnDestroy` or a `DestroyRef.onDestroy` callback: call the unsubscribe that `on` / `onRead` returned, or `hooks.clear()`.
246
280
 
247
281
  #### `completed: false` events
248
282
 
@@ -1259,6 +1259,33 @@ class EvalResult {
1259
1259
  get trace() {
1260
1260
  return this._trace;
1261
1261
  }
1262
+ /**
1263
+ * Whether {@link trace} stopped short of everything this state pushed,
1264
+ * because `options.maxTraceItems` was reached.
1265
+ *
1266
+ * **Latches.** Once true it stays true until {@link clearTrace}, however many
1267
+ * evaluations run in between, because the trace does: it spans every
1268
+ * evaluation run on this result, so a flag that cleared per walk would
1269
+ * describe a different array than the one beside it.
1270
+ *
1271
+ * False under `maxTraceItems: 0`, which is a caller asking for no trace
1272
+ * rather than a trace that lost something.
1273
+ */
1274
+ get traceTruncated() {
1275
+ return this._traceTruncated;
1276
+ }
1277
+ /**
1278
+ * How many values were pushed for tracing since this result was built or last
1279
+ * cleared by {@link clearTrace} - which is what {@link trace} no longer tells
1280
+ * you once {@link traceTruncated} is set.
1281
+ *
1282
+ * Counts pushes, not entries kept, so it goes on rising past the bound, and
1283
+ * it stays accurate under `maxTraceItems: 0` - a caller who disabled tracing
1284
+ * for the allocation still gets the walk-size figure.
1285
+ */
1286
+ get tracePushCount() {
1287
+ return this._tracePushCount;
1288
+ }
1262
1289
  /**
1263
1290
  * Gets the evaluation context.
1264
1291
  */
@@ -1302,10 +1329,74 @@ class EvalResult {
1302
1329
  * @param context The evaluation context.
1303
1330
  */
1304
1331
  constructor(context) {
1332
+ this._tracePushCount = 0;
1333
+ this._traceTruncated = false;
1305
1334
  this._stack = new Stack();
1306
1335
  this._trace = new EvalTrace();
1307
1336
  this._context = context;
1308
1337
  }
1338
+ /**
1339
+ * Records one traced push against `limit`, adding it to {@link trace} only
1340
+ * while there is room.
1341
+ *
1342
+ * **The bound is the caller's, and that is the point.** `limit` arrives from
1343
+ * `EvalState.maxTraceItems` - the *walk's* options - because this object
1344
+ * cannot read them: {@link options} returns `this._context.options`, and a
1345
+ * context can be handed to any number of evaluations carrying options none
1346
+ * of them used. Reading the bound here would reproduce the split `CLAUDE.md`
1347
+ * documents for `caseInsensitive`.
1348
+ *
1349
+ * One call, replacing the bare `trace.add` the push helpers made before, so
1350
+ * the guarded path costs an increment and a comparison rather than a second
1351
+ * call per node. `_traceTruncated` is written rather than tested-then-written
1352
+ * for the same reason: it is idempotent, and a write is cheaper than a read
1353
+ * and a branch on a path a runaway loop takes hundreds of thousands of times.
1354
+ *
1355
+ * @internal Not part of the published API.
1356
+ */
1357
+ addTraceBounded(node, value, limit) {
1358
+ this._tracePushCount++;
1359
+ if (this._trace.length >= limit) {
1360
+ // `limit` 0 is tracing turned off, not a trace that lost something.
1361
+ if (limit > 0) {
1362
+ this._traceTruncated = true;
1363
+ }
1364
+ return;
1365
+ }
1366
+ this._trace.add(node, value, this._expression);
1367
+ }
1368
+ /**
1369
+ * Empties {@link trace} and resets {@link traceTruncated} and
1370
+ * {@link tracePushCount} - the only reset any of the three has.
1371
+ *
1372
+ * **For the caller who reuses one state.** The trace spans every evaluation
1373
+ * run on this result rather than restarting per walk, which is deliberate
1374
+ * (`docs/backlog.md` A15) and is what `options.maxTraceItems` bounds.
1375
+ * A caller using the `createState` + repeated `eval` style who wants the
1376
+ * trace to describe only the walk they just ran calls this before each one.
1377
+ *
1378
+ * **The array is emptied in place, not replaced.** {@link trace} has always
1379
+ * returned the same instance for the life of the result, so a consumer
1380
+ * holding it - `const t = state.result.trace` - keeps a live reference
1381
+ * across this call rather than a stale snapshot.
1382
+ *
1383
+ * That is the **opposite** of `EvalState.resetHookBookkeeping`, which
1384
+ * replaces its record rather than emptying it so as not to mutate a
1385
+ * collection the caller holds a reference to - and both are right for their
1386
+ * own goal, which is why this says so rather than leaving a reader to find
1387
+ * one of them and read the other as a slip. Emptying in place is what
1388
+ * *releases* memory a caller-held array would otherwise pin, and that is the
1389
+ * whole of A12; replacing here would leave the old array, and every value in
1390
+ * it, alive in the caller's hand.
1391
+ *
1392
+ * Leaves {@link expression} alone: that is one string replaced per
1393
+ * evaluation, not an accumulator.
1394
+ */
1395
+ clearTrace() {
1396
+ this._trace.length = 0;
1397
+ this._tracePushCount = 0;
1398
+ this._traceTruncated = false;
1399
+ }
1309
1400
  /**
1310
1401
  * Starts the evaluation process.
1311
1402
  */
@@ -1970,6 +2061,32 @@ const readMaxIterations = (options) => {
1970
2061
  ? value
1971
2062
  : DEFAULT_MAX_ITERATIONS;
1972
2063
  };
2064
+ /**
2065
+ * How many values one state's trace holds when the caller names no other.
2066
+ *
2067
+ * Sized rather than picked: ~0.5 MB at the measured ~51 bytes an item,
2068
+ * which is three orders of magnitude above any
2069
+ * expression written by hand - the largest in this repository's own specs and
2070
+ * READMEs is a handful of nodes - and 70x below the 700,007 items a
2071
+ * 100,000-iteration loop produced unbounded.
2072
+ */
2073
+ const DEFAULT_MAX_TRACE_ITEMS = 10000;
2074
+ /**
2075
+ * The trace bound the options ask for, or the default.
2076
+ *
2077
+ * Same cast and same permissive fallback as {@link readMaxIterations}, for the
2078
+ * same reason: options are a record nothing validates, and a malformed value
2079
+ * must not become a *smaller* bound than the default by accident. `0` is
2080
+ * honoured - a caller who wants no trace at all is asking for something
2081
+ * coherent - and `Infinity` opts out, which is why the test is not
2082
+ * `Number.isFinite`.
2083
+ */
2084
+ const readMaxTraceItems = (options) => {
2085
+ const value = options?.['maxTraceItems'];
2086
+ return typeof value === 'number' && !Number.isNaN(value) && value >= 0
2087
+ ? value
2088
+ : DEFAULT_MAX_TRACE_ITEMS;
2089
+ };
1973
2090
  /**
1974
2091
  * Represents the evaluation state, which includes the context, result, and options.
1975
2092
  */
@@ -2115,6 +2232,12 @@ class EvalState {
2115
2232
  if (depth === 1) {
2116
2233
  this._iterationBudget = readMaxIterations(this._options);
2117
2234
  this._iterationsRemaining = this._iterationBudget;
2235
+ // Read here for the second half of the refill's reason, and not for the
2236
+ // first: the trace bound has no per-walk state to restore - it bounds the
2237
+ // state's trace, which spans every walk - but the options are the same
2238
+ // mutable record the caller holds, so a caller who raises it between two
2239
+ // evaluations on a held state is honoured exactly as they are above.
2240
+ this._maxTraceItems = readMaxTraceItems(this._options);
2118
2241
  }
2119
2242
  return depth;
2120
2243
  }
@@ -2142,6 +2265,22 @@ class EvalState {
2142
2265
  get iterationsRemaining() {
2143
2266
  return this._iterationsRemaining;
2144
2267
  }
2268
+ /**
2269
+ * How many values this state's trace may hold, from `options.maxTraceItems`
2270
+ * and defaulting to 10,000. `0` disables tracing; `Infinity` opts out.
2271
+ *
2272
+ * Filled by {@link enterWalk} on the outermost entry, exactly as the
2273
+ * iteration budget is - so **before the first walk this reports the default**
2274
+ * whatever the options said, and a caller reading it to discover what they
2275
+ * asked for should read it after an evaluation rather than before one.
2276
+ *
2277
+ * Read by `visitor-result.ts`'s two push helpers and nowhere else.
2278
+ *
2279
+ * @internal Not part of the published API.
2280
+ */
2281
+ get maxTraceItems() {
2282
+ return this._maxTraceItems;
2283
+ }
2145
2284
  /**
2146
2285
  * Charges one loop iteration against the budget, throwing when it is spent.
2147
2286
  *
@@ -2220,8 +2359,7 @@ class EvalState {
2220
2359
  * not named for them. `EvalHooks.clear` cannot reach any of this - the
2221
2360
  * bookkeeping belongs to the state - so without this method nothing drains
2222
2361
  * 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`.
2362
+ * reachable for as long as the state is.
2225
2363
  *
2226
2364
  * The errors matter for the same reason under the state-first style:
2227
2365
  * `createState` plus repeated `eval` on one state accumulates them for the
@@ -2249,6 +2387,7 @@ class EvalState {
2249
2387
  this._walkDepth = 0;
2250
2388
  this._iterationBudget = DEFAULT_MAX_ITERATIONS;
2251
2389
  this._iterationsRemaining = DEFAULT_MAX_ITERATIONS;
2390
+ this._maxTraceItems = DEFAULT_MAX_TRACE_ITEMS;
2252
2391
  this._context = context;
2253
2392
  this._result = result;
2254
2393
  this._options = options;
@@ -2292,10 +2431,31 @@ const defaultParserOptions = {
2292
2431
  cacheSize: 100
2293
2432
  };
2294
2433
 
2434
+ /**
2435
+ * The two push helpers each carry their own trace-bound call rather than
2436
+ * sharing one.
2437
+ *
2438
+ * **Why the read is at these two sites.** `st.maxTraceItems` is the *walk's*
2439
+ * bound. `EvalResult` cannot read it for itself: it holds a context, and a
2440
+ * context's options are not the walk's - the split `CLAUDE.md` documents for
2441
+ * `caseInsensitive`. So the option is read where `st` is in hand and passed in.
2442
+ *
2443
+ * **Why the one line is duplicated rather than factored.** A shared helper put
2444
+ * a third frame on a path taken once per node - `push` -> helper ->
2445
+ * `addTraceBounded` -> `EvalTrace.add` - to save one identical line. Measured
2446
+ * both ways at 50,000 walks of `2 + 3 * a`, the difference was inside
2447
+ * run-to-run noise, so this is not a speed claim; it is that the helper cost a
2448
+ * frame on the hot path and bought nothing, and that `addTraceBounded`'s own
2449
+ * docblock claims one call per push, which only this shape makes true.
2450
+ *
2451
+ * **The value stack is not bounded and must not be.** It is how visitors return
2452
+ * values to each other, and dropping an entry desynchronises every node above
2453
+ * it. Only the trace - which nothing in this library reads - is capped.
2454
+ */
2295
2455
  const pushVisitorResult = (node, st, value) => {
2296
2456
  const result = st.result;
2297
2457
  result.stack.push(value);
2298
- result.trace.add(node, value, st.result.expression);
2458
+ result.addTraceBounded(node, value, st.maxTraceItems);
2299
2459
  return value;
2300
2460
  };
2301
2461
  const popVisitorResult = (node, st) => {
@@ -2306,7 +2466,7 @@ const popVisitorResult = (node, st) => {
2306
2466
  const pushVisitorResultAsync = (node, st, value) => {
2307
2467
  const result = st.result;
2308
2468
  result.stack.push(value);
2309
- result.trace.add(node, value, st.result.expression);
2469
+ result.addTraceBounded(node, value, st.maxTraceItems);
2310
2470
  return value;
2311
2471
  };
2312
2472
  const popVisitorResultAsync = (node, st) => {
@@ -5299,7 +5459,11 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImpor
5299
5459
  }], ctorParameters: () => [] });
5300
5460
 
5301
5461
  /**
5302
- * Service for evaluating and parsing expressions with proper memory management.
5462
+ * Service for evaluating and parsing expressions.
5463
+ *
5464
+ * It keeps no reference to anything you pass it or anything it hands back: a
5465
+ * state from `createState`, its context and an `options.hooks` registry are
5466
+ * yours, and are collectable once you drop them (`docs/backlog.md` A8).
5303
5467
  */
5304
5468
  class EvalService extends BaseEval {
5305
5469
  /**
@@ -5308,88 +5472,31 @@ class EvalService extends BaseEval {
5308
5472
  constructor() {
5309
5473
  super(inject(ParserService));
5310
5474
  this._isDestroyed = false;
5311
- this._activeContexts = new Set();
5312
- this._activeStates = new Set();
5313
5475
  this.parserService = inject(ParserService);
5314
5476
  this.parserOptions = defaultParserOptions;
5315
5477
  }
5316
5478
  /**
5317
- * Override createState to track active contexts and states for cleanup
5479
+ * Builds a state for `eval` / `evalAsync`. The service does not keep it:
5480
+ * the state is yours, and so are its context and any `options.hooks`
5481
+ * registry it adopted (`docs/backlog.md` A8, A20). Nothing the service does
5482
+ * later, `ngOnDestroy` included, reaches it.
5318
5483
  */
5319
5484
  createState(context, options) {
5320
5485
  if (this._isDestroyed) {
5321
5486
  throw new Error('EvalService has been destroyed and cannot be used');
5322
5487
  }
5323
- const state = super.createState(context, options);
5324
- // Track active states for cleanup
5325
- this._activeStates.add(state);
5326
- // Track active contexts
5327
- if (context && typeof context === 'object') {
5328
- // Check if it's a Registry-based context (has type property)
5329
- if ('type' in context) {
5330
- this._activeContexts.add(context);
5331
- }
5332
- // For EvalContext, check if it has a nested context using bracket notation
5333
- if ('context' in context) {
5334
- const nestedContext = context['context'];
5335
- if (nestedContext && typeof nestedContext === 'object' && 'type' in nestedContext) {
5336
- this._activeContexts.add(nestedContext);
5337
- }
5338
- }
5339
- }
5340
- return state;
5488
+ return super.createState(context, options);
5341
5489
  }
5342
5490
  /**
5343
- * Clean up resources to prevent memory leaks
5491
+ * Marks the service destroyed, so that `createState`, `simpleEval` and
5492
+ * `simpleEvalAsync` throw from then on. It releases and changes nothing
5493
+ * else: the service holds no state, context or registry to release. Clear
5494
+ * a registry you passed through `options.hooks` in your own teardown, with
5495
+ * the unsubscribe `on` / `onRead` returned or `hooks.clear()`
5496
+ * (`docs/backlog.md` A8).
5344
5497
  */
5345
5498
  ngOnDestroy() {
5346
5499
  this._isDestroyed = true;
5347
- // Clean up all active states
5348
- for (const state of this._activeStates) {
5349
- try {
5350
- // Clear the stack in the result
5351
- if (state.result?.stack) {
5352
- state.result.stack.clear();
5353
- }
5354
- // Clear context if it has a clear method
5355
- if (state.context && typeof state.context === 'object' && 'clear' in state.context && typeof state.context.clear === 'function') {
5356
- state.context.clear();
5357
- }
5358
- // Drop hook registrations so a long-lived closure cannot pin a
5359
- // destroyed state. This matters most for a registry the caller passed
5360
- // through `options.hooks` and still holds: one that outlives the
5361
- // service keeps every state its closures captured reachable. A
5362
- // state-owned registry would die with its state regardless.
5363
- //
5364
- // Guarded on `hasHooks` rather than reading `state.hooks`, because that
5365
- // getter builds a registry on first access - allocating inside the
5366
- // method whose job is releasing memory. The guard is exact for this
5367
- // purpose: it is false only when no hook is registered, and clearing an
5368
- // empty registry does nothing.
5369
- if (state.hasHooks) {
5370
- state.hooks.clear();
5371
- }
5372
- // Bookkeeping lives on the state and `clear` cannot reach it, so the
5373
- // open-node stack and collected errors need dropping separately.
5374
- state.resetHookBookkeeping();
5375
- }
5376
- catch (error) {
5377
- console.warn('Error cleaning up EvalState:', error);
5378
- }
5379
- }
5380
- this._activeStates.clear();
5381
- // Clean up all active contexts
5382
- for (const context of this._activeContexts) {
5383
- try {
5384
- if (context && typeof context.clear === 'function') {
5385
- context.clear();
5386
- }
5387
- }
5388
- catch (error) {
5389
- console.warn('Error cleaning up Context:', error);
5390
- }
5391
- }
5392
- this._activeContexts.clear();
5393
5500
  }
5394
5501
  /**
5395
5502
  * Evaluates the given expression.
@@ -5401,6 +5508,8 @@ class EvalService extends BaseEval {
5401
5508
  simpleEval(expression, context, options) {
5402
5509
  try {
5403
5510
  const ast = this.parse(expression);
5511
+ // Through `createState`, which a subclass may override, rather than a
5512
+ // private builder (`docs/a8/plan.md` § 2.1).
5404
5513
  const state = this.createState(context, options);
5405
5514
  if (state?.result && typeof expression === 'string') {
5406
5515
  state.result.expression = expression;
@@ -5453,6 +5562,8 @@ class EvalService extends BaseEval {
5453
5562
  simpleEvalAsync(expression, context, options) {
5454
5563
  try {
5455
5564
  const ast = this.parse(expression);
5565
+ // As in `simpleEval`. The pending frame holds the state for as long as
5566
+ // the promise it awaits is reachable, and nothing else does.
5456
5567
  const state = this.createState(context, options);
5457
5568
  if (state?.result && typeof expression === 'string') {
5458
5569
  state.result.expression = expression;