@zvenigora/ng-eval-core 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -14,6 +14,64 @@ Versions 0.1.104–0.1.107 are on npm without entries here.
14
14
 
15
15
  ---
16
16
 
17
+ ## [0.13.2] - 2026-10-22
18
+
19
+ ### Changed
20
+ - **The README states a limit of `caseInsensitive` on a context built with `new EvalContext`**: a
21
+ plain object handed to the constructor matches no case variant, even with the option passed to
22
+ the walk too, and `EvalContext.fromContext` is the way to build one that does. No code change
23
+ ([A44](../../docs/backlog.md#a44), where it was measured).
24
+
25
+ ### Fixed
26
+ - **An update converts its operand to a number once, as JavaScript does**, and uses that one
27
+ conversion for the value it writes and for its result. `x++` on `"5"` gives `5` and writes `6`,
28
+ where it gave `"5"` and wrote `"51"`; an object that does not convert to a number, or a
29
+ non-numeric string, gives `NaN` and writes `NaN`, where `++` concatenated and a postfix update
30
+ gave the operand as read; and an update of a BigInt updates it, where it threw. An operand that
31
+ cannot convert, a Symbol or a throwing `valueOf`, throws before anything is written
32
+ ([A41](../../docs/backlog-retired.md#a41)).
33
+ - **A postfix update of a listed function no longer throws after writing**: `tools.eval++` gives
34
+ `NaN` and writes `NaN`, as JavaScript does, where the write landed and the funnel then refused the
35
+ old value. The result is a number, so the funnel has nothing to refuse
36
+ ([A40](../../docs/backlog-retired.md#a40)).
37
+ - **Under `caseInsensitive`, an identifier assignment or update to a name the context resolves to
38
+ nothing writes that name**, where it wrote the key `undefined`: the string `"undefined"` on a
39
+ plain object, the value `undefined` in a `Registry`. That covers a name absent from the context
40
+ and one bound to `undefined`, as `x = 1` on `{ x: undefined }`. A context that refuses writes, as
41
+ `eval-signals`' signal context does, is now asked about the name as written, so its refusal names
42
+ it ([A43](../../docs/backlog-retired.md#a43)). The name `undefined` itself, and under
43
+ `caseInsensitive` a spelling of a literal, is refused instead: see the next entry.
44
+ - **A write that would rebind `undefined` on the context throws
45
+ `Assignment to read-only name "<name>".`**, as do, under `caseInsensitive`, a write to any
46
+ spelling of `undefined`, `null`, `true` or `false`, such as `TRUE = 0` or `Undefined++`. Up to
47
+ 0.13.1, `undefined = 1` landed on the context, and every later evaluation on it read the written
48
+ value; under `caseInsensitive` these writes went to the stray key the entry above describes. A
49
+ case variant of `undefined` is refused under a case-sensitive walk too, when the context's store
50
+ compares keys case-insensitively, as one built with `caseInsensitive` on the context alone does:
51
+ up to 0.13.1 such a write, `UNDEFINED = 1`, rebound `undefined` there. It is refused only when
52
+ nothing else binds the name: a parameter may still shadow it, and a key the context resolves to a
53
+ value other than `undefined` stays writable. A context class that overrides `set` decides these
54
+ writes itself, so a signal context still throws its own `SignalContextWriteError`
55
+ ([A46](../../docs/backlog-retired.md#a46)).
56
+
57
+ ---
58
+
59
+ ## [0.13.1] - 2026-10-22
60
+
61
+ ### Changed
62
+ - **The package README is the package's whole documentation**, and every `javascript` block in it
63
+ is executed by a case. It gains the sections the repository README held — evaluation,
64
+ compilation, async evaluation and compilation, the supported syntax, case-insensitive evaluation
65
+ and evaluation with state — and opens with Install, Sibling packages and Security, quoting each
66
+ peer range verbatim. The repository README no longer has to be read for the API. No code
67
+ change.
68
+ - **The evaluation section brought in from the repository README states the built-ins
69
+ precisely**: over the default, empty context the global built-ins are out of an expression's
70
+ reach, but the methods of the values it holds stay callable, as `'abc'.toUpperCase()` does. No
71
+ code change and no behaviour change ([F23](../../docs/backlog-retired.md#f23)).
72
+
73
+ ---
74
+
17
75
  ## [0.13.0] - 2026-10-20
18
76
 
19
77
  **The route through `this` is closed, in both halves — the value and the receiver — and the
@@ -250,7 +308,7 @@ ranges are `>=0.11.0 <0.13.0` and `>=0.12.0 <0.13.0`.
250
308
  - assigning over a listed function, `fetch = 1` or `obj.fetch = 1`, since an assignment reads
251
309
  its target before writing it;
252
310
  - updating one, `obj.fetch++`, which writes first and then throws, so the failed evaluation
253
- leaves its write behind ([A40](../../docs/backlog.md#a40));
311
+ leaves its write behind ([A40](../../docs/backlog-retired.md#a40));
254
312
  - an operator's operand, `x instanceof Function` or `obj.fetch != null`;
255
313
  - a conditional's test, `obj.fetch ? 1 : 0`;
256
314
  - a template interpolation, `` `${eval}` ``, and a declaration's initializer;
package/README.md CHANGED
@@ -1,20 +1,31 @@
1
1
  # @zvenigora/ng-eval-core
2
2
 
3
- An expression evaluator for Angular.
3
+ An expression evaluator for Angular: JavaScript expression parsing and evaluation, built on [acorn](https://github.com/acornjs/acorn) and exposed as injectable services. An expression is evaluated against a context the host supplies, and resolves names only against that context. This file is the package's whole documentation.
4
4
 
5
- The sources for this package are in the main [@zvenigora/ng-eval](https://github.com/zvenigora/ng-eval) repo.
5
+ ## Install
6
6
 
7
- This library was generated with [Nx](https://nx.dev).
7
+ ```sh
8
+ npm install --save @zvenigora/ng-eval-core
9
+ ```
10
+
11
+ Peer dependencies: `@angular/core >=19.0.0`, `acorn ^8.11.2`, `acorn-walk ^8.3.0` and `js-sha256 ^0.10.1 || ^0.11.0 || ^0.12.0 || ^1.0.0`.
12
+
13
+ ## Sibling packages
14
+
15
+ - [`@zvenigora/ng-eval-signals`](https://github.com/zvenigora/ng-eval/tree/master/modules/eval-signals#readme) — an expression over a context of signals as an Angular `Signal`, which recomputes exactly when a key the expression read has changed.
16
+ - [`@zvenigora/ng-eval-forms`](https://github.com/zvenigora/ng-eval/tree/master/modules/eval-forms#readme) — Angular form field properties driven by expressions that arrive as strings at runtime, for Reactive Forms and Signal Forms.
17
+
18
+ The sources for all three are in the [@zvenigora/ng-eval](https://github.com/zvenigora/ng-eval) repository.
8
19
 
9
- Full documentation — parsing, evaluation, compilation, async evaluation, discovery, and the `caseInsensitive` / state / scope options — is in the [repository README](https://github.com/zvenigora/ng-eval#readme). This file names the exported entry points, then documents the options that need more than a snippet.
20
+ ## Security
10
21
 
11
- **Security.** [`SECURITY.md`](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md) covers the threat model, the prototype-pollution and call-sandboxing protections, and their documented limits. It also records [reviewed external advisories](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md#reviewed-external-advisories) — advisories raised against related projects and whether this library shares the defect. [GHSA-pj3p-xpg7-h7gw](https://github.com/Zvenigora/jse-eval/security/advisories/GHSA-pj3p-xpg7-h7gw), the case-insensitive guard bypass reported against the separate `@zvenigora/jse-eval` package, **does not apply to `@zvenigora/ng-eval-core`**: this library does not depend on `jse-eval`, and the advisory's proof-of-concept was run against this evaluator and is blocked. Note that ng-eval does not attempt to be a complete sandbox — see the threat model before evaluating untrusted expressions.
22
+ **ng-eval is not a sandbox.** An expression reaches whatever its context holds, and every function in the context runs with the host's privileges. [`SECURITY.md`](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md) covers the threat model, the protections the code has, and their [documented limits](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md#documented-limits) — read it before evaluating an expression you did not write. [GHSA-qrqj-3445-3rjx](https://github.com/Zvenigora/ng-eval/security/advisories/GHSA-qrqj-3445-3rjx), dangerous functions and the evaluation context reachable past the call sandbox, affects `@zvenigora/ng-eval-core` up to 0.12.1 and is fixed in 0.13.0. `SECURITY.md` also records [reviewed external advisories](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md#reviewed-external-advisories) — advisories raised against related projects and whether this library shares the defect. [GHSA-pj3p-xpg7-h7gw](https://github.com/Zvenigora/jse-eval/security/advisories/GHSA-pj3p-xpg7-h7gw), the case-insensitive guard bypass reported against the separate `@zvenigora/jse-eval` package, **does not apply to `@zvenigora/ng-eval-core`**: this library does not depend on `jse-eval`, and the advisory's proof-of-concept was run against this evaluator and is blocked.
12
23
 
13
24
  ## Exported entry points
14
25
 
15
- The [repository README](https://github.com/zvenigora/ng-eval#readme) walks through each of these in full. They are named here because they are what installing this package gives you: a symbol documented only in the repository README is one the consumer who installed the package cannot read about.
26
+ Each service below is documented in its own section. `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout.
16
27
 
17
- `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout the sections below.
28
+ Each service also has a form that needs no injector. The free functions `parse`, `extract`, `evaluate`, `evaluateAsync`, `compile`, `call`, `compileAsync` and `callAsync` are what the services call. `parse` takes the expression text; `extract`, `compile` and `compileAsync` take the AST node `parse` returns, not a string; and `evaluate`, `evaluateAsync`, `call` and `callAsync` take an `EvalState`, which `EvalState.fromContext(context, options)` builds.
18
29
 
19
30
  ### Parsing — `ParserService`
20
31
 
@@ -27,6 +38,124 @@ const ast = service.parse('1 + foo'); // an ESTree AST
27
38
  ast.type; // 'BinaryExpression'
28
39
  ```
29
40
 
41
+ The result of the parse is an AST (abstract syntax tree):
42
+
43
+ ```json
44
+ {
45
+ "type": "BinaryExpression",
46
+ "start": 0,
47
+ "end": 7,
48
+ "left": {
49
+ "type": "Literal",
50
+ "start": 0,
51
+ "end": 1,
52
+ "value": 1,
53
+ "raw": "1"
54
+ },
55
+ "operator": "+",
56
+ "right": {
57
+ "type": "Identifier",
58
+ "start": 4,
59
+ "end": 7,
60
+ "name": "foo"
61
+ }
62
+ }
63
+ ```
64
+
65
+ `ParserService` parses with `ecmaVersion: 2020`, keeps a cache of 100 parses, and sets `extractExpressions`, so `parse` returns the expression itself — the `BinaryExpression` above — rather than the `Program` around it. `EvalService`, `CompilerService` and `DiscoveryService` parse with `extractExpressions` off, into a `Program`, which is what lets an expression be a statement list.
66
+
67
+ ### Evaluation — `EvalService`
68
+
69
+ `simpleEval(expression, context)` evaluates an expression against the given context. Without a context, the context is empty.
70
+
71
+ ```javascript
72
+ import { EvalService } from '@zvenigora/ng-eval-core';
73
+
74
+ const service = inject(EvalService);
75
+
76
+ const expression = '2 + 3 * a';
77
+ const context = { a: 10 };
78
+ const result = service.simpleEval(expression, context); // 32
79
+ ```
80
+
81
+ Since the default context is empty, an expression cannot reach JavaScript's global built-ins, such as `Math`, `parseInt` or `Date`. The methods of the values it holds stay callable: `'abc'.toUpperCase()` and `[3, 1, 2].map(x => x * 2)` run over an empty context. To allow the globals, add them to the context passed to `simpleEval`:
82
+
83
+ ```javascript
84
+ const context = {
85
+ Date,
86
+ Array,
87
+ Object,
88
+ encodeURI,
89
+ decodeURI,
90
+ isFinite,
91
+ isNaN,
92
+ JSON,
93
+ Math,
94
+ parseFloat,
95
+ parseInt,
96
+ RegExp,
97
+ // ...myCustomPropertiesAndFunctions,
98
+ };
99
+ service.simpleEval('Math.max(1, 2) + parseInt("40")', context); // 42
100
+ ```
101
+
102
+ ### Compilation — `CompilerService`
103
+
104
+ ```javascript
105
+ import { CompilerService } from '@zvenigora/ng-eval-core';
106
+
107
+ const service = inject(CompilerService);
108
+
109
+ const fn = service.compile('x + y');
110
+ const context = { x: 1, y: 2 };
111
+ const options = { caseInsensitive: false };
112
+ const value = service.simpleCall(fn, context, options); // 3
113
+ ```
114
+
115
+ ### Async evaluation and compilation
116
+
117
+ Asynchronous evaluation is limited, and based on promises. The walk itself is synchronous, and a promise is awaited once it has finished, wherever it sits in the result: the result itself, or an element or property of an array or object the expression builds.
118
+
119
+ ```javascript
120
+ import { EvalService } from '@zvenigora/ng-eval-core';
121
+
122
+ const service = inject(EvalService);
123
+
124
+ const context = {
125
+ one: 1,
126
+ two: 2,
127
+ asyncFunc: async (a: number, b: number) => { return await (a+b); }
128
+ };
129
+ const expr = 'asyncFunc(one, two)';
130
+ const value = await service.simpleEvalAsync(expr, context); // 3
131
+
132
+ await service.simpleEvalAsync('[asyncFunc(one, two), two]', context); // [3, 2]
133
+ ```
134
+
135
+ ```javascript
136
+ import { CompilerService } from '@zvenigora/ng-eval-core';
137
+
138
+ const service = inject(CompilerService);
139
+
140
+ const context = {
141
+ one: 1,
142
+ two: 2,
143
+ promiseFunc: (a: number, b: number) => {
144
+ return new Promise((resolve) => {
145
+ setTimeout(() => {
146
+ return resolve(a + b);
147
+ }, 10);
148
+ });
149
+ }
150
+ };
151
+ const expr = 'promiseFunc(one, two)';
152
+ const fn = service.compileAsync(expr);
153
+ const result = await service.simpleCallAsync(fn, context); // 3
154
+
155
+ const nested = service.compileAsync('({ sum: promiseFunc(one, two) })');
156
+ await service.simpleCallAsync(nested, context); // { sum: 3 }
157
+ ```
158
+
30
159
  ### Discovery — `DiscoveryService`
31
160
 
32
161
  Finds every node of a given type in an expression.
@@ -76,7 +205,7 @@ const result = service.simpleEval('cat.action(args, cat.num, "times")', evalCont
76
205
  // 'Mister Whiskers says meow 3 times' - `this` is thisArg; cat.num still reads cat
77
206
  ```
78
207
 
79
- Note that an `EvalContext` may back any number of evaluations, and that `caseInsensitive` set on the context alone does not reach the walk — pass it in the evaluation options too.
208
+ Note that an `EvalContext` may back any number of evaluations, and that `caseInsensitive` set on the context alone does not reach the walk — pass it in the evaluation options too. Even then, a plain object handed to `new EvalContext` matches no case variant: build the context with `EvalContext.fromContext(object, options)` instead, which copies the object into a case-insensitive store.
80
209
 
81
210
  ### Colon-joined names — `provideColonIdentifiers`
82
211
 
@@ -123,8 +252,144 @@ service.simpleEval('({a:1}).a'); // throws SyntaxError - write (
123
252
 
124
253
  **Read events and dependencies stay dotted.** A colon-joined name is one segment of a `path`: reading `obj.Q2:3` reports the `key` `Q2:3` and the `path` `obj.Q2:3`, and `createDependencyTracker()` records `obj.Q2:3`. Split a path on `.`, never on `:`.
125
254
 
255
+ ## Supported syntax
256
+
257
+ ### ESTree nodes supported
258
+
259
+ The project has been tested with the following node types:
260
+ - `BinaryExpression`
261
+ - `Identifier`
262
+ - `Literal`
263
+ - `CallExpression` *potentially unsafe*
264
+ - `AwaitExpression`
265
+ - `ConditionalExpression`
266
+ - `MemberExpression`
267
+ - `ArrayExpression`
268
+ - `UnaryExpression`
269
+ - `LogicalExpression`
270
+ - `ThisExpression` — only as the object of a member access, `this.k`, `this['k']` or `this.fn()`;
271
+ anywhere else it throws, since `@zvenigora/ng-eval-core` 0.13.0. Up to 0.12.1 it evaluated to the
272
+ evaluation context
273
+ - `NewExpression`
274
+ - `TemplateLiteral`
275
+ - `TaggedTemplateExpression`
276
+ - `ObjectExpression`
277
+ - `AssignmentExpression` — to an identifier or a member, parenthesised or not. Destructuring
278
+ assignment, `[a, b] = arr` or `({ m } = o)`, throws `Unsupported assignment target`;
279
+ before `@zvenigora/ng-eval-core` 0.7.0 it silently did nothing. An identifier write that
280
+ would shadow `undefined`, or under `caseInsensitive` a literal, throws
281
+ `Assignment to read-only name`, since 0.13.2
282
+ - `UpdateExpression` — to an identifier or a member, parenthesised or not
283
+ - `ArrowFunctionExpression` *potentially unsafe* (AssignmentPattern is not implemented, so a
284
+ destructuring default — `({ a = 1 }) => a` — is rejected rather than defaulted)
285
+ - `SequenceExpression` — each expression in order, the value the last one's
286
+
287
+ Object and array destructuring bind the names JavaScript binds, in parameter lists and in
288
+ `let` / `const` declarations alike: shorthand, renaming, nesting, literal and computed keys,
289
+ and rest elements. **Before `@zvenigora/ng-eval-core` 0.5.0 the renaming forms bound the wrong
290
+ names** — see the 0.5.0 entry in the
291
+ [CHANGELOG](https://github.com/zvenigora/ng-eval/blob/master/modules/eval-core/CHANGELOG.md#050---2026-09-17).
292
+
293
+ Statements, since `@zvenigora/ng-eval-core` 0.4.0:
294
+
295
+ - `Program`
296
+ - `ExpressionStatement`
297
+ - `EmptyStatement`
298
+ - `BlockStatement`
299
+ - `VariableDeclaration` — `let` and `const` only; `var` is rejected
300
+ - `IfStatement`
301
+ - `ForStatement` — the classic three-part form only
302
+
303
+ **Every other statement type is rejected with `Unsupported statement type: <type>`.**
304
+ That is a change of kind, not only of coverage: before 0.4.0 an unsupported statement was
305
+ handed to `acorn-walk`'s base walker, which walked the subtree as an expression and left
306
+ whatever it pushed on the value stack — so `throw 1` evaluated to `1` and threw nothing, and
307
+ `switch (1) { case 1: 2 }` evaluated to `2`. See the
308
+ [CHANGELOG](https://github.com/zvenigora/ng-eval/blob/master/modules/eval-core/CHANGELOG.md#040---2026-09-15) for the full before/after table.
309
+
310
+ `WhileStatement`, `DoWhileStatement`, `ForInStatement`, `ForOfStatement`, `SwitchStatement`,
311
+ `TryStatement`, `ThrowStatement`, `LabeledStatement`, `BreakStatement`, `ContinueStatement`,
312
+ `FunctionDeclaration` and `ClassDeclaration` are among the rejected types. The three that
313
+ imply **abrupt completion** and are reachable — `break`, `continue`, `throw` — are out by
314
+ design rather than by schedule: the evaluator has no completion record to carry them, and
315
+ adding one is a redesign of the walker rather than another visitor. `return` never reaches
316
+ the evaluator at all: an expression is parsed outside any function, so `return 1` is a parse
317
+ error (`'return' outside of function`) both before and after 0.4.0.
318
+
319
+ ### How statements differ from JavaScript
320
+
321
+ Seven deliberate divergences, each a documented rule rather than an accident:
322
+
323
+ 1. **An arrow function with a block body returns the block's completion value**, where
324
+ JavaScript returns `undefined` without a `return`. `x => { 1 }` yields `1` here. With
325
+ `return` unsupported, the completion value is the only answer available that is not an
326
+ error.
327
+ 2. **`const` reassignment throws at the write, not at parse time.**
328
+ 3. **An unsupported statement type throws**, where before 0.4.0 it returned a value.
329
+ 4. **No hoisting.** A `let` binds when its declaration is reached; reading it earlier reads
330
+ the enclosing context rather than raising a temporal-dead-zone error.
331
+ 5. **Closures do not capture their lexical scope.** An arrow resolves its free variables
332
+ against the context *as it is when it is called*, not as it was where it was written — so
333
+ `for (let i = 0; i < 3; i++) { fns.push(() => i) }` leaves three functions that all read
334
+ whatever `i` resolves to at call time. This is pre-existing behaviour that statements
335
+ neither cause nor worsen.
336
+ 6. **A pattern form the binder does not implement throws** rather than binding nothing.
337
+ 7. **A binding name on the prototype-pollution blocklist is rejected — including as an arrow
338
+ function parameter.** `(toString => toString)(1)` returned `1` before 0.4.0 and now
339
+ throws; so do `constructor`, `prototype`, `valueOf`, `hasOwnProperty`, `isPrototypeOf`,
340
+ `propertyIsEnumerable`, `toLocaleString` and the four `__define`/`__lookup` accessors.
341
+ Binding writes share the blocklist with every other write site, which is wider than the
342
+ threat — only `__proto__` is an actual write vector — and is kept wide so that "is this
343
+ name blocked?" does not depend on which visitor reached it. From 0.4.0 to 0.6.x a throw
344
+ from inside a called arrow function was re-wrapped, so this one arrived as
345
+ `Function call error: Access to dangerous property "toString" is blocked…`; since 0.7.0
346
+ it arrives as thrown, without the prefix.
347
+
126
348
  ## Options
127
349
 
350
+ To change the evaluator's default behaviour, pass `options`: the last argument of `simpleEval`, `simpleCall` and `createState`.
351
+
352
+ ### Case-insensitive evaluation
353
+
354
+ While JavaScript is a case-sensitive language, some may find it hard to use. To provide case-insensitive evaluation, set `caseInsensitive` to `true`. It applies to identifiers and to member names alike.
355
+
356
+ ```javascript
357
+ import { EvalService } from '@zvenigora/ng-eval-core';
358
+
359
+ const service = inject(EvalService);
360
+
361
+ const options = { caseInsensitive: true };
362
+
363
+ const expression = '2 + 3 * A';
364
+ const context = { a: 10 };
365
+ const result = service.simpleEval(expression, context, options); // 32
366
+
367
+ service.simpleEval('User.NAME', { user: { name: 'Ann' } }, options); // 'Ann'
368
+ ```
369
+
370
+ ### Evaluation with state
371
+
372
+ `eval(expression, state)` evaluates against a state rather than a context. The state holds the context, the result and the options; the visitors read it as they walk, so it can extend the evaluator — for example with the execution history, or the time each node type took. `simpleEval` builds a state internally and never hands it back, so reading back what the walk recorded — `nodeTimings`, the trace, collected hook errors — needs this style.
373
+
374
+ ```javascript
375
+ import { EvalService } from '@zvenigora/ng-eval-core';
376
+
377
+ const service = inject(EvalService);
378
+
379
+ const expression = '2 + 3 * A';
380
+ const context = { a: 10 };
381
+ const options = { caseInsensitive: true };
382
+ const state = service.createState(context, options);
383
+ // update the state if required - register hooks on state.hooks, for example
384
+
385
+ const result = service.eval(expression, state); // 32
386
+
387
+ // read the state: the execution history, one entry per value the walk pushed
388
+ state.result.trace.map((item) => `${item.expression} = ${item.value}`);
389
+ // ['2 = 2', '3 = 3', 'A = 10', '3 * A = 30', '2 + 3 * A = 32', '2 + 3 * A = 32', '2 + 3 * A = 32']
390
+ state.result.traceTruncated; // false - did it stop short? see `maxTraceItems`
391
+ ```
392
+
128
393
  ### Per-node timing
129
394
 
130
395
  Set `trackTime` to `true` to accumulate per-node-type timings for an evaluation. They are read back from the state as `nodeTimings`, so this option needs the state-first style — `simpleEval` builds its state internally and never hands it back.
@@ -693,6 +693,16 @@ const setContextValue = (context, key, value) => {
693
693
  object[key] = value;
694
694
  }
695
695
  };
696
+ /**
697
+ * Whether `store` compares its keys case-insensitively: a `Registry` built
698
+ * with `caseInsensitive`. A case-sensitive `Registry` and a plain record are
699
+ * read by exact key, whatever the options of the context that holds them.
700
+ *
701
+ * The one copy of that test. `eval-context.ts`'s `spellingIn` asks it to find
702
+ * a key's stored spelling, and `variable-declaration.ts` asks it of the store
703
+ * a write lands in (`docs/backlog-retired.md` A46).
704
+ */
705
+ const isCaseInsensitiveStore = (store) => store instanceof Registry && store.options['caseInsensitive'] === true;
696
706
 
697
707
  /**
698
708
  * Opens a node: records it as open and fires the registered 'before' hooks.
@@ -2740,12 +2750,42 @@ const popVisitorResultAsync = (node, st) => {
2740
2750
  return value;
2741
2751
  };
2742
2752
 
2753
+ /**
2754
+ * The names `identifier.ts` resolves to a built-in value under
2755
+ * `caseInsensitive`, in any spelling, when the context holds none of them.
2756
+ * ESTree parses `undefined` as an `Identifier`, and under that option a case
2757
+ * variant of `null`, `true` or `false` is one too, so each reaches the
2758
+ * identifier visitor rather than the literal one.
2759
+ */
2743
2760
  const literals = Registry.fromObject({
2744
2761
  'undefined': undefined,
2745
2762
  'null': null,
2746
2763
  'true': true,
2747
2764
  'false': false,
2748
2765
  }, { caseInsensitive: true });
2766
+ /**
2767
+ * Whether `name`, as written, is one the evaluator resolves to a built-in
2768
+ * value, for a write that would land in `store`: `undefined` in both modes,
2769
+ * and under `caseInsensitive` any spelling of a {@link literals} name.
2770
+ * Case-sensitively, `TRUE` and `NULL` are ordinary names, and `true`, `null`
2771
+ * and `false` never reach an identifier.
2772
+ *
2773
+ * **Any spelling of `undefined` also counts when the store compares keys
2774
+ * case-insensitively**, whatever the walk's mode. A case-insensitive context
2775
+ * walked with case-sensitive options is the split the README warns of, and
2776
+ * there `UNDEFINED = 1` lands in a store whose `get('undefined')` then finds
2777
+ * it, so the case-sensitive read of `undefined` would read the write. `TRUE`,
2778
+ * `NULL` and `FALSE` need no such clause: a case-sensitive walk never reads
2779
+ * them as literals. The length test keeps the lowering off every other write.
2780
+ *
2781
+ * `NaN` and `Infinity` are not among them: the evaluator resolves neither, so
2782
+ * on an empty context each reads `undefined` (`docs/backlog-retired.md` A46).
2783
+ */
2784
+ const isLiteralName = (name, caseInsensitive, store) => name === 'undefined'
2785
+ || (caseInsensitive
2786
+ ? literals.has(name)
2787
+ : name.length === 9 && name.toLowerCase() === 'undefined' && isCaseInsensitiveStore(store));
2788
+
2749
2789
  /**
2750
2790
  * Reports a resolved identifier read to the hook layer.
2751
2791
  *
@@ -3884,6 +3924,40 @@ const variableDeclarationVisitor = (node, st, callback) => {
3884
3924
  pushVisitorResult(node, st, EMPTY_COMPLETION);
3885
3925
  afterVisitor(node, st);
3886
3926
  };
3927
+ /**
3928
+ * Refuses a write that would rebind a name the evaluator resolves to a
3929
+ * built-in value - `undefined`, and under `caseInsensitive` a case variant of
3930
+ * a literal - on the context (`docs/backlog-retired.md` A46). Up to 0.13.1 a
3931
+ * write to `undefined` landed like any other key, and `identifier.ts` reads
3932
+ * the context before its literals, so every later evaluation on that context
3933
+ * read the written value; A43's fallback would have done the same for a case
3934
+ * variant of a literal.
3935
+ * A case variant of `undefined` is refused under a case-sensitive walk too,
3936
+ * when the store the write lands in - the context's original, which `set`
3937
+ * writes - compares keys case-insensitively, since its `get('undefined')`
3938
+ * would then find the write.
3939
+ *
3940
+ * Called only when no pushed scope binds the name, so a parameter or a `let`
3941
+ * may still shadow it, as in JavaScript. The cheap name test runs first, so
3942
+ * any other name pays nothing more. A key the context resolves to a value
3943
+ * other than `undefined` stays writable - one the host holds, or one a lookup
3944
+ * answers; a key held as `undefined` resolves to nothing, as A43 counts it.
3945
+ *
3946
+ * **A context class that overrides `set` decides these writes itself.** `set`
3947
+ * is resolved by class, as every method the evaluator calls on a context is
3948
+ * (`context-method.ts`), so an own property planted on the instance cannot
3949
+ * pass for an override. `eval-signals`' signal context overrides `set` to
3950
+ * refuse every key write with `SignalContextWriteError`, which `eval-forms`
3951
+ * rethrows by class past its error policy; refusing here first would have
3952
+ * replaced that error with this one.
3953
+ */
3954
+ const refuseReadOnlyName = (context, name, caseInsensitive) => {
3955
+ if (isLiteralName(name, caseInsensitive, context.original)
3956
+ && context.getKey(name) === undefined
3957
+ && prototypeMethod(context, 'set') === EvalContext.prototype.set) {
3958
+ throw new Error(`Assignment to read-only name "${name}".`);
3959
+ }
3960
+ };
3887
3961
  /**
3888
3962
  * Assigns to `key`, preferring a binding the evaluation itself created.
3889
3963
  *
@@ -3925,6 +3999,7 @@ const assignToBinding = (st, key, value, name) => {
3925
3999
  }
3926
4000
  const scope = contextScopeHolding(st.context, key);
3927
4001
  if (!scope) {
4002
+ refuseReadOnlyName(st.context, name, !!st.options?.caseInsensitive);
3928
4003
  contextSet(st.context, key, value);
3929
4004
  return;
3930
4005
  }
@@ -3978,8 +4053,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
3978
4053
  throw new Error(`Context is not set.`);
3979
4054
  }
3980
4055
  else if (target.type === 'Identifier') {
4056
+ // `getKey` gives `undefined` when `get` finds nothing - an absent name, or
4057
+ // one bound to `undefined` - and that key was written as it came
4058
+ // (`docs/backlog-retired.md` A43). The name as written is the fallback
4059
+ // `identifier.ts` already takes.
3981
4060
  const key = st.options?.caseInsensitive
3982
- ? st.context.getKey(target.name)
4061
+ ? st.context.getKey(target.name) ?? target.name
3983
4062
  : target.name;
3984
4063
  const value = func(left, right);
3985
4064
  // Scope first, the caller's object second. Before Phase 2 this was
@@ -4006,10 +4085,6 @@ const assignmentExpressionVisitor = (node, st, callback) => {
4006
4085
  afterVisitor(node, st);
4007
4086
  };
4008
4087
 
4009
- const updateOperators = {
4010
- '++': (value) => { return value + 1; },
4011
- '--': (value) => { return value - 1; },
4012
- };
4013
4088
  const updateExpressionVisitor = (node, st, callback) => {
4014
4089
  beforeVisitor(node, st);
4015
4090
  // `(a)++` under `preserveParens` arrives wrapped (`docs/backlog-retired.md` A2).
@@ -4018,29 +4093,43 @@ const updateExpressionVisitor = (node, st, callback) => {
4018
4093
  throw new Error(`Context is not set.`);
4019
4094
  }
4020
4095
  else if (target.type === 'Identifier') {
4096
+ // The fallback `assignment-expression.ts` takes, for the same reason
4097
+ // (`docs/backlog-retired.md` A43).
4021
4098
  const key = st.options?.caseInsensitive
4022
- ? st.context.getKey(target.name)
4099
+ ? st.context.getKey(target.name) ?? target.name
4023
4100
  : target.name;
4024
4101
  const value = st.context?.get(key);
4025
- const newValue = updateOperators[node.operator](value);
4102
+ // The update run natively on a copy of the operand. JavaScript converts
4103
+ // the operand to a numeric once, then adds or subtracts, and a postfix
4104
+ // update gives that converted old value. `value + 1` on the operand as
4105
+ // read concatenated a string or an object, gave a postfix result
4106
+ // unconverted, and threw on a BigInt (`docs/backlog-retired.md` A41).
4107
+ // Running the operator itself is the conversion, BigInt included, which
4108
+ // `Number()` or a unary `+` is not. It runs before the write, here and in
4109
+ // the member branch, so an operand that cannot convert - a Symbol, a
4110
+ // throwing `valueOf` - throws with nothing written.
4111
+ let updated = value;
4112
+ const old = node.operator === '++' ? updated++ : updated--;
4026
4113
  // The same redirection as `assignment-expression.ts`, and the site that
4027
4114
  // matters for `for (let i = 0; …; i++)`: without it every loop counter this
4028
4115
  // library runs would be written into the consumer's context object, and
4029
4116
  // left there.
4030
- assignToBinding(st, key, newValue, target.name);
4031
- pushVisitorResult(node, st, node.prefix ? newValue : value);
4117
+ assignToBinding(st, key, updated, target.name);
4118
+ pushVisitorResult(node, st, node.prefix ? updated : old);
4032
4119
  }
4033
4120
  else if (target.type === 'MemberExpression') {
4034
4121
  const [object, property, value] = evaluateMember(target, st, callback);
4035
- const newValue = updateOperators[node.operator](value);
4122
+ // As in the identifier branch: one native conversion, before the write.
4123
+ let updated = value;
4124
+ const old = node.operator === '++' ? updated++ : updated--;
4036
4125
  // The same consultation as `assignment-expression.ts`'s member branch.
4037
4126
  const created = st.createdObjects;
4038
4127
  if (created) {
4039
4128
  consultMemberWrite(st, created, object, property);
4040
4129
  }
4041
4130
  // Use safe property assignment to prevent prototype pollution
4042
- safeSetProperty(object, property, newValue);
4043
- pushVisitorResult(node, st, node.prefix ? newValue : value);
4131
+ safeSetProperty(object, property, updated);
4132
+ pushVisitorResult(node, st, node.prefix ? updated : old);
4044
4133
  }
4045
4134
  else {
4046
4135
  // Without this the visitor reached `afterVisitor` having pushed nothing,
@@ -5183,9 +5272,7 @@ const resolve = (context, key) => {
5183
5272
  * own spelling there.
5184
5273
  */
5185
5274
  const spellingIn = (holder, key) => {
5186
- if (holder instanceof Registry
5187
- && holder.options['caseInsensitive'] === true
5188
- && typeof key === 'string') {
5275
+ if (isCaseInsensitiveStore(holder) && typeof key === 'string') {
5189
5276
  const lowered = key.toLowerCase();
5190
5277
  for (const candidate of holder.keys) {
5191
5278
  if (typeof candidate === 'string' && candidate.toLowerCase() === lowered) {