@zvenigora/ng-eval-forms 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,511 @@
1
+ import { createMetadataKey, disabled, metadata, hidden } from '@angular/forms/signals';
2
+ import { EvalState, call, parse, defaultParserOptions, compile } from '@zvenigora/ng-eval-core';
3
+ import { createFieldContext, applyErrorPolicy, toVisible, toText } from '@zvenigora/ng-eval-forms';
4
+ import { simple } from 'acorn-walk';
5
+ import { computed } from '@angular/core';
6
+
7
+ /**
8
+ * Runs one compiled rule against one context, and leaves the context's scope
9
+ * stack exactly as it found it.
10
+ *
11
+ * **This is the entry point's only path to the walk, and that is the whole
12
+ * point of it** (plan S 3.3, `phase-4-plan.md` S 9.1). Every walk needs an
13
+ * `EvalState`, and outside Angular DI there are exactly two ways to get one:
14
+ * the static factory this function calls below, and the class's public
15
+ * constructor. The one construction in this package is that line, inside this
16
+ * function's body; S 6 gate 3 greps for both spellings and expects one hit and
17
+ * zero.
18
+ *
19
+ * **Neither spelling is written out in this comment, deliberately.** Gate 3 is
20
+ * a grep, and prose naming what it searches for is a standing hit on the file
21
+ * the gate exists to bless - which is what revision 10 spent a revision
22
+ * removing from that gate's third row, after a block comment in
23
+ * `reactive/src/lib/field-schema.ts` made it read as failing. A gate with a
24
+ * known pre-existing hit is one people learn to ignore.
25
+ *
26
+ * **Module-private to `/signals`, deliberately, and not merely unexported by
27
+ * omission.** Placing it in the shared core was measured against this and
28
+ * separates on one row that matters: a barrel re-exports whole modules, so a
29
+ * helper the core's `public-api.ts` can reach **is published**, permanently,
30
+ * on an entry point already released at 0.1.0 - and a published `evaluateRule`
31
+ * *is* a second path to the walk by existing, since any consumer could call it
32
+ * with a hand-built `EvalContext`. Here the set of callers is the set of files
33
+ * in this directory, which is checkable by grep. The three placement
34
+ * hypotheses that sound decisive - `/reactive` bundle weight, `@angular/core`
35
+ * leakage, FESM size - were measured and are not: ng-packagr compiles each
36
+ * entry point separately and the helper appears in `/reactive`'s FESM at zero
37
+ * bytes either way (S 3.3's table).
38
+ *
39
+ * **Why the `finally` exists.** The scope stack is the third and longest-lived
40
+ * of `eval-core`'s three stack invariants ([`CLAUDE.md`](../../../../../CLAUDE.md)):
41
+ * unlike the value stack and the open-node stack, which live on the per-walk
42
+ * `EvalState` and die with it, scopes live on the `EvalContext`. A rule holds
43
+ * its context across every invocation Angular makes, and `EvalContext.get`
44
+ * resolves `scopes` **first**, so one scope left behind shadows the source key
45
+ * of that name for the life of the form. Nothing else drains it.
46
+ *
47
+ * **Retained, not redundant.** This was written against a specific defect -
48
+ * `arrow-function-expression.ts` pushed a scope and popped it with no
49
+ * `try`/`finally`, so an arrow body that threw skipped the pop - and Phase 2
50
+ * step 0 fixed exactly that
51
+ * ([backlog A9](../../../../../docs/backlog.md#a9)). The loop stays anyway, for
52
+ * two reasons that outlive the fix - and they are not the same *kind* of
53
+ * reason, which is the part an earlier version of this docblock got wrong:
54
+ *
55
+ * - `package.json` declares `"@zvenigora/ng-eval-core": ">=0.3.0 <0.5.0"`.
56
+ * That range admits the *leaking* 0.3.0 as well as the fixed 0.4.0, so a
57
+ * supported installation can still be running the defect. **Range-dependent**:
58
+ * it would stop being true if the range were ever raised past 0.3.0.
59
+ * - `EvalContext.push` and `pop` are public methods on a published class: a
60
+ * scope can be stranded with no visitor involved at all. That is the route
61
+ * `evaluate-rule.spec.ts`'s containment cases now drive, because it is the
62
+ * one no fix inside the core's visitors can close. **True at every version**,
63
+ * and therefore the reason this loop is not removable at any peer range.
64
+ *
65
+ * **Raising the peer range does not make this removable**, and the sentence
66
+ * that used to sit here said it did - "removal is gated on raising the peer
67
+ * range" reads as a sufficient condition and is only a necessary one. Whoever
68
+ * raises it retires the first reason and leaves the second untouched. The same
69
+ * error was in the plan's step 0b, corrected there in Phase 2 step 7; this copy
70
+ * of it was corrected in step 8.
71
+ *
72
+ * A third reason has expired and is recorded as gone rather than silently
73
+ * dropped: this was also the backstop for the scope-push sites Phase 2 was
74
+ * adding to the core. `Program`, `BlockStatement` and `ForStatement` all
75
+ * shipped in 0.4.0, each popping in a `finally`.
76
+ *
77
+ * The unwind is a loop to a **depth mark**, not a single `pop()`: one throw
78
+ * can leave more than one scope open, and unwinding to the bottom would drain
79
+ * scopes this call did not push - `evaluate()` is re-entrant through the arrow
80
+ * closure, so the depth on entry is not reliably zero.
81
+ *
82
+ * This helper deliberately does **not** apply the error policy. The throw
83
+ * propagates, and `applyErrorPolicy` sits outside this call in the `LogicFn`
84
+ * body (S 3.5) - containment first, then the policy - so an expression that
85
+ * throws is contained whether the consumer asked for `'throw'`, `'undefined'`
86
+ * or a handler.
87
+ *
88
+ * @param compiled - `eval-core`'s own `stateCallback`, from
89
+ * `compile(parse(expression, ...))`. A registrar compiles
90
+ * once and holds the callback; nothing recompiles per
91
+ * invocation.
92
+ * @param context - The rule's context, from `ModelSource.createRuleContext()`.
93
+ * One per rule per `form()` (S 3.6), reused across every
94
+ * invocation of that rule.
95
+ * @param options - The walk's options, which are **not** the context's:
96
+ * visitors read `caseInsensitive` off the state, so it has to
97
+ * reach both to correct property names as well as identifier
98
+ * keys.
99
+ */
100
+ const evaluateRule = (compiled, context, options) => {
101
+ const depth = context.scopes.length;
102
+ // `fromContext` short-circuits on identity for an `EvalContext`, so this
103
+ // builds a fresh per-walk state around the *same* context rather than
104
+ // copying it - which is what lets one context back many invocations, and
105
+ // equally what makes a leaked scope durable.
106
+ const state = EvalState.fromContext(context, options);
107
+ try {
108
+ return call(compiled, state);
109
+ }
110
+ finally {
111
+ while (context.scopes.length > depth) {
112
+ context.pop();
113
+ }
114
+ }
115
+ };
116
+
117
+ /**
118
+ * Throws if the expression names an identifier that is an own property of
119
+ * `Object.prototype` (plan S 3.8).
120
+ *
121
+ * **The failure this prevents is silent and truthy.** `createSignalContext`
122
+ * builds its context on an empty `original` object, and `EvalContext.get`
123
+ * consults `original` *before* `lookups` - so an identifier like
124
+ * `constructor` resolves off the prototype and never reaches the model
125
+ * resolver at all. A function is truthy, so `toVisible` says visible and
126
+ * `evalVisible(p.city, 'constructor')` renders the field with no data, no
127
+ * error and nothing logged (Q10, Q11). It is not GHSA-pj3p-xpg7-h7gw's
128
+ * case-variant bypass: the behaviour is identical with and without
129
+ * `caseInsensitive`, and `CONSTRUCTOR` resolves `undefined` in both.
130
+ *
131
+ * **The subject is the expression, not the field name** - which is what makes
132
+ * this the same answer `/reactive` gives (`field-schema.ts:172-178`) on a
133
+ * different input. There the field names arrive in the library's own
134
+ * `FieldSchema[]`; here the paths are compile-time `p.city` tokens and the
135
+ * library never sees a name it could validate. What it does see, at
136
+ * registration, is the expression. A model key nobody names harms nobody, so
137
+ * the expression is the complete subject and this check inherits none of the
138
+ * growing-key-set problem a scan of the model would have.
139
+ *
140
+ * **The predicate is normative and any list of names is illustrative**
141
+ * (S 3.8.1, revision 18 item 2). `Object.getOwnPropertyNames(Object.prototype)`
142
+ * is twelve names: the seven a form author might plausibly type -
143
+ * `constructor`, `toString`, `valueOf`, `hasOwnProperty`, `isPrototypeOf`,
144
+ * `propertyIsEnumerable`, `toLocaleString` - plus `__proto__` and the four
145
+ * `__define*` / `__lookup*` accessors. Hard-coding the seven would satisfy
146
+ * every other criterion of this step, which is why one of the other five is
147
+ * asserted.
148
+ *
149
+ * **Deliberately over-rejecting** (S 3.8.1). An arrow's own frame is
150
+ * genuinely safe - `EvalContext.get` resolves `scopes` at step 1 and
151
+ * `original` at step 2, so a bound `valueOf` shadows the prototype and
152
+ * resolves correctly - and `'[1].map(valueOf => valueOf)'` is refused anyway.
153
+ * The scope-aware alternative is a second copy of `eval-core`'s frame logic,
154
+ * tracking two scope-pushing visitors this library does not own, that fails
155
+ * by *under*-rejecting when it drifts. The costs are asymmetric: a named
156
+ * error at registration, whose fix is renaming a parameter, against a field
157
+ * that always renders in production.
158
+ *
159
+ * **`acorn-walk`'s `simple`, borrowed rather than hand-rolled** (S 0.1) - the
160
+ * same package `eval-core` walks with. Two of its properties are load-bearing
161
+ * rather than incidental, and both are pinned by specs:
162
+ *
163
+ * - its base walker descends into `node.property` only when `node.computed`,
164
+ * so `user.constructor` is **not** seen as an `Identifier`. That is
165
+ * `eval-core`'s prototype-pollution guard's business and the stated upper
166
+ * bound of this one;
167
+ * - `base.Function` walks parameters under the `"Pattern"` override, which
168
+ * `simple` suppresses, so a **binding** is never visited while a
169
+ * **reference** is. `'[1].map(valueOf => 1)'` therefore registers.
170
+ *
171
+ * A hand-rolled scan over every node would reject both, which is the
172
+ * difference the borrow is checked at.
173
+ *
174
+ * @param expression the source, named in the message so an author can tell
175
+ * which of a schema's rules to fix
176
+ * @param node the AST the registrar has just parsed. Typed
177
+ * `ReturnType<typeof parse>` rather than `AnyNode`: `eval-core` publishes
178
+ * `AnyNodeTypes` and not `AnyNode`, so spelling it out would force
179
+ * `import type { AnyNode } from 'acorn'` - an undeclared dependency whose
180
+ * shortest fix is the `acorn` peer S 3.8 rejects.
181
+ */
182
+ const guardIdentifiers = (expression, node) => {
183
+ // `parse`'s declared return is `Program | AnyNode | undefined` and `simple`
184
+ // takes a `Node`, so the narrowing is forced by the signature rather than
185
+ // by a case this package can reach: `prepare` passes `defaultParserOptions`,
186
+ // which sets `extractExpressions: false`, and `parse` then returns the
187
+ // `Program` unconditionally. `undefined` is `extractExpression`'s answer
188
+ // when a program's body is not exactly one `ExpressionStatement` - `'a; b'`
189
+ // as much as the empty program - so a caller passing different options
190
+ // could produce it.
191
+ //
192
+ // **No spec covers this branch, and skipping the walk is still right if one
193
+ // ever reaches it**: nothing to walk is nothing to reject, and the caller
194
+ // hands the same value to `compile`, whose `evaluate` already answers
195
+ // `undefined` for a falsy node. The guard changes no contract by declining.
196
+ if (node === undefined) {
197
+ return;
198
+ }
199
+ simple(node, {
200
+ Identifier(identifier) {
201
+ if (Object.prototype.hasOwnProperty.call(Object.prototype, identifier.name)) {
202
+ throw new Error(`Expression '${expression}': identifier '${identifier.name}' is a member of ` +
203
+ `Object.prototype and cannot be resolved reliably: it reads the prototype's ` +
204
+ `value whenever the model holds no such key, so the rule sees a function - ` +
205
+ `which is truthy - rather than the absence it was written for. Rename the ` +
206
+ `model key, or the parameter that binds it.`);
207
+ }
208
+ },
209
+ });
210
+ };
211
+
212
+ /**
213
+ * Resolves one key against the model object, preferring an exact match.
214
+ *
215
+ * **This is a re-implementation of `eval-signals`' own `resolve`
216
+ * (`signal-context.ts:127-144`), not a borrow, and the plan requires that be
217
+ * said plainly rather than recorded as reuse** (plan S 0.1, S 3.2.1).
218
+ * `resolve` is module-private there and cannot be called. The two must agree
219
+ * on the same rule - exact match first, then the first key differing only in
220
+ * case, in insertion order - and if upstream's ever changes, this is the
221
+ * second copy that does not know.
222
+ */
223
+ const readProperty = (model, key, caseInsensitive) => {
224
+ if (Object.prototype.hasOwnProperty.call(model, key)) {
225
+ return model[key];
226
+ }
227
+ if (!caseInsensitive) {
228
+ return undefined;
229
+ }
230
+ const lowered = key.toLowerCase();
231
+ const match = Object.keys(model).find((candidate) => candidate.toLowerCase() === lowered);
232
+ return match === undefined ? undefined : model[match];
233
+ };
234
+ /**
235
+ * Builds the `/signals` adapter's source over the model signal a consumer
236
+ * passed to `form()`.
237
+ *
238
+ * **The property read happens *inside* the `computed`, and that is the whole
239
+ * design** (plan S 3.2.1). Two earlier shapes are withdrawn and both failed
240
+ * in ways worth naming, because each looks correct until a second read:
241
+ *
242
+ * - A bare `() => model()[key]` in a `SignalContextSource` record resolves to
243
+ * the **function object** - truthy, never called, never tracked - because
244
+ * upstream's resolver unwraps signals and passes functions through
245
+ * untouched. That is the silent freeze `src/lib/field-context.ts:60-64`
246
+ * already records for the `/reactive` form half.
247
+ * - A record whose entries are memoised `computed`s, written back as the
248
+ * expression spelled the key, becomes an **exact** match on the second read
249
+ * under `caseInsensitive` and shadows the model's own key for the life of
250
+ * the form. Measured as Q4: the first read resolves and every read after it
251
+ * is frozen.
252
+ *
253
+ * With resolution inside the computed there is nothing left for a record to
254
+ * hold, so both `createFieldContext` sources are `{}` and the resolver
255
+ * pushed onto `lookups` answers every key.
256
+ *
257
+ * **The read is what subscribes, and it happens even when the key resolves to
258
+ * `undefined`.** `EvalContext.get` treats `undefined` as absent at every step,
259
+ * so an expression naming a key the model does not hold yet resolves to
260
+ * nothing - but `keySignal(key)()` has been *called* inside Angular's
261
+ * derivation, so the rule is subscribed. When the model gains the key, the
262
+ * computed's value changes and the rule re-runs. A record that simply lacked
263
+ * the key would read nothing, subscribe to nothing, and stay frozen.
264
+ *
265
+ * **Per-key propagation survives even though every `computed` reads the whole
266
+ * model.** Angular's `computed` memoises on `Object.is`, so a write to `zip`
267
+ * re-evaluates each computed's property read and propagates only from
268
+ * `zip`'s. The cost per model write is O(keys some expression actually
269
+ * reads), not O(rules) and not O(model keys), because `computed` is lazy and
270
+ * a key nothing names is never evaluated.
271
+ *
272
+ * **What is limited**, for the README beside `/reactive`'s key-set caveat -
273
+ * and neither item is resolution, since every key an expression can name
274
+ * resolves at any spelling `caseInsensitive` allows, whether or not the model
275
+ * held it when the form was built:
276
+ *
277
+ * - The nested-signal diagnostic does not reach this adapter.
278
+ * `findNestedSignals` only reports a key whose value `isPlainObject`, and
279
+ * every value here is a `computed`. A model property holding a signal is
280
+ * read un-called by the member visitor and nothing warns.
281
+ * - Enumeration of the form's keys is not available upstream, because the
282
+ * memo is deliberately private. That is the fix rather than a cost: the
283
+ * record being enumerable by upstream's `resolve` is precisely what
284
+ * produced Q4's freeze.
285
+ *
286
+ * @param model - The `WritableSignal` the consumer passes to `form()`.
287
+ * `form()` does not copy it, so the model signal and the field
288
+ * tree are two views of one thing.
289
+ * @param options - Configures this source and the contexts it builds, not the
290
+ * walk. As upstream, `caseInsensitive` corrects identifier
291
+ * keys here but not *property* names.
292
+ */
293
+ const createModelSource = (model, options) => {
294
+ // Index access, not dotted: `EvalOptions` is an index signature and
295
+ // `noPropertyAccessFromIndexSignature` is set in all three libraries.
296
+ const caseInsensitive = !!options?.['caseInsensitive'];
297
+ // A `Map`, deliberately, and **not** the record `createFieldContext` hands
298
+ // to `createSignalContext` - see Q4 in the docblock above. Nothing upstream
299
+ // can see it, so no memo entry can ever shadow a model key.
300
+ const memo = new Map();
301
+ const keySignal = (key) => {
302
+ let cached = memo.get(key);
303
+ if (!cached) {
304
+ // Created inside Angular's reactive consumer, on the first read of any
305
+ // key. That is allowed - `computed()` needs no injection context and is
306
+ // not `effect()`. The inner computed becomes the active consumer for
307
+ // its own body, so `model()` is attributed there and the outer consumer
308
+ // records the inner one as a dependency, which is what makes the
309
+ // per-key propagation above hold.
310
+ cached = computed(() => readProperty(model(), key, caseInsensitive));
311
+ memo.set(key, cached);
312
+ }
313
+ return cached;
314
+ };
315
+ const createRuleContext = () => {
316
+ // `createFieldContext` is still what builds the context - not for its
317
+ // sources, which are both empty, but for its **class**. It returns a
318
+ // context whose `set` throws `SignalContextWriteError`, which is the
319
+ // error the error policy must re-throw rather than swallow. A hand-built
320
+ // `EvalContext` would silently accept an assigning expression.
321
+ const context = createFieldContext({}, {}, options);
322
+ // The resolver's parameter is deliberately unannotated. `EvalLookup` is
323
+ // `(key: unknown, …) => unknown` and a parameter position is
324
+ // contravariant under `strict`, so `(key: string) => …` does not compile;
325
+ // upstream writes it the same way for the same reason. The `typeof`
326
+ // narrowing is therefore not defensive padding - without it a non-string
327
+ // key would be coerced into the memo as a spurious entry.
328
+ context.lookups.push((key) => (typeof key === 'string' ? keySignal(key)() : undefined));
329
+ return context;
330
+ };
331
+ return { keySignal, createRuleContext };
332
+ };
333
+
334
+ /**
335
+ * The metadata key `evalText` writes through and a consumer reads back
336
+ * (plan S 1.2.8, S 3.5).
337
+ *
338
+ * `text` has no dedicated primitive in `@angular/forms/signals` the way
339
+ * `hidden` and `disabled` do, so it is `metadata(path, TEXT, logic)` against a
340
+ * key created once - which is Angular's own mechanism rather than a second one
341
+ * beside it, per the `/signals` reviewer checklist's item 4.
342
+ *
343
+ * **Created once, at module scope, deliberately.** `createMetadataKey` mints a
344
+ * fresh key per call, and the write and the read-back have to name the same
345
+ * object: a key re-created per access would let `metadata(p.x, TEXT, …)` write
346
+ * under one identity and `f.x().metadata(TEXT)` read under another, and the
347
+ * read would be `undefined` with nothing to show why. `text-key.spec.ts`
348
+ * asserts the two halves of that - `createMetadataKey` is per-call, and this
349
+ * is one of its results rather than the function itself.
350
+ */
351
+ const TEXT = createMetadataKey();
352
+
353
+ /**
354
+ * Binds one model signal and returns the three expression-driven registrars.
355
+ *
356
+ * **A factory rather than free functions, because a `LogicFn` cannot recover
357
+ * the source** (plan S 3.2.1). `RootFieldContext` exposes the *current*
358
+ * field's node plus compile-time-token accessors and no root or parent
359
+ * handle, so a rule on `p.city` evaluating `country === "US"` has no route to
360
+ * `country` from inside the `LogicFn`. The source must be closed over at
361
+ * registration or it is unreachable.
362
+ *
363
+ * ```ts
364
+ * const rules = createExpressionRules(model);
365
+ * const s = schema<Model>((p) => {
366
+ * required(p.email); // Angular's
367
+ * rules.evalVisible(p.city, 'country === "US"'); // ours
368
+ * });
369
+ * const f = form(model, s);
370
+ * ```
371
+ *
372
+ * **A schema *value* shared across models is the unsupported shape.** Nothing
373
+ * stops two `form()` calls from one schema - Angular re-invokes the schema
374
+ * body once per `form()`, so each form mints its own contexts - but the
375
+ * registrars close over the **factory's** model, and the factory is bound to
376
+ * one. A schema built from `createExpressionRules(modelA)` and reused for
377
+ * `form(modelB, s)` re-registers every rule and every one of them still reads
378
+ * model A: form B renders against form A's data, silently, with no error and
379
+ * a fully functional form (Q9).
380
+ *
381
+ * The supported reuse shape is therefore a schema **function of the rules** -
382
+ * `const makeSchema = (rules) => schema<Model>(p => …)`, called per form -
383
+ * which keeps reuse while giving each form a factory bound to its own model.
384
+ *
385
+ * What one factory retains: **one private memo**, per factory, bounded by the
386
+ * union of keys the rules mention; and, per rule per `form()`, one
387
+ * `EvalContext` and one compiled callback. Nothing registers with a
388
+ * `DestroyRef` and there is no `destroy()` - it all becomes garbage with the
389
+ * form (S 3.6).
390
+ */
391
+ const createExpressionRules = (model, options) => {
392
+ // Called **once** per factory: it is what fixes the memo's lifetime, one
393
+ // per factory rather than one per rule (plan S 3.6). Calling it per
394
+ // registrar instead would satisfy every behavioural criterion in this phase
395
+ // while quietly making the memo per rule, which is why the count has a spec
396
+ // of its own.
397
+ const source = createModelSource(model, options?.eval);
398
+ /**
399
+ * Resolves the two levels `ExpressionRuleOptions` arrives at:
400
+ * **registration wins, per key** (plan S 3.5.3). Each key is resolved
401
+ * independently and neither is a deep merge, so a registration supplying
402
+ * only `onError` keeps the factory's `eval` and vice versa.
403
+ *
404
+ * Exact for `onError`, partial for `eval.caseInsensitive` - see the note on
405
+ * `ExpressionRuleOptions.eval`. The divergence is characterised in
406
+ * `rules.spec.ts` rather than left to be discovered.
407
+ */
408
+ const resolveOptions = (rule) => ({
409
+ eval: rule?.eval ?? options?.eval,
410
+ onError: rule?.onError ?? options?.onError,
411
+ });
412
+ /**
413
+ * Everything a registrar does before handing Angular a `LogicFn`, and the
414
+ * shape of what it returns is the phase's one structural invariant.
415
+ *
416
+ * **Called once per registration**, so `parse` + `compile` and
417
+ * `createRuleContext()` happen at schema-body time - which Angular re-runs
418
+ * once per `form()` (Q8), giving S 3.6's count of one context and one
419
+ * compiled callback per rule per form. Nothing here re-parses per
420
+ * derivation; risk 8 is a compile that drifts into the returned closure, and
421
+ * `rules.invocation-count.spec.ts` counts `compile` to say it has not.
422
+ *
423
+ * **`guardIdentifiers` runs here, between `parse` and `compile`, and one
424
+ * call site is deliberate** (S 3.8, revision 18 item 1). Revision 16's rule
425
+ * rejects "the wrapper is shared" as a substitute for a per-registrar case,
426
+ * and the discriminator it states is whether the subject is a path Angular
427
+ * owns. This one is not: the guard throws **before any Angular primitive is
428
+ * reached**, so in the rejecting case `hidden`, `metadata` and
429
+ * `addDisabledReasonRule` are never called and the three registrars have
430
+ * nothing downstream that could diverge. Contrast the invocation count and
431
+ * the write-error bypass, whose values arrive *through* those three
432
+ * primitives - `rules.spec.ts` gives each of them a case per registrar for
433
+ * exactly that reason. Anything the returned closure does stays
434
+ * registrar-level; this runs before there is a closure.
435
+ *
436
+ * **`applyErrorPolicy` is the outermost call in the returned closure, and
437
+ * that is load-bearing twice over** (S 3.5). The policy has to cover the
438
+ * coercion's *input* rather than only the walk - a registrar that coerced
439
+ * first would hand `toVisible` a value the policy never saw - and S 6.1.1's
440
+ * invocation instrument counts this exact call. M7 measured what a guard
441
+ * hoisted *above* the wrapper does to that number: ground truth 1,
442
+ * instrument **0**, which reads as "the rule did not re-run" in every
443
+ * negative case in this package. A later guard belongs **inside** the
444
+ * `run` callback, never ahead of this call.
445
+ */
446
+ const prepare = (expression, ruleOptions) => {
447
+ const resolved = resolveOptions(ruleOptions);
448
+ const node = parse(expression, defaultParserOptions);
449
+ guardIdentifiers(expression, node);
450
+ const compiled = compile(node);
451
+ const context = source.createRuleContext();
452
+ return () => applyErrorPolicy(() => evaluateRule(compiled, context, resolved.eval), resolved.onError);
453
+ };
454
+ return {
455
+ // Angular's **config** overload (S 1.2.7); the deprecated one takes the
456
+ // `LogicFn` positionally. `hidden`'s `when` is the only required config of
457
+ // the three primitives this entry point registers.
458
+ //
459
+ // The `!` is S 3.5.1's inversion, and it lives here rather than in every
460
+ // consumer's expression so the same rule string means the same thing at
461
+ // this entry point and at `/reactive`'s `visible`.
462
+ evalVisible: (path, expression, ruleOptions) => {
463
+ const evaluated = prepare(expression, ruleOptions);
464
+ hidden(path, { when: () => !toVisible(evaluated()) });
465
+ },
466
+ // `text` has no dedicated primitive, so it is Angular's `metadata` against
467
+ // the module-scope key of `text-key.ts` (S 1.2.8) - its own mechanism
468
+ // rather than a second one beside it.
469
+ evalText: (path, expression, ruleOptions) => {
470
+ const evaluated = prepare(expression, ruleOptions);
471
+ metadata(path, TEXT, () => toText(evaluated()));
472
+ },
473
+ // Angular's polarity, uninverted: `/reactive` ships no `disabled`, so no
474
+ // expression has to mean the same thing at two entry points, and `true`
475
+ // disabling is what an author expects (S 3.5.1).
476
+ //
477
+ // **The reason is a static option, never the expression's return**
478
+ // (S 3.5.2). Angular's `when` is a single field carrying both the
479
+ // condition and the reason - it returns `boolean | string`, and a truthy
480
+ // string is *both* (1.2.7) - so a registrar forwarding `evaluated()` raw
481
+ // would disable a field on the string `'false'` **with the reason
482
+ // `"false"`**. Coercing through `toVisible` first, and sourcing the reason
483
+ // from the registration instead, is what kills that: the string never
484
+ // comes from the expression at all.
485
+ //
486
+ // A *dynamic* reason stays out of scope - it reopens the trap and needs a
487
+ // coercion rule of its own.
488
+ evalDisabled: (path, expression, ruleOptions) => {
489
+ const evaluated = prepare(expression, ruleOptions);
490
+ const reason = ruleOptions?.reason;
491
+ disabled(path, {
492
+ when: () => {
493
+ // `evaluated()` first, so `applyErrorPolicy` stays the outermost
494
+ // call in this body as it is in the other two (S 3.5). `reason` is
495
+ // read from a closure rather than branched on ahead of the call:
496
+ // a guard hoisted above the wrapper is M7's arrangement, which
497
+ // reads 0 on an instrument whose ground truth is 1.
498
+ const on = toVisible(evaluated());
499
+ return on && reason !== undefined ? reason : on;
500
+ },
501
+ });
502
+ },
503
+ };
504
+ };
505
+
506
+ /**
507
+ * Generated bundle index. Do not edit.
508
+ */
509
+
510
+ export { TEXT, createExpressionRules };
511
+ //# sourceMappingURL=zvenigora-ng-eval-forms-signals.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zvenigora-ng-eval-forms-signals.mjs","sources":["../../../../modules/eval-forms/signals/src/lib/evaluate-rule.ts","../../../../modules/eval-forms/signals/src/lib/guard-identifiers.ts","../../../../modules/eval-forms/signals/src/lib/model-source.ts","../../../../modules/eval-forms/signals/src/lib/text-key.ts","../../../../modules/eval-forms/signals/src/lib/rules.ts","../../../../modules/eval-forms/signals/src/zvenigora-ng-eval-forms-signals.ts"],"sourcesContent":["import { EvalContext, EvalOptions, EvalState, call, stateCallback } from '@zvenigora/ng-eval-core';\r\n\r\n/**\r\n * Runs one compiled rule against one context, and leaves the context's scope\r\n * stack exactly as it found it.\r\n *\r\n * **This is the entry point's only path to the walk, and that is the whole\r\n * point of it** (plan S 3.3, `phase-4-plan.md` S 9.1). Every walk needs an\r\n * `EvalState`, and outside Angular DI there are exactly two ways to get one:\r\n * the static factory this function calls below, and the class's public\r\n * constructor. The one construction in this package is that line, inside this\r\n * function's body; S 6 gate 3 greps for both spellings and expects one hit and\r\n * zero.\r\n *\r\n * **Neither spelling is written out in this comment, deliberately.** Gate 3 is\r\n * a grep, and prose naming what it searches for is a standing hit on the file\r\n * the gate exists to bless - which is what revision 10 spent a revision\r\n * removing from that gate's third row, after a block comment in\r\n * `reactive/src/lib/field-schema.ts` made it read as failing. A gate with a\r\n * known pre-existing hit is one people learn to ignore.\r\n *\r\n * **Module-private to `/signals`, deliberately, and not merely unexported by\r\n * omission.** Placing it in the shared core was measured against this and\r\n * separates on one row that matters: a barrel re-exports whole modules, so a\r\n * helper the core's `public-api.ts` can reach **is published**, permanently,\r\n * on an entry point already released at 0.1.0 - and a published `evaluateRule`\r\n * *is* a second path to the walk by existing, since any consumer could call it\r\n * with a hand-built `EvalContext`. Here the set of callers is the set of files\r\n * in this directory, which is checkable by grep. The three placement\r\n * hypotheses that sound decisive - `/reactive` bundle weight, `@angular/core`\r\n * leakage, FESM size - were measured and are not: ng-packagr compiles each\r\n * entry point separately and the helper appears in `/reactive`'s FESM at zero\r\n * bytes either way (S 3.3's table).\r\n *\r\n * **Why the `finally` exists.** The scope stack is the third and longest-lived\r\n * of `eval-core`'s three stack invariants ([`CLAUDE.md`](../../../../../CLAUDE.md)):\r\n * unlike the value stack and the open-node stack, which live on the per-walk\r\n * `EvalState` and die with it, scopes live on the `EvalContext`. A rule holds\r\n * its context across every invocation Angular makes, and `EvalContext.get`\r\n * resolves `scopes` **first**, so one scope left behind shadows the source key\r\n * of that name for the life of the form. Nothing else drains it.\r\n *\r\n * **Retained, not redundant.** This was written against a specific defect -\r\n * `arrow-function-expression.ts` pushed a scope and popped it with no\r\n * `try`/`finally`, so an arrow body that threw skipped the pop - and Phase 2\r\n * step 0 fixed exactly that\r\n * ([backlog A9](../../../../../docs/backlog.md#a9)). The loop stays anyway, for\r\n * two reasons that outlive the fix - and they are not the same *kind* of\r\n * reason, which is the part an earlier version of this docblock got wrong:\r\n *\r\n * - `package.json` declares `\"@zvenigora/ng-eval-core\": \">=0.3.0 <0.5.0\"`.\r\n * That range admits the *leaking* 0.3.0 as well as the fixed 0.4.0, so a\r\n * supported installation can still be running the defect. **Range-dependent**:\r\n * it would stop being true if the range were ever raised past 0.3.0.\r\n * - `EvalContext.push` and `pop` are public methods on a published class: a\r\n * scope can be stranded with no visitor involved at all. That is the route\r\n * `evaluate-rule.spec.ts`'s containment cases now drive, because it is the\r\n * one no fix inside the core's visitors can close. **True at every version**,\r\n * and therefore the reason this loop is not removable at any peer range.\r\n *\r\n * **Raising the peer range does not make this removable**, and the sentence\r\n * that used to sit here said it did - \"removal is gated on raising the peer\r\n * range\" reads as a sufficient condition and is only a necessary one. Whoever\r\n * raises it retires the first reason and leaves the second untouched. The same\r\n * error was in the plan's step 0b, corrected there in Phase 2 step 7; this copy\r\n * of it was corrected in step 8.\r\n *\r\n * A third reason has expired and is recorded as gone rather than silently\r\n * dropped: this was also the backstop for the scope-push sites Phase 2 was\r\n * adding to the core. `Program`, `BlockStatement` and `ForStatement` all\r\n * shipped in 0.4.0, each popping in a `finally`.\r\n *\r\n * The unwind is a loop to a **depth mark**, not a single `pop()`: one throw\r\n * can leave more than one scope open, and unwinding to the bottom would drain\r\n * scopes this call did not push - `evaluate()` is re-entrant through the arrow\r\n * closure, so the depth on entry is not reliably zero.\r\n *\r\n * This helper deliberately does **not** apply the error policy. The throw\r\n * propagates, and `applyErrorPolicy` sits outside this call in the `LogicFn`\r\n * body (S 3.5) - containment first, then the policy - so an expression that\r\n * throws is contained whether the consumer asked for `'throw'`, `'undefined'`\r\n * or a handler.\r\n *\r\n * @param compiled - `eval-core`'s own `stateCallback`, from\r\n * `compile(parse(expression, ...))`. A registrar compiles\r\n * once and holds the callback; nothing recompiles per\r\n * invocation.\r\n * @param context - The rule's context, from `ModelSource.createRuleContext()`.\r\n * One per rule per `form()` (S 3.6), reused across every\r\n * invocation of that rule.\r\n * @param options - The walk's options, which are **not** the context's:\r\n * visitors read `caseInsensitive` off the state, so it has to\r\n * reach both to correct property names as well as identifier\r\n * keys.\r\n */\r\nexport const evaluateRule = (\r\n compiled: stateCallback,\r\n context: EvalContext,\r\n options?: EvalOptions\r\n): unknown => {\r\n\r\n const depth = context.scopes.length;\r\n\r\n // `fromContext` short-circuits on identity for an `EvalContext`, so this\r\n // builds a fresh per-walk state around the *same* context rather than\r\n // copying it - which is what lets one context back many invocations, and\r\n // equally what makes a leaked scope durable.\r\n const state = EvalState.fromContext(context, options);\r\n\r\n try {\r\n return call(compiled, state);\r\n } finally {\r\n while (context.scopes.length > depth) {\r\n context.pop();\r\n }\r\n }\r\n};\r\n","import type { parse } from '@zvenigora/ng-eval-core';\r\nimport { simple } from 'acorn-walk';\r\n\r\n/**\r\n * Throws if the expression names an identifier that is an own property of\r\n * `Object.prototype` (plan S 3.8).\r\n *\r\n * **The failure this prevents is silent and truthy.** `createSignalContext`\r\n * builds its context on an empty `original` object, and `EvalContext.get`\r\n * consults `original` *before* `lookups` - so an identifier like\r\n * `constructor` resolves off the prototype and never reaches the model\r\n * resolver at all. A function is truthy, so `toVisible` says visible and\r\n * `evalVisible(p.city, 'constructor')` renders the field with no data, no\r\n * error and nothing logged (Q10, Q11). It is not GHSA-pj3p-xpg7-h7gw's\r\n * case-variant bypass: the behaviour is identical with and without\r\n * `caseInsensitive`, and `CONSTRUCTOR` resolves `undefined` in both.\r\n *\r\n * **The subject is the expression, not the field name** - which is what makes\r\n * this the same answer `/reactive` gives (`field-schema.ts:172-178`) on a\r\n * different input. There the field names arrive in the library's own\r\n * `FieldSchema[]`; here the paths are compile-time `p.city` tokens and the\r\n * library never sees a name it could validate. What it does see, at\r\n * registration, is the expression. A model key nobody names harms nobody, so\r\n * the expression is the complete subject and this check inherits none of the\r\n * growing-key-set problem a scan of the model would have.\r\n *\r\n * **The predicate is normative and any list of names is illustrative**\r\n * (S 3.8.1, revision 18 item 2). `Object.getOwnPropertyNames(Object.prototype)`\r\n * is twelve names: the seven a form author might plausibly type -\r\n * `constructor`, `toString`, `valueOf`, `hasOwnProperty`, `isPrototypeOf`,\r\n * `propertyIsEnumerable`, `toLocaleString` - plus `__proto__` and the four\r\n * `__define*` / `__lookup*` accessors. Hard-coding the seven would satisfy\r\n * every other criterion of this step, which is why one of the other five is\r\n * asserted.\r\n *\r\n * **Deliberately over-rejecting** (S 3.8.1). An arrow's own frame is\r\n * genuinely safe - `EvalContext.get` resolves `scopes` at step 1 and\r\n * `original` at step 2, so a bound `valueOf` shadows the prototype and\r\n * resolves correctly - and `'[1].map(valueOf => valueOf)'` is refused anyway.\r\n * The scope-aware alternative is a second copy of `eval-core`'s frame logic,\r\n * tracking two scope-pushing visitors this library does not own, that fails\r\n * by *under*-rejecting when it drifts. The costs are asymmetric: a named\r\n * error at registration, whose fix is renaming a parameter, against a field\r\n * that always renders in production.\r\n *\r\n * **`acorn-walk`'s `simple`, borrowed rather than hand-rolled** (S 0.1) - the\r\n * same package `eval-core` walks with. Two of its properties are load-bearing\r\n * rather than incidental, and both are pinned by specs:\r\n *\r\n * - its base walker descends into `node.property` only when `node.computed`,\r\n * so `user.constructor` is **not** seen as an `Identifier`. That is\r\n * `eval-core`'s prototype-pollution guard's business and the stated upper\r\n * bound of this one;\r\n * - `base.Function` walks parameters under the `\"Pattern\"` override, which\r\n * `simple` suppresses, so a **binding** is never visited while a\r\n * **reference** is. `'[1].map(valueOf => 1)'` therefore registers.\r\n *\r\n * A hand-rolled scan over every node would reject both, which is the\r\n * difference the borrow is checked at.\r\n *\r\n * @param expression the source, named in the message so an author can tell\r\n * which of a schema's rules to fix\r\n * @param node the AST the registrar has just parsed. Typed\r\n * `ReturnType<typeof parse>` rather than `AnyNode`: `eval-core` publishes\r\n * `AnyNodeTypes` and not `AnyNode`, so spelling it out would force\r\n * `import type { AnyNode } from 'acorn'` - an undeclared dependency whose\r\n * shortest fix is the `acorn` peer S 3.8 rejects.\r\n */\r\nexport const guardIdentifiers = (expression: string, node: ReturnType<typeof parse>): void => {\r\n\r\n // `parse`'s declared return is `Program | AnyNode | undefined` and `simple`\r\n // takes a `Node`, so the narrowing is forced by the signature rather than\r\n // by a case this package can reach: `prepare` passes `defaultParserOptions`,\r\n // which sets `extractExpressions: false`, and `parse` then returns the\r\n // `Program` unconditionally. `undefined` is `extractExpression`'s answer\r\n // when a program's body is not exactly one `ExpressionStatement` - `'a; b'`\r\n // as much as the empty program - so a caller passing different options\r\n // could produce it.\r\n //\r\n // **No spec covers this branch, and skipping the walk is still right if one\r\n // ever reaches it**: nothing to walk is nothing to reject, and the caller\r\n // hands the same value to `compile`, whose `evaluate` already answers\r\n // `undefined` for a falsy node. The guard changes no contract by declining.\r\n if (node === undefined) {\r\n return;\r\n }\r\n\r\n simple(node, {\r\n Identifier(identifier) {\r\n if (Object.prototype.hasOwnProperty.call(Object.prototype, identifier.name)) {\r\n throw new Error(\r\n `Expression '${expression}': identifier '${identifier.name}' is a member of ` +\r\n `Object.prototype and cannot be resolved reliably: it reads the prototype's ` +\r\n `value whenever the model holds no such key, so the rule sees a function - ` +\r\n `which is truthy - rather than the absence it was written for. Rename the ` +\r\n `model key, or the parameter that binds it.`\r\n );\r\n }\r\n },\r\n });\r\n};\r\n","import { Signal, WritableSignal, computed } from '@angular/core';\r\nimport { EvalContext, EvalOptions } from '@zvenigora/ng-eval-core';\r\nimport { createFieldContext } from '@zvenigora/ng-eval-forms';\r\n\r\n/**\r\n * Resolves one key against the model object, preferring an exact match.\r\n *\r\n * **This is a re-implementation of `eval-signals`' own `resolve`\r\n * (`signal-context.ts:127-144`), not a borrow, and the plan requires that be\r\n * said plainly rather than recorded as reuse** (plan S 0.1, S 3.2.1).\r\n * `resolve` is module-private there and cannot be called. The two must agree\r\n * on the same rule - exact match first, then the first key differing only in\r\n * case, in insertion order - and if upstream's ever changes, this is the\r\n * second copy that does not know.\r\n */\r\nconst readProperty = (\r\n model: Record<string, unknown>,\r\n key: string,\r\n caseInsensitive: boolean\r\n): unknown => {\r\n\r\n if (Object.prototype.hasOwnProperty.call(model, key)) {\r\n return model[key];\r\n }\r\n\r\n if (!caseInsensitive) {\r\n return undefined;\r\n }\r\n\r\n const lowered = key.toLowerCase();\r\n const match = Object.keys(model).find((candidate) => candidate.toLowerCase() === lowered);\r\n return match === undefined ? undefined : model[match];\r\n};\r\n\r\n/**\r\n * What one `createExpressionRules` factory holds: a private memo of per-key\r\n * `computed`s, and the contexts built off it (plan S 3.2.1, S 3.6).\r\n *\r\n * Module-private to the `/signals` entry point - a real export of this\r\n * module, absent from `signals/src/public-api.ts`, changeable by a later\r\n * phase without a release (S 5).\r\n */\r\nexport interface ModelSource {\r\n\r\n /**\r\n * One `computed` per key, per **factory**. Exported so the memo can be\r\n * compared by identity: the memo itself is private and the resolver returns\r\n * a *value*, so comparing two resolved values passes with or without it.\r\n */\r\n keySignal: (key: string) => Signal<unknown>;\r\n\r\n /**\r\n * S 3.6's one context per rule per `form()`, built off the shared memo.\r\n */\r\n createRuleContext: () => EvalContext;\r\n}\r\n\r\n/**\r\n * Builds the `/signals` adapter's source over the model signal a consumer\r\n * passed to `form()`.\r\n *\r\n * **The property read happens *inside* the `computed`, and that is the whole\r\n * design** (plan S 3.2.1). Two earlier shapes are withdrawn and both failed\r\n * in ways worth naming, because each looks correct until a second read:\r\n *\r\n * - A bare `() => model()[key]` in a `SignalContextSource` record resolves to\r\n * the **function object** - truthy, never called, never tracked - because\r\n * upstream's resolver unwraps signals and passes functions through\r\n * untouched. That is the silent freeze `src/lib/field-context.ts:60-64`\r\n * already records for the `/reactive` form half.\r\n * - A record whose entries are memoised `computed`s, written back as the\r\n * expression spelled the key, becomes an **exact** match on the second read\r\n * under `caseInsensitive` and shadows the model's own key for the life of\r\n * the form. Measured as Q4: the first read resolves and every read after it\r\n * is frozen.\r\n *\r\n * With resolution inside the computed there is nothing left for a record to\r\n * hold, so both `createFieldContext` sources are `{}` and the resolver\r\n * pushed onto `lookups` answers every key.\r\n *\r\n * **The read is what subscribes, and it happens even when the key resolves to\r\n * `undefined`.** `EvalContext.get` treats `undefined` as absent at every step,\r\n * so an expression naming a key the model does not hold yet resolves to\r\n * nothing - but `keySignal(key)()` has been *called* inside Angular's\r\n * derivation, so the rule is subscribed. When the model gains the key, the\r\n * computed's value changes and the rule re-runs. A record that simply lacked\r\n * the key would read nothing, subscribe to nothing, and stay frozen.\r\n *\r\n * **Per-key propagation survives even though every `computed` reads the whole\r\n * model.** Angular's `computed` memoises on `Object.is`, so a write to `zip`\r\n * re-evaluates each computed's property read and propagates only from\r\n * `zip`'s. The cost per model write is O(keys some expression actually\r\n * reads), not O(rules) and not O(model keys), because `computed` is lazy and\r\n * a key nothing names is never evaluated.\r\n *\r\n * **What is limited**, for the README beside `/reactive`'s key-set caveat -\r\n * and neither item is resolution, since every key an expression can name\r\n * resolves at any spelling `caseInsensitive` allows, whether or not the model\r\n * held it when the form was built:\r\n *\r\n * - The nested-signal diagnostic does not reach this adapter.\r\n * `findNestedSignals` only reports a key whose value `isPlainObject`, and\r\n * every value here is a `computed`. A model property holding a signal is\r\n * read un-called by the member visitor and nothing warns.\r\n * - Enumeration of the form's keys is not available upstream, because the\r\n * memo is deliberately private. That is the fix rather than a cost: the\r\n * record being enumerable by upstream's `resolve` is precisely what\r\n * produced Q4's freeze.\r\n *\r\n * @param model - The `WritableSignal` the consumer passes to `form()`.\r\n * `form()` does not copy it, so the model signal and the field\r\n * tree are two views of one thing.\r\n * @param options - Configures this source and the contexts it builds, not the\r\n * walk. As upstream, `caseInsensitive` corrects identifier\r\n * keys here but not *property* names.\r\n */\r\nexport const createModelSource = <TModel extends object>(\r\n model: WritableSignal<TModel>,\r\n options?: EvalOptions\r\n): ModelSource => {\r\n\r\n // Index access, not dotted: `EvalOptions` is an index signature and\r\n // `noPropertyAccessFromIndexSignature` is set in all three libraries.\r\n const caseInsensitive = !!options?.['caseInsensitive'];\r\n\r\n // A `Map`, deliberately, and **not** the record `createFieldContext` hands\r\n // to `createSignalContext` - see Q4 in the docblock above. Nothing upstream\r\n // can see it, so no memo entry can ever shadow a model key.\r\n const memo = new Map<string, Signal<unknown>>();\r\n\r\n const keySignal = (key: string): Signal<unknown> => {\r\n let cached = memo.get(key);\r\n\r\n if (!cached) {\r\n // Created inside Angular's reactive consumer, on the first read of any\r\n // key. That is allowed - `computed()` needs no injection context and is\r\n // not `effect()`. The inner computed becomes the active consumer for\r\n // its own body, so `model()` is attributed there and the outer consumer\r\n // records the inner one as a dependency, which is what makes the\r\n // per-key propagation above hold.\r\n cached = computed(() => readProperty(model() as Record<string, unknown>, key, caseInsensitive));\r\n memo.set(key, cached);\r\n }\r\n\r\n return cached;\r\n };\r\n\r\n const createRuleContext = (): EvalContext => {\r\n\r\n // `createFieldContext` is still what builds the context - not for its\r\n // sources, which are both empty, but for its **class**. It returns a\r\n // context whose `set` throws `SignalContextWriteError`, which is the\r\n // error the error policy must re-throw rather than swallow. A hand-built\r\n // `EvalContext` would silently accept an assigning expression.\r\n const context = createFieldContext({}, {}, options);\r\n\r\n // The resolver's parameter is deliberately unannotated. `EvalLookup` is\r\n // `(key: unknown, …) => unknown` and a parameter position is\r\n // contravariant under `strict`, so `(key: string) => …` does not compile;\r\n // upstream writes it the same way for the same reason. The `typeof`\r\n // narrowing is therefore not defensive padding - without it a non-string\r\n // key would be coerced into the memo as a spurious entry.\r\n context.lookups.push((key) => (typeof key === 'string' ? keySignal(key)() : undefined));\r\n\r\n return context;\r\n };\r\n\r\n return { keySignal, createRuleContext };\r\n};\r\n","import { createMetadataKey } from '@angular/forms/signals';\r\n\r\n/**\r\n * The metadata key `evalText` writes through and a consumer reads back\r\n * (plan S 1.2.8, S 3.5).\r\n *\r\n * `text` has no dedicated primitive in `@angular/forms/signals` the way\r\n * `hidden` and `disabled` do, so it is `metadata(path, TEXT, logic)` against a\r\n * key created once - which is Angular's own mechanism rather than a second one\r\n * beside it, per the `/signals` reviewer checklist's item 4.\r\n *\r\n * **Created once, at module scope, deliberately.** `createMetadataKey` mints a\r\n * fresh key per call, and the write and the read-back have to name the same\r\n * object: a key re-created per access would let `metadata(p.x, TEXT, …)` write\r\n * under one identity and `f.x().metadata(TEXT)` read under another, and the\r\n * read would be `undefined` with nothing to show why. `text-key.spec.ts`\r\n * asserts the two halves of that - `createMetadataKey` is per-call, and this\r\n * is one of its results rather than the function itself.\r\n */\r\nexport const TEXT = createMetadataKey<string>();\r\n","import { WritableSignal } from '@angular/core';\r\nimport { type PathKind, type SchemaPath, type SchemaPathRules, disabled, hidden, metadata } from '@angular/forms/signals';\r\nimport { type EvalOptions, compile, defaultParserOptions, parse } from '@zvenigora/ng-eval-core';\r\nimport { type ExpressionErrorPolicy, applyErrorPolicy, toText, toVisible } from '@zvenigora/ng-eval-forms';\r\nimport { evaluateRule } from './evaluate-rule';\r\nimport { guardIdentifiers } from './guard-identifiers';\r\nimport { createModelSource } from './model-source';\r\nimport { TEXT } from './text-key';\r\n\r\n/**\r\n * What `createExpressionRules` takes, and what a single registration may\r\n * override (plan S 5).\r\n */\r\nexport interface ExpressionRuleOptions {\r\n\r\n /**\r\n * Passed to the context and to the walk. `caseInsensitive` has to reach\r\n * both: on the context it corrects identifier keys, and on the walk it\r\n * corrects *property* names, which the member visitor reads off the\r\n * state's options.\r\n *\r\n * **A per-registration value reaches exactly one of the three places it\r\n * has to: the walk** (plan S 3.5.3). The other two read the **factory's**\r\n * options, which are fixed when `createExpressionRules` is called: the memo\r\n * is built once, there; the context is minted per registration by\r\n * `createRuleContext()` but always from that same fixed setting, so a\r\n * registration cannot move it. So overriding this per registration corrects\r\n * *property* names and leaves *identifier* keys on the factory's setting,\r\n * and one expression then obeys two casing rules. Set `caseInsensitive` on\r\n * the **factory** unless that is the behaviour you want.\r\n *\r\n * Revision 19 item 2 corrects \"both are made once, at\r\n * `createExpressionRules` time\", which was wrong about the context and is\r\n * the claim the README states correctly.\r\n */\r\n eval?: EvalOptions;\r\n\r\n /**\r\n * What a field property does when its expression throws at runtime.\r\n * Defaults to `'undefined'` here, the opposite of `eval-signals`' own\r\n * default - see `ExpressionErrorPolicy` for why.\r\n */\r\n onError?: ExpressionErrorPolicy;\r\n}\r\n\r\n/**\r\n * The three registrars one factory returns, one per Angular rule.\r\n *\r\n * **One call per Angular primitive, never an aggregate** (plan S 3.5.1). A\r\n * single `evalRules(p.x, { visible, text, disabled })` would register three\r\n * different Angular rules behind one name, hiding which one each property\r\n * maps to - which is the `/signals` reviewer checklist's item 4 expressed as\r\n * an API.\r\n *\r\n * Named after the **property**, not after Angular's rule: `evalVisible`\r\n * registers `hidden`, inverted once inside the registrar rather than in every\r\n * consumer's expression, so the same expression string means the same thing\r\n * at this entry point and at `/reactive`.\r\n */\r\nexport interface ExpressionRules {\r\n\r\n /** Registers Angular's `hidden`, inverted (plan S 3.5.1). */\r\n evalVisible: <TValue, TPathKind extends PathKind = PathKind.Root>(\r\n path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>,\r\n expression: string,\r\n options?: ExpressionRuleOptions\r\n ) => void;\r\n\r\n /** Registers `metadata(path, TEXT, …)` (plan S 1.2.8, S 3.5). */\r\n evalText: <TValue, TPathKind extends PathKind = PathKind.Root>(\r\n path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>,\r\n expression: string,\r\n options?: ExpressionRuleOptions\r\n ) => void;\r\n\r\n /**\r\n * Registers Angular's `disabled`.\r\n *\r\n * The `reason` is authored as a static string and is never\r\n * expression-derived (plan S 3.5.2). Angular's `when` returns\r\n * `boolean | string` and a truthy string is *both* \"disabled\" and \"the\r\n * reason\", so a rule yielding `'false'` would otherwise disable the field\r\n * with the reason `\"false\"` - the `toVisible` truthiness trap in a new\r\n * shape. Keeping the expression boolean and the reason static is what kills\r\n * it.\r\n */\r\n evalDisabled: <TValue, TPathKind extends PathKind = PathKind.Root>(\r\n path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>,\r\n expression: string,\r\n options?: ExpressionRuleOptions & { reason?: string }\r\n ) => void;\r\n}\r\n\r\n/**\r\n * Binds one model signal and returns the three expression-driven registrars.\r\n *\r\n * **A factory rather than free functions, because a `LogicFn` cannot recover\r\n * the source** (plan S 3.2.1). `RootFieldContext` exposes the *current*\r\n * field's node plus compile-time-token accessors and no root or parent\r\n * handle, so a rule on `p.city` evaluating `country === \"US\"` has no route to\r\n * `country` from inside the `LogicFn`. The source must be closed over at\r\n * registration or it is unreachable.\r\n *\r\n * ```ts\r\n * const rules = createExpressionRules(model);\r\n * const s = schema<Model>((p) => {\r\n * required(p.email); // Angular's\r\n * rules.evalVisible(p.city, 'country === \"US\"'); // ours\r\n * });\r\n * const f = form(model, s);\r\n * ```\r\n *\r\n * **A schema *value* shared across models is the unsupported shape.** Nothing\r\n * stops two `form()` calls from one schema - Angular re-invokes the schema\r\n * body once per `form()`, so each form mints its own contexts - but the\r\n * registrars close over the **factory's** model, and the factory is bound to\r\n * one. A schema built from `createExpressionRules(modelA)` and reused for\r\n * `form(modelB, s)` re-registers every rule and every one of them still reads\r\n * model A: form B renders against form A's data, silently, with no error and\r\n * a fully functional form (Q9).\r\n *\r\n * The supported reuse shape is therefore a schema **function of the rules** -\r\n * `const makeSchema = (rules) => schema<Model>(p => …)`, called per form -\r\n * which keeps reuse while giving each form a factory bound to its own model.\r\n *\r\n * What one factory retains: **one private memo**, per factory, bounded by the\r\n * union of keys the rules mention; and, per rule per `form()`, one\r\n * `EvalContext` and one compiled callback. Nothing registers with a\r\n * `DestroyRef` and there is no `destroy()` - it all becomes garbage with the\r\n * form (S 3.6).\r\n */\r\nexport const createExpressionRules = <TModel extends object>(\r\n model: WritableSignal<TModel>,\r\n options?: ExpressionRuleOptions\r\n): ExpressionRules => {\r\n\r\n // Called **once** per factory: it is what fixes the memo's lifetime, one\r\n // per factory rather than one per rule (plan S 3.6). Calling it per\r\n // registrar instead would satisfy every behavioural criterion in this phase\r\n // while quietly making the memo per rule, which is why the count has a spec\r\n // of its own.\r\n const source = createModelSource(model, options?.eval);\r\n\r\n /**\r\n * Resolves the two levels `ExpressionRuleOptions` arrives at:\r\n * **registration wins, per key** (plan S 3.5.3). Each key is resolved\r\n * independently and neither is a deep merge, so a registration supplying\r\n * only `onError` keeps the factory's `eval` and vice versa.\r\n *\r\n * Exact for `onError`, partial for `eval.caseInsensitive` - see the note on\r\n * `ExpressionRuleOptions.eval`. The divergence is characterised in\r\n * `rules.spec.ts` rather than left to be discovered.\r\n */\r\n const resolveOptions = (rule?: ExpressionRuleOptions): ExpressionRuleOptions => ({\r\n eval: rule?.eval ?? options?.eval,\r\n onError: rule?.onError ?? options?.onError,\r\n });\r\n\r\n /**\r\n * Everything a registrar does before handing Angular a `LogicFn`, and the\r\n * shape of what it returns is the phase's one structural invariant.\r\n *\r\n * **Called once per registration**, so `parse` + `compile` and\r\n * `createRuleContext()` happen at schema-body time - which Angular re-runs\r\n * once per `form()` (Q8), giving S 3.6's count of one context and one\r\n * compiled callback per rule per form. Nothing here re-parses per\r\n * derivation; risk 8 is a compile that drifts into the returned closure, and\r\n * `rules.invocation-count.spec.ts` counts `compile` to say it has not.\r\n *\r\n * **`guardIdentifiers` runs here, between `parse` and `compile`, and one\r\n * call site is deliberate** (S 3.8, revision 18 item 1). Revision 16's rule\r\n * rejects \"the wrapper is shared\" as a substitute for a per-registrar case,\r\n * and the discriminator it states is whether the subject is a path Angular\r\n * owns. This one is not: the guard throws **before any Angular primitive is\r\n * reached**, so in the rejecting case `hidden`, `metadata` and\r\n * `addDisabledReasonRule` are never called and the three registrars have\r\n * nothing downstream that could diverge. Contrast the invocation count and\r\n * the write-error bypass, whose values arrive *through* those three\r\n * primitives - `rules.spec.ts` gives each of them a case per registrar for\r\n * exactly that reason. Anything the returned closure does stays\r\n * registrar-level; this runs before there is a closure.\r\n *\r\n * **`applyErrorPolicy` is the outermost call in the returned closure, and\r\n * that is load-bearing twice over** (S 3.5). The policy has to cover the\r\n * coercion's *input* rather than only the walk - a registrar that coerced\r\n * first would hand `toVisible` a value the policy never saw - and S 6.1.1's\r\n * invocation instrument counts this exact call. M7 measured what a guard\r\n * hoisted *above* the wrapper does to that number: ground truth 1,\r\n * instrument **0**, which reads as \"the rule did not re-run\" in every\r\n * negative case in this package. A later guard belongs **inside** the\r\n * `run` callback, never ahead of this call.\r\n */\r\n const prepare = (expression: string, ruleOptions?: ExpressionRuleOptions): (() => unknown) => {\r\n const resolved = resolveOptions(ruleOptions);\r\n const node = parse(expression, defaultParserOptions);\r\n\r\n guardIdentifiers(expression, node);\r\n\r\n const compiled = compile(node);\r\n const context = source.createRuleContext();\r\n\r\n return () =>\r\n applyErrorPolicy(() => evaluateRule(compiled, context, resolved.eval), resolved.onError);\r\n };\r\n\r\n return {\r\n\r\n // Angular's **config** overload (S 1.2.7); the deprecated one takes the\r\n // `LogicFn` positionally. `hidden`'s `when` is the only required config of\r\n // the three primitives this entry point registers.\r\n //\r\n // The `!` is S 3.5.1's inversion, and it lives here rather than in every\r\n // consumer's expression so the same rule string means the same thing at\r\n // this entry point and at `/reactive`'s `visible`.\r\n evalVisible: (path, expression, ruleOptions) => {\r\n const evaluated = prepare(expression, ruleOptions);\r\n\r\n hidden(path, { when: () => !toVisible(evaluated()) });\r\n },\r\n\r\n // `text` has no dedicated primitive, so it is Angular's `metadata` against\r\n // the module-scope key of `text-key.ts` (S 1.2.8) - its own mechanism\r\n // rather than a second one beside it.\r\n evalText: (path, expression, ruleOptions) => {\r\n const evaluated = prepare(expression, ruleOptions);\r\n\r\n metadata(path, TEXT, () => toText(evaluated()));\r\n },\r\n\r\n // Angular's polarity, uninverted: `/reactive` ships no `disabled`, so no\r\n // expression has to mean the same thing at two entry points, and `true`\r\n // disabling is what an author expects (S 3.5.1).\r\n //\r\n // **The reason is a static option, never the expression's return**\r\n // (S 3.5.2). Angular's `when` is a single field carrying both the\r\n // condition and the reason - it returns `boolean | string`, and a truthy\r\n // string is *both* (1.2.7) - so a registrar forwarding `evaluated()` raw\r\n // would disable a field on the string `'false'` **with the reason\r\n // `\"false\"`**. Coercing through `toVisible` first, and sourcing the reason\r\n // from the registration instead, is what kills that: the string never\r\n // comes from the expression at all.\r\n //\r\n // A *dynamic* reason stays out of scope - it reopens the trap and needs a\r\n // coercion rule of its own.\r\n evalDisabled: (path, expression, ruleOptions) => {\r\n const evaluated = prepare(expression, ruleOptions);\r\n const reason = ruleOptions?.reason;\r\n\r\n disabled(path, {\r\n when: () => {\r\n // `evaluated()` first, so `applyErrorPolicy` stays the outermost\r\n // call in this body as it is in the other two (S 3.5). `reason` is\r\n // read from a closure rather than branched on ahead of the call:\r\n // a guard hoisted above the wrapper is M7's arrangement, which\r\n // reads 0 on an instrument whose ground truth is 1.\r\n const on = toVisible(evaluated());\r\n\r\n return on && reason !== undefined ? reason : on;\r\n },\r\n });\r\n },\r\n };\r\n};\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FG;AACI,MAAM,YAAY,GAAG,CAC1B,QAAuB,EACvB,OAAoB,EACpB,OAAqB,KACV;AAEX,IAAA,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM;;;;;IAMnC,MAAM,KAAK,GAAG,SAAS,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,CAAC;AAErD,IAAA,IAAI;AACF,QAAA,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC;IAC9B;YAAU;QACR,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,KAAK,EAAE;YACpC,OAAO,CAAC,GAAG,EAAE;QACf;IACF;AACF,CAAC;;ACjHD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEG;AACI,MAAM,gBAAgB,GAAG,CA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