@zvenigora/ng-eval-forms 0.1.0 → 0.2.0

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