@azx-pbc/axiom-react 0.0.0-stage → 0.0.6

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.
Files changed (191) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +604 -2
  3. package/dist/FormErrorBoundary.d.ts +37 -0
  4. package/dist/FormErrorBoundary.d.ts.map +1 -0
  5. package/dist/FormErrorBoundary.js +54 -0
  6. package/dist/FormErrorBoundary.js.map +1 -0
  7. package/dist/FormProvider.d.ts +197 -0
  8. package/dist/FormProvider.d.ts.map +1 -0
  9. package/dist/FormProvider.js +149 -0
  10. package/dist/FormProvider.js.map +1 -0
  11. package/dist/field-error.d.ts +154 -0
  12. package/dist/field-error.d.ts.map +1 -0
  13. package/dist/field-error.js +2 -0
  14. package/dist/field-error.js.map +1 -0
  15. package/dist/field-props.d.ts +362 -0
  16. package/dist/field-props.d.ts.map +1 -0
  17. package/dist/field-props.js +64 -0
  18. package/dist/field-props.js.map +1 -0
  19. package/dist/form-context.d.ts +31 -0
  20. package/dist/form-context.d.ts.map +1 -0
  21. package/dist/form-context.js +13 -0
  22. package/dist/form-context.js.map +1 -0
  23. package/dist/form-store.d.ts +784 -0
  24. package/dist/form-store.d.ts.map +1 -0
  25. package/dist/form-store.js +2179 -0
  26. package/dist/form-store.js.map +1 -0
  27. package/dist/hints.d.ts +60 -0
  28. package/dist/hints.d.ts.map +1 -0
  29. package/dist/hints.js +158 -0
  30. package/dist/hints.js.map +1 -0
  31. package/dist/index.d.ts +57 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +36 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/render/field-value.d.ts +92 -0
  36. package/dist/render/field-value.d.ts.map +1 -0
  37. package/dist/render/field-value.js +124 -0
  38. package/dist/render/field-value.js.map +1 -0
  39. package/dist/render/nodes.d.ts +303 -0
  40. package/dist/render/nodes.d.ts.map +1 -0
  41. package/dist/render/nodes.js +325 -0
  42. package/dist/render/nodes.js.map +1 -0
  43. package/dist/render/schema.d.ts +30 -0
  44. package/dist/render/schema.d.ts.map +1 -0
  45. package/dist/render/schema.js +40 -0
  46. package/dist/render/schema.js.map +1 -0
  47. package/dist/render/value-text.d.ts +59 -0
  48. package/dist/render/value-text.d.ts.map +1 -0
  49. package/dist/render/value-text.js +104 -0
  50. package/dist/render/value-text.js.map +1 -0
  51. package/dist/store/array-bindings.d.ts +110 -0
  52. package/dist/store/array-bindings.d.ts.map +1 -0
  53. package/dist/store/array-bindings.js +181 -0
  54. package/dist/store/array-bindings.js.map +1 -0
  55. package/dist/store/bindings.d.ts +12 -0
  56. package/dist/store/bindings.d.ts.map +1 -0
  57. package/dist/store/bindings.js +16 -0
  58. package/dist/store/bindings.js.map +1 -0
  59. package/dist/store/buffer-state.d.ts +42 -0
  60. package/dist/store/buffer-state.d.ts.map +1 -0
  61. package/dist/store/buffer-state.js +51 -0
  62. package/dist/store/buffer-state.js.map +1 -0
  63. package/dist/store/configure.d.ts +19 -0
  64. package/dist/store/configure.d.ts.map +1 -0
  65. package/dist/store/configure.js +28 -0
  66. package/dist/store/configure.js.map +1 -0
  67. package/dist/store/derive.d.ts +106 -0
  68. package/dist/store/derive.d.ts.map +1 -0
  69. package/dist/store/derive.js +417 -0
  70. package/dist/store/derive.js.map +1 -0
  71. package/dist/store/errors.d.ts +20 -0
  72. package/dist/store/errors.d.ts.map +1 -0
  73. package/dist/store/errors.js +101 -0
  74. package/dist/store/errors.js.map +1 -0
  75. package/dist/store/fields.d.ts +35 -0
  76. package/dist/store/fields.d.ts.map +1 -0
  77. package/dist/store/fields.js +81 -0
  78. package/dist/store/fields.js.map +1 -0
  79. package/dist/store/form-channel.d.ts +174 -0
  80. package/dist/store/form-channel.d.ts.map +1 -0
  81. package/dist/store/form-channel.js +411 -0
  82. package/dist/store/form-channel.js.map +1 -0
  83. package/dist/store/gates.d.ts +22 -0
  84. package/dist/store/gates.d.ts.map +1 -0
  85. package/dist/store/gates.js +44 -0
  86. package/dist/store/gates.js.map +1 -0
  87. package/dist/store/ids.d.ts +20 -0
  88. package/dist/store/ids.d.ts.map +1 -0
  89. package/dist/store/ids.js +28 -0
  90. package/dist/store/ids.js.map +1 -0
  91. package/dist/store/inputs.d.ts +114 -0
  92. package/dist/store/inputs.d.ts.map +1 -0
  93. package/dist/store/inputs.js +202 -0
  94. package/dist/store/inputs.js.map +1 -0
  95. package/dist/store/layout.d.ts +81 -0
  96. package/dist/store/layout.d.ts.map +1 -0
  97. package/dist/store/layout.js +285 -0
  98. package/dist/store/layout.js.map +1 -0
  99. package/dist/store/messages.d.ts +56 -0
  100. package/dist/store/messages.d.ts.map +1 -0
  101. package/dist/store/messages.js +157 -0
  102. package/dist/store/messages.js.map +1 -0
  103. package/dist/store/option-pages.d.ts +193 -0
  104. package/dist/store/option-pages.d.ts.map +1 -0
  105. package/dist/store/option-pages.js +598 -0
  106. package/dist/store/option-pages.js.map +1 -0
  107. package/dist/store/parse-print.d.ts +105 -0
  108. package/dist/store/parse-print.d.ts.map +1 -0
  109. package/dist/store/parse-print.js +415 -0
  110. package/dist/store/parse-print.js.map +1 -0
  111. package/dist/store/proposals.d.ts +114 -0
  112. package/dist/store/proposals.d.ts.map +1 -0
  113. package/dist/store/proposals.js +90 -0
  114. package/dist/store/proposals.js.map +1 -0
  115. package/dist/store/publish.d.ts +48 -0
  116. package/dist/store/publish.d.ts.map +1 -0
  117. package/dist/store/publish.js +96 -0
  118. package/dist/store/publish.js.map +1 -0
  119. package/dist/store/snapshots.d.ts +63 -0
  120. package/dist/store/snapshots.d.ts.map +1 -0
  121. package/dist/store/snapshots.js +154 -0
  122. package/dist/store/snapshots.js.map +1 -0
  123. package/dist/store/steps.d.ts +13 -0
  124. package/dist/store/steps.d.ts.map +1 -0
  125. package/dist/store/steps.js +31 -0
  126. package/dist/store/steps.js.map +1 -0
  127. package/dist/store/view.d.ts +124 -0
  128. package/dist/store/view.d.ts.map +1 -0
  129. package/dist/store/view.js +301 -0
  130. package/dist/store/view.js.map +1 -0
  131. package/dist/store/visibility.d.ts +68 -0
  132. package/dist/store/visibility.d.ts.map +1 -0
  133. package/dist/store/visibility.js +231 -0
  134. package/dist/store/visibility.js.map +1 -0
  135. package/dist/store/wizard-cursor.d.ts +43 -0
  136. package/dist/store/wizard-cursor.d.ts.map +1 -0
  137. package/dist/store/wizard-cursor.js +67 -0
  138. package/dist/store/wizard-cursor.js.map +1 -0
  139. package/dist/store/writes.d.ts +50 -0
  140. package/dist/store/writes.d.ts.map +1 -0
  141. package/dist/store/writes.js +91 -0
  142. package/dist/store/writes.js.map +1 -0
  143. package/dist/typed.d.ts +134 -0
  144. package/dist/typed.d.ts.map +1 -0
  145. package/dist/typed.js +74 -0
  146. package/dist/typed.js.map +1 -0
  147. package/dist/useAsyncOptions.d.ts +20 -0
  148. package/dist/useAsyncOptions.d.ts.map +1 -0
  149. package/dist/useAsyncOptions.js +70 -0
  150. package/dist/useAsyncOptions.js.map +1 -0
  151. package/dist/useBufferedInput.d.ts +69 -0
  152. package/dist/useBufferedInput.d.ts.map +1 -0
  153. package/dist/useBufferedInput.js +132 -0
  154. package/dist/useBufferedInput.js.map +1 -0
  155. package/dist/useField.d.ts +42 -0
  156. package/dist/useField.d.ts.map +1 -0
  157. package/dist/useField.js +63 -0
  158. package/dist/useField.js.map +1 -0
  159. package/dist/useFieldArray.d.ts +25 -0
  160. package/dist/useFieldArray.d.ts.map +1 -0
  161. package/dist/useFieldArray.js +18 -0
  162. package/dist/useFieldArray.js.map +1 -0
  163. package/dist/useForm.d.ts +20 -0
  164. package/dist/useForm.d.ts.map +1 -0
  165. package/dist/useForm.js +9 -0
  166. package/dist/useForm.js.map +1 -0
  167. package/dist/useFormState.d.ts +23 -0
  168. package/dist/useFormState.d.ts.map +1 -0
  169. package/dist/useFormState.js +11 -0
  170. package/dist/useFormState.js.map +1 -0
  171. package/dist/useGate.d.ts +15 -0
  172. package/dist/useGate.d.ts.map +1 -0
  173. package/dist/useGate.js +21 -0
  174. package/dist/useGate.js.map +1 -0
  175. package/dist/useLayout.d.ts +29 -0
  176. package/dist/useLayout.d.ts.map +1 -0
  177. package/dist/useLayout.js +59 -0
  178. package/dist/useLayout.js.map +1 -0
  179. package/dist/useMessage.d.ts +58 -0
  180. package/dist/useMessage.d.ts.map +1 -0
  181. package/dist/useMessage.js +62 -0
  182. package/dist/useMessage.js.map +1 -0
  183. package/dist/useWatch.d.ts +19 -0
  184. package/dist/useWatch.d.ts.map +1 -0
  185. package/dist/useWatch.js +17 -0
  186. package/dist/useWatch.js.map +1 -0
  187. package/dist/useWizard.d.ts +166 -0
  188. package/dist/useWizard.d.ts.map +1 -0
  189. package/dist/useWizard.js +554 -0
  190. package/dist/useWizard.js.map +1 -0
  191. package/package.json +62 -3
@@ -0,0 +1,2179 @@
1
+ import { AxiomError, assertNever, canonicalizeRestricted, checkWrite, createCancellationPort, inspectDeps, rowKeyToken, sameWireValue, toAccessOverlay, toWireValue, } from '@azx-pbc/axiom-runtime';
2
+ import { bindingKey, bindingRef } from './store/bindings.js';
3
+ import { sameFieldErrors } from './store/derive.js';
4
+ import { fieldFacts, fieldFactsOf, validateInitialValues } from './store/fields.js';
5
+ import { bindingErrors } from './store/errors.js';
6
+ import { buildFormSummary, sameFormSummary } from './store/form-channel.js';
7
+ import { DEFAULT_POLICY, errorKey, incompleteRulesOf, sameIdSet } from './store/visibility.js';
8
+ import { evaluationInputOf, resolveSessionInputs, sameInputs, sameOverrides, } from './store/inputs.js';
9
+ import { gateViewOf, sameGateView } from './store/gates.js';
10
+ import { ArrayBindings, ArrayWriters } from './store/array-bindings.js';
11
+ import { fieldsByIdOf, findLayoutNode, findLayoutSection, layoutOf, layoutSliceOf, sameLayoutSlice, sameLayoutViews, } from './store/layout.js';
12
+ import { optionPageKey, OptionPages } from './store/option-pages.js';
13
+ import { ArraySubscriptions, FieldSubscriptions } from './store/publish.js';
14
+ import { editedBinding, isStructuralOperation, offersAlternatives } from './store/proposals.js';
15
+ import { FieldSnapshots, ValueSnapshots } from './store/snapshots.js';
16
+ import { heldValuesOf, SessionView } from './store/view.js';
17
+ import { declarationFor, FieldWriters, itemDeclarationFor, writeRefusalError, } from './store/writes.js';
18
+ import { openEngine } from './store/configure.js';
19
+ /**
20
+ * The form session a provider owns: one compiled artifact, one engine in force, and the
21
+ * React-side facts the engine does not keep.
22
+ *
23
+ * The engine owns values, access, row identity, the incremental pass, the derived field state
24
+ * and the submission projection. This class is the session shell: it derives candidate views
25
+ * without mutating committed state, keeps each binding's published props identity stable, holds
26
+ * `touched`/`dirty`/`submitCount` — the facts a session has and a record does not — and
27
+ * publishes only what changed. It owns no fact index, no derivation and no write rule of its
28
+ * own (`[ENGINE-7.1.2]`, `[ENGINE-5.1.3]`).
29
+ */
30
+ export class FormStore {
31
+ compiled;
32
+ facts;
33
+ /** Every rule's declared reads, from the artifact's cached dependency inspection. */
34
+ ruleReads;
35
+ initialValues;
36
+ idFactory;
37
+ subscriptions = new FieldSubscriptions();
38
+ formSubscriptions = new Set();
39
+ snapshots = new FieldSnapshots();
40
+ watched = new ValueSnapshots();
41
+ writers = new FieldWriters();
42
+ arrays = new ArrayBindings();
43
+ arraySubscriptions = new ArraySubscriptions();
44
+ arrayWriters = new ArrayWriters();
45
+ optionPages;
46
+ optionDomains;
47
+ layoutCache;
48
+ /** The declaration index every slice one publish reads shares, keyed by committed form. */
49
+ fieldIndex;
50
+ /**
51
+ * One slice per layout node and section id. The keys are artifact identifiers, so the map is
52
+ * bounded by the artifact's chrome and never by a session: a provider mounted for a shift sees
53
+ * the same node ids on its last render as on its first.
54
+ */
55
+ sliceMemo = new Map();
56
+ /** One view per declared gate id: bounded by the artifact, like `sliceMemo`. */
57
+ gateMemo = new Map();
58
+ layoutSubscriptions = new Set();
59
+ /** Consumers whose option basis keyed on a session-wide member may have moved. */
60
+ basisSubscriptions = new Set();
61
+ publishedBasis;
62
+ view = new SessionView();
63
+ /** One structurally-shared visibility answer per binding, so unchanged facts keep its identity. */
64
+ visibilityMemo = new Map();
65
+ /** The non-throwing write callbacks of each binding, built beside `writers` so both stay stable. */
66
+ attemptWriters = new Map();
67
+ /**
68
+ * The published props of each base snapshot, keyed by the snapshot they extend.
69
+ *
70
+ * Entries die with their base keys once the snapshot cache drops them, so neither a retire
71
+ * nor a reset clears this: a candidate read and a committed read keep their own extension
72
+ * without evicting one another.
73
+ */
74
+ publishedPropsMemo = new WeakMap();
75
+ /** The last paint list each binding stated, reused while the same failures hold. */
76
+ announceMemo = new Map();
77
+ session;
78
+ previewed;
79
+ hostOverrides;
80
+ imperativeOverlay;
81
+ /** Inputs an event handler installed, which stay in force while the props name none. */
82
+ imperativeContext;
83
+ imperativeEnv;
84
+ submitCount = 0;
85
+ isSubmitting = false;
86
+ /** Whether the last settled submission reached `onValid` and it returned without throwing. */
87
+ submitSucceeded = false;
88
+ inFlight = null;
89
+ mounted = true;
90
+ published;
91
+ summary;
92
+ candidateSummary;
93
+ trace = { bindings: [], arrays: [], ruleEvaluations: {} };
94
+ reportedPass;
95
+ publishListener;
96
+ /**
97
+ * The host's staged-write interceptor, when it installed one.
98
+ *
99
+ * It is present exactly when `FormProvider` was given `onWriteProposed`: a session with no
100
+ * interceptor hands every write straight to the engine, so a form that stages nothing pays
101
+ * nothing for the feature.
102
+ */
103
+ writeInterceptor;
104
+ /**
105
+ * The one staged write the host is confirming, and the order that says which is newest.
106
+ *
107
+ * A session stages at most one write: a newer qualifying write replaces the pending one, so a
108
+ * host never holds two proposals it could apply in either order. `nextProposalSequence` keeps
109
+ * counting after a proposal is cleared, so an older staged proposal is still refused once the
110
+ * newer one has been applied.
111
+ */
112
+ pendingProposal;
113
+ nextProposalSequence = 0;
114
+ /**
115
+ * The candidates a host declined while they were the pending confirmation.
116
+ *
117
+ * Cleared pending state alone cannot answer "was this write cancelled": the engine still holds
118
+ * the derived candidate, so a sequence that outlived its confirmation would otherwise look
119
+ * committable. A declined candidate is never applied, and the weak set lets it go with the
120
+ * proposal the host stopped holding.
121
+ */
122
+ declinedCandidates = new WeakSet();
123
+ /**
124
+ * The high-level user writes behind a staged candidate.
125
+ *
126
+ * Replacing an assigned array becomes remove/append operations, but its direct control write
127
+ * marks the container. The candidate key carries that fact through a reconstructed public
128
+ * wrapper without letting wrapper metadata describe a different change set.
129
+ */
130
+ proposalUserWrites = new WeakMap();
131
+ /**
132
+ * The bindings the user has written in this session, by binding key.
133
+ *
134
+ * The engine reports one reference per written binding but not who wrote it, so a host claim
135
+ * and a user's own write look alike there. This is the provenance: a host claim the user never
136
+ * wrote is dropped with the prop that declared it, and one the user did write is replayed —
137
+ * subtracting it would blank the control the user is typing in.
138
+ */
139
+ userWrites = new Set();
140
+ /** The addressable-row index, memoised by the committed form object `publish` saw. */
141
+ rowIndex;
142
+ /** The view identity a summary is keyed to; a write, blur or submit advances it. */
143
+ snapshotEpoch = 0;
144
+ nextRevision = 0;
145
+ formHandle;
146
+ /**
147
+ * The prefix every element id this session emits begins with.
148
+ *
149
+ * Settled once, when the session opens: `FormProvider` passes the host's `idPrefix` or the
150
+ * `useId()` one it minted for this mount. It is not a display option a host flips mid-session —
151
+ * re-keying every control's id under a rendered label helps no one — so it lives on the store
152
+ * and every display the store derives carries it.
153
+ */
154
+ idPrefix;
155
+ constructor(config, idPrefix) {
156
+ this.idPrefix = idPrefix;
157
+ this.compiled = config.compiled;
158
+ this.facts = fieldFacts(config.compiled);
159
+ this.ruleReads = ruleReadsOf(config.compiled);
160
+ this.hostOverrides = config;
161
+ this.optionPages = new OptionPages(config.optionSources ?? {}, config.cancellation ?? createCancellationPort, config.defer);
162
+ // A loaded page is a derivation input: the field's eligibility is read from it, so a page
163
+ // list that changed re-derives committed state before this publish tells anyone.
164
+ this.optionPages.subscribe(() => {
165
+ this.optionDomainChanged();
166
+ });
167
+ const inputs = this.effective(config);
168
+ // Every value entering the store is read through the wire contract once, so a control
169
+ // always holds a canonical, private copy of what the host supplied.
170
+ this.initialValues = validateInitialValues(this.facts, config.initialValues);
171
+ this.idFactory = config.idFactory;
172
+ const engine = this.open(inputs, this.initialValues, inputs.sessionWrites, config.rowManifest);
173
+ this.session = this.newSession(engine, inputs, this.defaultDisplay(), config);
174
+ this.captureBaseline(engine);
175
+ }
176
+ /** The published per-binding props of committed state. */
177
+ getFieldProps(fieldId, rowKey) {
178
+ return this.propsOf(this.session, fieldId, rowKey);
179
+ }
180
+ /** The per-binding props as one candidate derived them, for the render reading it. */
181
+ getCandidateFieldProps(candidate, fieldId, rowKey) {
182
+ return this.propsOf(this.sessionOf(candidate), fieldId, rowKey);
183
+ }
184
+ /** The engine's identity-stable value state of one binding, as committed. */
185
+ getValueState(fieldId, rowKey) {
186
+ return this.valueStateOf(this.session, fieldId, rowKey);
187
+ }
188
+ /** The value state as one candidate derived it. */
189
+ getCandidateValueState(candidate, fieldId, rowKey) {
190
+ return this.valueStateOf(this.sessionOf(candidate), fieldId, rowKey);
191
+ }
192
+ /** The form-level summary of committed state. */
193
+ getFormSummary() {
194
+ return this.summaryOf(this.session);
195
+ }
196
+ /** The form-level summary as one candidate derived it. */
197
+ getCandidateFormSummary(candidate) {
198
+ return this.summaryOf(this.sessionOf(candidate));
199
+ }
200
+ subscribe(fieldId, rowKey, listener) {
201
+ const ref = typeof rowKey === 'function' ? bindingRef(fieldId, undefined) : bindingRef(fieldId, rowKey);
202
+ fieldFactsOf(this.facts, ref.fieldId, ref.rowKey, this.compiled.schemaId);
203
+ const notify = typeof rowKey === 'function' ? rowKey : listener;
204
+ if (notify === undefined)
205
+ throw new Error('a subscription needs a listener');
206
+ return this.subscriptions.subscribe(ref, notify);
207
+ }
208
+ /** Registers `listener` on the form channel; the returned release is idempotent. */
209
+ subscribeForm(listener) {
210
+ this.formSubscriptions.add(listener);
211
+ return () => {
212
+ this.formSubscriptions.delete(listener);
213
+ };
214
+ }
215
+ /** How many listeners one binding currently has, so a leak can be counted rather than assumed. */
216
+ subscriptionCount(fieldId, rowKey) {
217
+ return this.subscriptions.count(bindingRef(fieldId, rowKey));
218
+ }
219
+ /**
220
+ * How many live entries each per-binding cache retains.
221
+ *
222
+ * A test seam, like `subscriptionCount`, and not part of the package entry: a list that
223
+ * appends and removes rows has to be able to count what a removed row left behind instead of
224
+ * trusting that the caches let go of it.
225
+ */
226
+ retainedBindings() {
227
+ return {
228
+ snapshots: this.snapshots.retained(),
229
+ values: this.watched.retained(),
230
+ writers: this.writers.retained(),
231
+ views: this.view.retained(),
232
+ rowRefs: this.arrays.retainedRows(),
233
+ touched: this.view.touchedCount(),
234
+ changed: this.view.changedCount(),
235
+ written: this.userWrites.size,
236
+ };
237
+ }
238
+ /**
239
+ * Whether the artifact declares a field with this id.
240
+ *
241
+ * A read of the declaration, not of the record: an unmounted row and a withheld value are
242
+ * still declared. The untyped `useField` door reads it for its development guard, so a
243
+ * declared id where a row key belongs names the typed door instead of failing later.
244
+ */
245
+ declaresField(fieldId) {
246
+ return this.facts.has(fieldId);
247
+ }
248
+ /**
249
+ * Whether the artifact holds rows under this field: an array container, or a member whose
250
+ * value exists once per row.
251
+ */
252
+ declaresRows(fieldId) {
253
+ const facts = this.facts.get(fieldId);
254
+ if (facts === undefined)
255
+ return false;
256
+ return facts.field.primitive === 'array' || facts.arrayContainerId !== undefined;
257
+ }
258
+ /**
259
+ * Derives the session state a render with these inputs would read, without assigning any
260
+ * committed state. The same inputs, raw overrides and display return the same candidate, so an
261
+ * unchanged render neither re-evaluates nor replaces a snapshot.
262
+ */
263
+ preview(overrides, display) {
264
+ const inputs = this.effective(overrides);
265
+ const shown = display ?? this.session.display;
266
+ if (this.previewed !== undefined && this.sameView(this.previewed, inputs, shown, overrides)) {
267
+ return this.previewed;
268
+ }
269
+ if (sameInputs(inputs, this.session.inputs) &&
270
+ sameDisplay(shown, this.session.display) &&
271
+ sameOverrides(this.session.candidate.overrides, overrides)) {
272
+ this.previewed = this.session.candidate;
273
+ return this.session.candidate;
274
+ }
275
+ // A display-only change reuses the session the store already holds: how a failure is
276
+ // revealed is not a record change, so re-opening the engine for it would evaluate the whole
277
+ // record again and replay every assigned row id for nothing.
278
+ const engine = sameInputs(inputs, this.session.inputs)
279
+ ? this.session.engine
280
+ : this.open(inputs, this.session.engine.values(), this.writesFor(inputs), this.session.engine.rowManifest());
281
+ const candidate = this.newCandidate(engine, inputs, shown, overrides);
282
+ this.previewed = candidate;
283
+ return candidate;
284
+ }
285
+ /**
286
+ * Adopts a candidate a render derived, and nothing else. A candidate that is not the latest
287
+ * preview belongs to a render React superseded or discarded — a Suspense abort, a transition
288
+ * it threw away — so it commits nothing.
289
+ *
290
+ * It answers whether it adopted a *different* view. A commit that changed nothing needs no
291
+ * publish, which is what keeps an unrelated re-render of the provider from re-deriving every
292
+ * subscribed binding.
293
+ */
294
+ commit(candidate) {
295
+ if (candidate !== this.previewed)
296
+ return false;
297
+ if (candidate.revision <= this.session.candidate.revision)
298
+ return false;
299
+ // Only a committed render may change which props an imperative setter must yield to.
300
+ this.hostOverrides = candidate.overrides;
301
+ // A commit that re-opened the engine replaced the state a staged write was derived from, so
302
+ // the confirmation it belonged to no longer names the write this session would take. A
303
+ // display-only commit reuses the engine and leaves the confirmation answerable.
304
+ if (candidate.engine !== this.session.engine)
305
+ this.retirePending();
306
+ this.snapshots.commit(candidate);
307
+ this.watched.commit(candidate);
308
+ this.arrays.commit(candidate);
309
+ if (this.candidateSummary?.owner === candidate) {
310
+ const cache = this.candidateSummary.cache;
311
+ // A summary derived before a write staged a proposal states no pending proposal; adopting
312
+ // it would hide the confirmation the host must answer. Leave the committed summary unset so
313
+ // the next read rebuilds it from the proposal the session now holds.
314
+ this.summary = cache.pendingProposal === this.pendingProposal ? cache : undefined;
315
+ this.candidateSummary = undefined;
316
+ }
317
+ const changed = !sameInputs(candidate.inputs, this.session.inputs) ||
318
+ !sameDisplay(candidate.display, this.session.display);
319
+ this.session = {
320
+ engine: candidate.engine,
321
+ inputs: candidate.inputs,
322
+ display: candidate.display,
323
+ candidate,
324
+ };
325
+ if (changed)
326
+ this.markChanged();
327
+ return changed;
328
+ }
329
+ /**
330
+ * Applies the evaluation inputs the host is rendering with, as the imperative composition of
331
+ * a preview and a commit, for a caller outside a render. A provider renders through `preview`
332
+ * and commits in the insertion phase instead, so a render it abandons leaves the session
333
+ * untouched.
334
+ */
335
+ configure(overrides) {
336
+ this.commit(this.preview(overrides));
337
+ }
338
+ /**
339
+ * Tells every subscribed binding whose props object changed, then the form channel if the
340
+ * summary changed. The trace names what this publish delivered and copies the pass counts
341
+ * from the engine's own last-pass trace.
342
+ */
343
+ publish() {
344
+ // Sticky reveals are session history, so they are reconciled at the first moment committed
345
+ // state is read as a whole: before any subscriber derives. A binding whose failure is still
346
+ // true keeps its painted key; a binding whose failure was corrected drops it here, which is
347
+ // what lets a later, different failure be judged by the policy afresh.
348
+ this.reconcileReveal();
349
+ // The row index is built from committed state only if a row-keyed binding asks for it, and
350
+ // once per committed form: a form with thirty thousand rows pays one pass over its fields
351
+ // rather than a scan of them per notified binding, and a publish nobody subscribed to a row
352
+ // before pays nothing at all.
353
+ let reachable;
354
+ const reachableRows = () => (reachable ??= this.addressableRows());
355
+ const bindings = this.subscriptions.publish((key, ref) => {
356
+ // A removed row's control is still mounted for the commit that removed it, and committed
357
+ // state no longer addresses it. Its registration stays: `useField`'s subscribe callback is
358
+ // stable for one binding, so React never re-registers a mounted control and evicting here
359
+ // would leave it unable to learn that its row came back. A dormant registration costs
360
+ // nothing — it is handed no derivation until it is addressable again, and then this
361
+ // publish notifies it once. The caches it filled are dropped now, so a removed row's props
362
+ // and the value they hold are not retained until the session ends.
363
+ if (!this.addresses(ref, reachableRows)) {
364
+ this.retireBinding(key, ref);
365
+ return false;
366
+ }
367
+ // The previous object has to be read before the derivation replaces it: the cache holds
368
+ // one entry per binding, and a derivation stores the new one. The comparison is on the
369
+ // snapshot layer, which keeps its identity while the binding's state holds; the published
370
+ // extension is a different object by construction and would notify every subscriber.
371
+ const previous = this.snapshots.current(key);
372
+ const facts = fieldFactsOf(this.facts, ref.fieldId, ref.rowKey, this.compiled.schemaId);
373
+ const state = this.engineStateOf(this.session, ref.fieldId, ref.rowKey);
374
+ return this.snapshotOf(this.session, key, facts, state, ref.fieldId, ref.rowKey) !== previous;
375
+ });
376
+ const arrays = this.arraySubscriptions.publish((fieldId) => {
377
+ // A committed read returns the view it already holds while the structure holds, so a
378
+ // changed identity is exactly what a list subscriber must be told about.
379
+ const previous = this.arrays.current(fieldId);
380
+ return (this.arrays.read(this.session.candidate, true, this.session.engine, fieldId) !== previous);
381
+ });
382
+ this.publishForm();
383
+ for (const listener of [...this.layoutSubscriptions])
384
+ listener();
385
+ this.publishOptionBasis();
386
+ // The counts belong to the pass this publish delivered. A publish that ran no pass — a
387
+ // blur, a summary-only change, a reconfigure — reports none rather than repeating the
388
+ // previous write's numbers as though it had evaluated them.
389
+ const pass = this.session.engine.lastPass();
390
+ const fresh = pass !== this.reportedPass;
391
+ this.reportedPass = pass;
392
+ this.trace = { bindings, arrays, ruleEvaluations: fresh ? pass.ruleEvaluations : {} };
393
+ this.publishListener?.(this.trace);
394
+ }
395
+ /**
396
+ * Observes every committed-state publish, or clears the observer with `undefined`.
397
+ *
398
+ * A summary-only notification is not a publish: `publishForm` states the changed summary on
399
+ * the form channel alone, so a staged-write confirmation is announced there rather than here.
400
+ */
401
+ observePublishes(listener) {
402
+ this.publishListener = listener;
403
+ }
404
+ /**
405
+ * Installs the staged-write interceptor, or removes it with `undefined`.
406
+ *
407
+ * While one is installed every user write is previewed before it commits: a change set that
408
+ * adds a blocker offering alternatives is staged and reported instead of committed, and the
409
+ * host answers it with `applyProposal` or `discardProposal`. With none installed a write is
410
+ * handed to the engine exactly as before.
411
+ */
412
+ interceptWrites(listener) {
413
+ this.writeInterceptor = listener;
414
+ }
415
+ /** The engine's counted facts of the last committed pass. */
416
+ lastPass() {
417
+ return this.session.engine.lastPass();
418
+ }
419
+ /** The access version committed state was derived under. */
420
+ accessVersion() {
421
+ return this.session.engine.lastPass().accessVersion;
422
+ }
423
+ /**
424
+ * The `onHide: "exclude"` submission projection of committed state. It accepts no
425
+ * caller-supplied report, and refuses a signature that would travel without its coverage.
426
+ * `writableOnly` is the body a client sends; the default is the record this process stores.
427
+ */
428
+ exportSubmission(options) {
429
+ return this.session.engine.exportSubmission(options);
430
+ }
431
+ /**
432
+ * Re-baselines the session from `values`, or from the record it opened with.
433
+ *
434
+ * The new record crosses the wire contract, the engine derives its row identity afresh, and
435
+ * the touched set, the dirty baselines, the submit count and every session write are cleared
436
+ * — so a `write_only` value typed before a reset is no longer readable in the new session.
437
+ */
438
+ reset(values) {
439
+ const next = validateInitialValues(this.facts, values ?? this.initialValues);
440
+ const inputs = { ...this.session.inputs, sessionWrites: [] };
441
+ const engine = this.open(inputs, next, [], undefined);
442
+ this.session = this.newSession(engine, inputs, this.session.display, this.hostOverrides);
443
+ this.captureBaseline(engine);
444
+ // A reset is the one retirement path for a session write: the facts that said the user
445
+ // typed a `write_only` value belong to the session that opened before this one.
446
+ this.userWrites.clear();
447
+ this.clearCaches();
448
+ this.submitCount = 0;
449
+ this.isSubmitting = false;
450
+ this.submitSucceeded = false;
451
+ this.retirePending();
452
+ this.previewed = undefined;
453
+ this.snapshotChanged();
454
+ }
455
+ /**
456
+ * Drops every cache derived from the session that just ended.
457
+ *
458
+ * `capture()` clears the session facts (baselines, touched, changed, refusals, revealed and
459
+ * per-binding views), but the per-binding props, watched values, writer closures and derived
460
+ * chrome are keyed by binding and would otherwise outlive the reset. A `write_only` value an
461
+ * unread binding still held in `FieldProps.value` is exactly the value `reset()` promises is
462
+ * no longer readable. A binding that is still mounted re-derives on the publish that follows.
463
+ */
464
+ clearCaches() {
465
+ this.snapshots.clear();
466
+ this.watched.clear();
467
+ this.writers.clear();
468
+ this.attemptWriters.clear();
469
+ this.announceMemo.clear();
470
+ this.arrays.clear();
471
+ this.visibilityMemo.clear();
472
+ this.sliceMemo.clear();
473
+ this.gateMemo.clear();
474
+ this.layoutCache = undefined;
475
+ this.fieldIndex = undefined;
476
+ }
477
+ /** The stable write callback for one binding; the same function on every call. */
478
+ setValueFor(fieldId, rowKey) {
479
+ return this.writersOf(fieldId, rowKey).setValue;
480
+ }
481
+ /** The stable blur callback for one binding; the same function on every call. */
482
+ blurFor(fieldId, rowKey) {
483
+ return this.writersOf(fieldId, rowKey).onBlur;
484
+ }
485
+ /** One array binding's committed structure: its rows in order and its mutation permissions. */
486
+ getArrayView(fieldId) {
487
+ return this.arrayViewOf(this.session, fieldId);
488
+ }
489
+ /** The array structure as one candidate derived it, for the render reading it. */
490
+ getCandidateArrayView(candidate, fieldId) {
491
+ return this.arrayViewOf(this.sessionOf(candidate), fieldId);
492
+ }
493
+ /** Registers `listener` for one array's structure; the returned release is idempotent. */
494
+ subscribeArray(fieldId, listener) {
495
+ fieldFactsOf(this.facts, fieldId, undefined, this.compiled.schemaId);
496
+ return this.arraySubscriptions.subscribe(fieldId, listener);
497
+ }
498
+ /** The five structural operations of one array, with stable identities. */
499
+ arrayControls(fieldId) {
500
+ return this.arrayWriters.for(fieldId, () => {
501
+ const facts = fieldFactsOf(this.facts, fieldId, undefined, this.compiled.schemaId);
502
+ const declaration = itemDeclarationFor(facts);
503
+ const parse = (value) => toWireValue(value, `$.values.${fieldId}`, declaration);
504
+ return {
505
+ append: (value) => this.structural([{ kind: 'append', fieldId, value: parse(value), origin: 'user' }]),
506
+ insert: (index, value) => this.structural([
507
+ { kind: 'insert', fieldId, index, value: parse(value), origin: 'user' },
508
+ ]),
509
+ remove: (rowKey) => this.structural([{ kind: 'removeRow', fieldId, rowKey, origin: 'user' }]),
510
+ move: (fromIndex, toIndex) => this.moveArray(fieldId, fromIndex, toIndex),
511
+ moveRow: (rowKey, toIndex) => this.structural([{ kind: 'move', fieldId, rowKey, toIndex, origin: 'user' }]),
512
+ replace: (values) => this.replaceArray(fieldId, values),
513
+ };
514
+ });
515
+ }
516
+ /**
517
+ * The basis one option page list is keyed by, `[MODEL-3.1.8]`.
518
+ *
519
+ * The signature is built from the binding, the source, the declared dependencies' current
520
+ * values, the session record date and the access version, so a change to any of them is a
521
+ * different list. A dependency this device may not read makes the basis unreadable and never
522
+ * reaches the loader. The reader's search text is not a member: it narrows the pages of one
523
+ * domain, and the page machine publishes it and owns the request that answers it.
524
+ */
525
+ optionBasis(fieldId, rowKey) {
526
+ const facts = fieldFactsOf(this.facts, fieldId, rowKey, this.compiled.schemaId);
527
+ const source = hostOptionSource(facts.field.optionSource, fieldId);
528
+ const dependsOn = {};
529
+ let readable = true;
530
+ for (const ref of this.optionDependencyRefs(fieldId, rowKey)) {
531
+ const value = this.session.engine.getField(ref.fieldId, ref.rowKey).value;
532
+ if (value.kind === 'withheld') {
533
+ readable = false;
534
+ dependsOn[ref.fieldId] = undefined;
535
+ continue;
536
+ }
537
+ dependsOn[ref.fieldId] = value.kind === 'value' ? value.value : undefined;
538
+ }
539
+ const recordDate = this.session.inputs.env.recordDate;
540
+ const accessVersion = this.session.engine.lastPass().accessVersion;
541
+ const dependencies = Object.keys(dependsOn)
542
+ .map((depId) => `${depId}=${valueSignature(dependsOn[depId])}`)
543
+ .join('\u0001');
544
+ const signature = [
545
+ this.compiled.schemaId,
546
+ optionPageKey(fieldId, rowKey),
547
+ source.sourceId,
548
+ recordDate ?? '',
549
+ String(accessVersion),
550
+ readable ? '1' : '0',
551
+ dependencies,
552
+ ].join('\u0000');
553
+ return {
554
+ fieldId,
555
+ ...(rowKey === undefined ? {} : { rowKey }),
556
+ sourceId: source.sourceId,
557
+ dependsOn,
558
+ readable,
559
+ signature,
560
+ };
561
+ }
562
+ /**
563
+ * The bindings whose changes re-key one option list.
564
+ *
565
+ * A source declared on a row reads a top-level dependency as it stands and a sibling member
566
+ * in that row, so the list re-renders only for the values its own page keys on.
567
+ */
568
+ optionDependencyRefs(fieldId, rowKey) {
569
+ const facts = fieldFactsOf(this.facts, fieldId, rowKey, this.compiled.schemaId);
570
+ const source = hostOptionSource(facts.field.optionSource, fieldId);
571
+ return (source.dependsOn ?? []).map((depId) => {
572
+ const dependency = this.facts.get(depId);
573
+ return dependency?.arrayContainerId !== undefined && rowKey !== undefined
574
+ ? { fieldId: depId, rowKey }
575
+ : { fieldId: depId };
576
+ });
577
+ }
578
+ /** One binding's current page list. */
579
+ optionState(fieldId, rowKey) {
580
+ return this.optionPages.stateOf(optionPageKey(fieldId, rowKey));
581
+ }
582
+ /** Registers a listener for every page-list change; the returned release is idempotent. */
583
+ subscribeOptionPages(listener) {
584
+ return this.optionPages.subscribe(listener);
585
+ }
586
+ /**
587
+ * Starts a load when the committed basis or the page size moved; a no-op while they hold.
588
+ *
589
+ * The effect's render signature is only its wake-up. Reading the basis at effect time avoids
590
+ * discarding the last committed change when no further render follows it.
591
+ */
592
+ ensureOptions(fieldId, rowKey, pageSize) {
593
+ this.optionPages.ensure(optionPageKey(fieldId, rowKey), this.optionBasis(fieldId, rowKey), pageSize);
594
+ }
595
+ /** The stable load-more and reload callbacks of one page list. */
596
+ optionControls(fieldId, rowKey) {
597
+ return this.optionPages.controls(optionPageKey(fieldId, rowKey));
598
+ }
599
+ /**
600
+ * Publishes the reader's search text for one host-loaded binding.
601
+ *
602
+ * The text reaches the page machine at the edit, so the pages that answered the previous
603
+ * query are dropped and its request aborted before the loader is asked for the new one. A
604
+ * binding the reader has not mounted has no pages, so it has nothing to narrow.
605
+ */
606
+ searchOptions(fieldId, rowKey, text) {
607
+ this.optionPages.search(optionPageKey(fieldId, rowKey), text);
608
+ }
609
+ /** Registers one mounted consumer of a page list; the release cancels when it was the last. */
610
+ retainOptions(fieldId, rowKey) {
611
+ return this.optionPages.retain(optionPageKey(fieldId, rowKey), fieldId, rowKey);
612
+ }
613
+ /** The layout chrome committed state renders, or the candidate's when it is current. */
614
+ layoutViews(candidate) {
615
+ const session = this.sessionFor(candidate);
616
+ const form = session.engine.getFormState();
617
+ if (this.layoutCache?.form === form)
618
+ return this.layoutCache.views;
619
+ const input = evaluationInputOf(session.inputs, session.engine.values(), session.engine.sessionWrites());
620
+ const views = layoutOf(this.compiled, input, session.inputs.env);
621
+ const previous = this.layoutCache?.views;
622
+ // An edit that moves no chrome keeps the array a `useLayout` consumer already rendered.
623
+ const chosen = previous !== undefined && sameLayoutViews(previous, views) ? previous : views;
624
+ this.layoutCache = { form, views: chosen };
625
+ return chosen;
626
+ }
627
+ /** One layout node's slice, by the node id the artifact states. */
628
+ layoutNode(candidate, nodeId) {
629
+ const node = findLayoutNode(this.layoutViews(candidate), nodeId);
630
+ if (node === undefined) {
631
+ throw new Error(`@azx-pbc/axiom-react: layout node ${JSON.stringify(nodeId)} is not declared by schema ${this.compiled.schemaId}`);
632
+ }
633
+ return this.layoutSliceOf(candidate, `node\u0000${nodeId}`, node);
634
+ }
635
+ /** One layout section's slice, by the anchor its `sectionId` states. */
636
+ layoutSection(candidate, sectionId) {
637
+ const node = findLayoutSection(this.layoutViews(candidate), sectionId);
638
+ if (node === undefined) {
639
+ throw new Error(`@azx-pbc/axiom-react: layout section ${JSON.stringify(sectionId)} is not declared by schema ${this.compiled.schemaId}`);
640
+ }
641
+ return this.layoutSliceOf(candidate, `section\u0000${sectionId}`, node);
642
+ }
643
+ /** One gate's state: the named one, or the artifact's primary gate when none is named. */
644
+ gateView(candidate, gateId) {
645
+ const named = gateId ?? this.compiled.primaryGateId;
646
+ if (named === undefined)
647
+ return undefined;
648
+ const form = this.sessionFor(candidate).engine.getFormState();
649
+ const next = gateViewOf(this.compiled, form, gateId);
650
+ if (next === undefined)
651
+ return undefined;
652
+ const previous = this.gateMemo.get(named);
653
+ if (previous !== undefined && sameGateView(previous, next))
654
+ return previous;
655
+ this.gateMemo.set(named, next);
656
+ return next;
657
+ }
658
+ /** Registers a listener for every publish that may move chrome; the release is idempotent. */
659
+ subscribeLayout(listener) {
660
+ this.layoutSubscriptions.add(listener);
661
+ return () => {
662
+ this.layoutSubscriptions.delete(listener);
663
+ };
664
+ }
665
+ /**
666
+ * Registers a listener for a move in the session-wide members of an option basis — the record
667
+ * date and the access version — so a mounted picker re-reads the basis it keys its pages by.
668
+ * A declared dependency's value is a binding of its own; a consumer subscribes to that.
669
+ */
670
+ subscribeOptionBasis(listener) {
671
+ this.basisSubscriptions.add(listener);
672
+ return () => {
673
+ this.basisSubscriptions.delete(listener);
674
+ };
675
+ }
676
+ arrayViewOf(session, fieldId) {
677
+ const facts = fieldFactsOf(this.facts, fieldId, undefined, this.compiled.schemaId);
678
+ if (facts.field.primitive !== 'array') {
679
+ throw new AxiomError('ENGINE_ERROR', `${JSON.stringify(fieldId)} holds no rows, so it has no array binding`, fieldId);
680
+ }
681
+ return this.arrays.read(session.candidate, session === this.session, session.engine, fieldId);
682
+ }
683
+ /**
684
+ * Applies one structural write, staging it when the host asked to confirm such a write.
685
+ *
686
+ * A staged structural write committed nothing, so the rows a refusal was about have not moved.
687
+ */
688
+ structural(operations) {
689
+ const written = this.writeThrough(operations);
690
+ if (written.outcome.outcome === 'refused')
691
+ throw writeRefusalError(written.outcome);
692
+ if (written.staged)
693
+ return;
694
+ this.structuralApplied();
695
+ }
696
+ /** Resolves a positional move, then previews the identity-addressed operation like every write. */
697
+ moveArray(fieldId, fromIndex, toIndex) {
698
+ const rowKey = this.session.engine.getField(fieldId).addressableRows?.[fromIndex];
699
+ if (rowKey === undefined) {
700
+ // Keep the engine's identity and index refusals exact for a position it cannot resolve.
701
+ this.structuralRun((engine) => engine.move(fieldId, fromIndex, toIndex, 'user'));
702
+ return;
703
+ }
704
+ this.structural([{ kind: 'move', fieldId, rowKey, toIndex, origin: 'user' }]);
705
+ }
706
+ /** Issues one structural write the engine expresses as a call rather than as an operation. */
707
+ structuralRun(run) {
708
+ const outcome = run(this.session.engine);
709
+ if (outcome.outcome === 'refused')
710
+ throw writeRefusalError(outcome);
711
+ this.structuralApplied();
712
+ }
713
+ structuralApplied() {
714
+ // The rows a refusal was about may have moved or gone, so every refusal is stale now.
715
+ this.view.clearRefusals();
716
+ this.snapshotChanged();
717
+ }
718
+ /**
719
+ * Replaces every row of one array through the container write the engine already owns.
720
+ *
721
+ * The container is where an array's whole value lives, so this is the one path that works for
722
+ * a natural-key array and an `assigned` one alike: the engine re-derives row identity from the
723
+ * new values (natural) or mints fresh ids through the host's factory (`assigned`). A row whose
724
+ * natural key survives the replace keeps its `RowRef`, and with it the failure the item rule
725
+ * decided about that key; a row the new list dropped retires, and a row it added starts fresh.
726
+ */
727
+ replaceArray(fieldId, values) {
728
+ const attempted = this.write({ fieldId }, 'value', [...values]);
729
+ // A staged write replaced nothing yet, so the rows a refusal was about have not moved.
730
+ if (attempted.staged === true)
731
+ return;
732
+ // A replaced list moved or removed the rows a refusal was about.
733
+ this.view.clearRefusals();
734
+ this.snapshotChanged();
735
+ }
736
+ /** One node's slice, reusing the previous object while every fact it states holds. */
737
+ layoutSliceOf(candidate, key, node) {
738
+ const session = this.sessionFor(candidate);
739
+ const form = session.engine.getFormState();
740
+ const next = layoutSliceOf(node, this.compiled, session.engine, form, this.facts, this.fieldsById(form));
741
+ const previous = this.sliceMemo.get(key);
742
+ if (previous !== undefined && sameLayoutSlice(previous, next))
743
+ return previous;
744
+ this.sliceMemo.set(key, next);
745
+ return next;
746
+ }
747
+ /**
748
+ * The declaration list indexed by field, shared by every slice one publish reads.
749
+ *
750
+ * Each slice needs the `FormState` entry for each field it places; indexing once per form
751
+ * keeps a host that reads many slices from paying one pass per slice.
752
+ */
753
+ fieldsById(form) {
754
+ const cached = this.fieldIndex;
755
+ if (cached !== undefined && cached.form === form)
756
+ return cached.byId;
757
+ const byId = fieldsByIdOf(form);
758
+ this.fieldIndex = { form, byId };
759
+ return byId;
760
+ }
761
+ /** The session a read answers from: the candidate while it is current, else committed state. */
762
+ sessionFor(candidate) {
763
+ return candidate === undefined || !this.isCurrentCandidate(candidate)
764
+ ? this.session
765
+ : this.sessionOf(candidate);
766
+ }
767
+ /**
768
+ * A loaded page changed: re-derive committed state with the new domain and publish it.
769
+ *
770
+ * Eligibility is the field's derived `invalidValue`, so the derivation is the only place
771
+ * that answers it — the hook never recomputes it and the engine stores no option state.
772
+ */
773
+ optionDomainChanged() {
774
+ const next = this.optionPages.domains();
775
+ if (next === this.optionDomains)
776
+ return;
777
+ this.optionDomains = next;
778
+ // A page list released during unmount changes the domain too; re-deriving a session nobody
779
+ // renders would only re-open the engine on the way out.
780
+ if (!this.mounted)
781
+ return;
782
+ // The loaded domain is a derivation input, like the record and the access answer: a page
783
+ // that arrived changes what eligibility can answer, and the next write must be judged by the
784
+ // domain the user can see. One pass per user-driven page is the price of that; skipping it
785
+ // left a value from a freshly loaded page reported `invalid-value`.
786
+ this.configure(this.hostOverrides);
787
+ this.publish();
788
+ }
789
+ /**
790
+ * Tells the option consumers when the record date or the access version moved.
791
+ *
792
+ * Those two members appear in every basis and no field binding carries them, so nothing else
793
+ * would wake a picker that keys on them. The comparison is against what the last publish
794
+ * delivered: a keystroke re-derives the record but moves neither, so it notifies nobody.
795
+ */
796
+ publishOptionBasis() {
797
+ const next = {
798
+ recordDate: this.session.inputs.env.recordDate,
799
+ accessVersion: this.session.engine.lastPass().accessVersion,
800
+ };
801
+ const previous = this.publishedBasis;
802
+ this.publishedBasis = next;
803
+ if (previous !== undefined &&
804
+ previous.recordDate === next.recordDate &&
805
+ previous.accessVersion === next.accessVersion) {
806
+ return;
807
+ }
808
+ for (const listener of [...this.basisSubscriptions])
809
+ listener();
810
+ }
811
+ /**
812
+ * The imperative handle: one identity-stable object that never subscribes, so a host can
813
+ * hold it across renders and call it from an event handler.
814
+ */
815
+ handle() {
816
+ if (this.formHandle !== undefined)
817
+ return this.formHandle;
818
+ // Every member is an arrow inside this method, so `this` is already the instance: an alias
819
+ // (`const store = this`) would say the same thing while reading as if scope were lost.
820
+ const handle = {
821
+ handleSubmit: (onValid, onInvalid) => this.submit(onValid, onInvalid),
822
+ submitHandler: (onValid, onInvalid) => () => this.submit(onValid, onInvalid),
823
+ reset: (values) => this.reset(values),
824
+ exportSubmission: (options) => this.exportSubmission(options),
825
+ getValues: () => this.session.engine.values(),
826
+ getField: (fieldId, rowKey) => this.session.engine.getField(fieldId, rowKey),
827
+ getState: () => this.getFormSummary(),
828
+ batch: (operations) => this.apply(operations),
829
+ setValue: (fieldId, value, rowKey) => {
830
+ const ref = bindingRef(fieldId, rowKey);
831
+ return this.apply([{ kind: 'value', ref, value, origin: 'user' }]);
832
+ },
833
+ setNull: (fieldId, rowKey) => {
834
+ const ref = bindingRef(fieldId, rowKey);
835
+ return this.apply([{ kind: 'null', ref, origin: 'user' }]);
836
+ },
837
+ removeValue: (fieldId, rowKey) => {
838
+ const ref = bindingRef(fieldId, rowKey);
839
+ return this.apply([{ kind: 'remove', ref, origin: 'user' }]);
840
+ },
841
+ propose: (operations) => this.propose(operations),
842
+ applyProposal: (proposal) => this.applyProposal(proposal),
843
+ discardProposal: (proposal) => {
844
+ this.discardProposal(proposal);
845
+ },
846
+ setContext: (root, value) => this.applyContext(root, value),
847
+ setEnv: (env) => this.applyEnv(env),
848
+ setAccess: (overlay) => this.applyAccess(overlay),
849
+ explainField: (fieldId, rowKey) => this.session.engine.explainField(fieldId, rowKey),
850
+ inspectFieldDeps: (fieldId) => this.session.engine.inspectFieldDeps(fieldId),
851
+ };
852
+ this.formHandle = handle;
853
+ return handle;
854
+ }
855
+ /** Whether a candidate is still the view the session is rendering from. */
856
+ isCurrentCandidate(candidate) {
857
+ return candidate === this.session.candidate || candidate === this.previewed;
858
+ }
859
+ /** Marks the store as mounted, so a settled submission may still publish. */
860
+ mount() {
861
+ this.mounted = true;
862
+ this.optionPages.mount();
863
+ }
864
+ /**
865
+ * Marks the store as unmounted: a settled submission publishes nothing, and every option
866
+ * request is cancelled so neither a resolve nor a reject writes afterwards.
867
+ */
868
+ unmount() {
869
+ this.mounted = false;
870
+ // A session that is gone has no confirmation left to answer, and a stored proposal would
871
+ // keep a candidate and its report alive for the lifetime of the object. Mark the retired
872
+ // candidate declined so a host still holding it from `onWriteProposed` cannot commit it
873
+ // after teardown.
874
+ if (this.pendingProposal !== undefined) {
875
+ this.declinedCandidates.add(this.pendingProposal.candidate);
876
+ }
877
+ this.retirePending();
878
+ this.optionPages.unmount();
879
+ }
880
+ applyContext(root, value) {
881
+ const outcome = this.session.engine.setContext(root, value);
882
+ if (outcome.outcome === 'committed') {
883
+ const name = root.replace(/^context\./, '');
884
+ const declaration = this.compiled.context?.roots.find((entry) => entry.path.replace(/^context\./, '') === name);
885
+ if (declaration === undefined) {
886
+ throw new AxiomError('ENGINE_ERROR', 'a committed context root has no declaration', name);
887
+ }
888
+ // The engine owns its committed copy; the input carried into a later re-open needs its own
889
+ // canonical copy too, or a caller mutating the original would change a future pass.
890
+ const stored = toWireValue(value, `$.context.${name}`, {
891
+ primitive: declaration.primitive,
892
+ ...(declaration.items === undefined ? {} : { items: declaration.items }),
893
+ });
894
+ const context = { ...this.session.inputs.context, [name]: stored };
895
+ this.imperativeContext = context;
896
+ this.session = { ...this.session, inputs: { ...this.session.inputs, context } };
897
+ // A committed session input moved the basis a staged write was derived from.
898
+ this.retirePending();
899
+ this.snapshotChanged();
900
+ }
901
+ return outcome;
902
+ }
903
+ applyEnv(env) {
904
+ const outcome = this.session.engine.setEnv(env);
905
+ if (outcome.outcome === 'committed') {
906
+ const installed = {
907
+ ...env,
908
+ ...(env.capabilities === undefined ? {} : { capabilities: [...env.capabilities] }),
909
+ };
910
+ this.imperativeEnv = installed;
911
+ this.session = { ...this.session, inputs: { ...this.session.inputs, env: installed } };
912
+ // A committed session input moved the basis a staged write was derived from.
913
+ this.retirePending();
914
+ this.snapshotChanged();
915
+ }
916
+ return outcome;
917
+ }
918
+ /**
919
+ * Installs the overlay as the session's access source.
920
+ *
921
+ * A provider that supplies `overlay` or `access` is the access authority, so the imperative
922
+ * call yields to it; with no access prop the overlay sticks across renders, because it is the
923
+ * session's own input from now on.
924
+ */
925
+ applyAccess(overlay) {
926
+ const previous = this.imperativeOverlay;
927
+ // The session owns the overlay it will replay on a later render, not the caller's mutable
928
+ // object. Parsing here also refuses an invalid imperative input even while a prop is in force.
929
+ this.imperativeOverlay = toAccessOverlay(overlay);
930
+ if (this.hostOverrides.overlay !== undefined || this.hostOverrides.access !== undefined) {
931
+ return;
932
+ }
933
+ let changed;
934
+ try {
935
+ changed = this.commit(this.preview(this.hostOverrides));
936
+ }
937
+ catch (error) {
938
+ // A refused overlay was never the session's input; do not let it poison the next render.
939
+ this.imperativeOverlay = previous;
940
+ throw error;
941
+ }
942
+ if (changed)
943
+ this.publish();
944
+ }
945
+ /**
946
+ * Applies one user write outside a render and publishes what it changed.
947
+ *
948
+ * A control and the handle reach it with the same engine operations, so the two entry points
949
+ * cannot disagree about provenance, the dirty and touched marks, or whether the session
950
+ * staged the write for confirmation instead of committing it.
951
+ */
952
+ apply(operations) {
953
+ const userWrote = operations.flatMap(userWriteRefs);
954
+ const before = this.valuesBefore(userWrote);
955
+ const written = this.writeThrough(operations);
956
+ // A staged write committed nothing: the provenance and the marks belong to the host's
957
+ // acceptance, so the attempt that asked for one records none of them.
958
+ if (written.staged || written.outcome.outcome === 'refused')
959
+ return written.outcome;
960
+ this.syncCommittedInputs(operations);
961
+ this.recordUserWrites(userWrote, before);
962
+ this.snapshotChanged();
963
+ return written.outcome;
964
+ }
965
+ /**
966
+ * Derives the state a change set would commit, and what applying it would move.
967
+ *
968
+ * Nothing is committed, no basis moves and no listener is notified: the answer is the engine's
969
+ * own proposal, so a host can show the effect before deciding.
970
+ */
971
+ propose(operations) {
972
+ const proposed = this.session.engine.propose(operations);
973
+ if (proposed.outcome === 'refused')
974
+ return proposed;
975
+ const { candidate } = proposed;
976
+ // The delta is the engine's lazy property, so a host that dry-runs a change set and reads
977
+ // only the blockers, the candidate or the operations seals neither report.
978
+ const proposal = Object.freeze({
979
+ outcome: 'proposed',
980
+ operations: candidate.operations,
981
+ candidate,
982
+ addedBlockers: proposed.addedBlockers,
983
+ get delta() {
984
+ return proposed.delta;
985
+ },
986
+ });
987
+ return proposal;
988
+ }
989
+ /** Commits the state one proposal derived, through the bookkeeping a keystroke performs. */
990
+ applyProposal(proposal) {
991
+ if (!this.mounted) {
992
+ return Object.freeze({
993
+ outcome: 'refused',
994
+ code: 'STALE_BASIS',
995
+ basis: proposal.candidate.basis,
996
+ });
997
+ }
998
+ if (!this.isLatestProposal(proposal)) {
999
+ return this.supersededRefusal(proposal);
1000
+ }
1001
+ // The candidate is the immutable operation source the engine commits. A host reconstructing
1002
+ // the public wrapper cannot make the store's bookkeeping describe a different change set.
1003
+ const operations = proposal.candidate.operations;
1004
+ const userWrote = this.proposalUserWrites.get(proposal.candidate) ?? operations.flatMap(userWriteRefs);
1005
+ const before = this.valuesBefore(userWrote);
1006
+ // The engine judges the candidate's session and basis, so a proposal derived before the
1007
+ // committed state moved is refused whole rather than applied over the newer state.
1008
+ const outcome = this.session.engine.commit(proposal.candidate);
1009
+ // The apply is the end of the confirmation, whether the engine took it or refused it: a
1010
+ // refused proposal is stale, and keeping it pending would offer a host an answer the record
1011
+ // can no longer take.
1012
+ if (this.isPending(proposal))
1013
+ this.retirePending();
1014
+ if (outcome.outcome === 'refused') {
1015
+ if (this.mounted)
1016
+ this.publishForm();
1017
+ return outcome;
1018
+ }
1019
+ // A candidate that moved an input moved it in the engine too; keep the store's own copy in
1020
+ // step so the next re-open replays the accepted input rather than the one it replaced.
1021
+ this.syncCommittedInputs(operations);
1022
+ this.recordUserWrites(userWrote, before);
1023
+ // A structural operation or whole-array value replace moves the rows a refusal was about.
1024
+ // The kind test is total over the operation union, so a new operation kind fails typecheck.
1025
+ if (operations.some((operation) => isStructuralOperation(operation, (fieldId) => this.facts.get(fieldId)?.field.primitive === 'array'))) {
1026
+ this.view.clearRefusals();
1027
+ }
1028
+ this.markChanged();
1029
+ if (this.mounted)
1030
+ this.publish();
1031
+ return outcome;
1032
+ }
1033
+ /**
1034
+ * Declines one proposal: nothing is written, and every control repaints its committed value.
1035
+ *
1036
+ * Declining is not a write, so no dirty or touched mark is recorded and the engine's basis is
1037
+ * untouched. The store still publishes, because a control may have painted the declined write
1038
+ * in its own state before the session answered it.
1039
+ */
1040
+ discardProposal(proposal) {
1041
+ // Declining the write the session is confirming ends the confirmation and marks the
1042
+ // candidate declined: the engine still holds the derived state, so only this marker keeps a
1043
+ // later `applyProposal` for the same proposal from committing the cancelled write. Declining
1044
+ // an older proposal writes nothing either, and leaves the newer one pending for its own
1045
+ // answer.
1046
+ if (this.isPending(proposal)) {
1047
+ this.declinedCandidates.add(proposal.candidate);
1048
+ this.retirePending();
1049
+ }
1050
+ // Nothing was written, so no fact moved: what the host declined is a paint. Forgetting the
1051
+ // written bindings' props makes each of their controls re-derive and render the committed
1052
+ // value, which is the value the record still holds.
1053
+ const repainted = new Set();
1054
+ const repaintValue = (ref) => {
1055
+ const key = bindingKey(ref.fieldId, ref.rowKey);
1056
+ if (repainted.has(key))
1057
+ return;
1058
+ repainted.add(key);
1059
+ this.snapshots.retire(key);
1060
+ // A value-only subscriber needs a new wrapper too: the committed value deliberately holds.
1061
+ this.watched.repaint(key);
1062
+ if (ref.rowKey === undefined && this.facts.get(ref.fieldId)?.field.primitive === 'array') {
1063
+ this.arrays.retireView(ref.fieldId);
1064
+ }
1065
+ };
1066
+ for (const operation of proposal.candidate.operations) {
1067
+ switch (operation.kind) {
1068
+ case 'value':
1069
+ case 'null':
1070
+ case 'remove':
1071
+ // Repaint every value target, including a host's system capture. Only provenance and
1072
+ // touched marks are restricted to user-origin operations; a decline has neither.
1073
+ repaintValue(operation.ref);
1074
+ continue;
1075
+ case 'append':
1076
+ case 'insert':
1077
+ case 'removeRow':
1078
+ case 'move':
1079
+ repaintValue({ fieldId: operation.fieldId });
1080
+ continue;
1081
+ case 'context':
1082
+ case 'env':
1083
+ case 'access':
1084
+ // A session input names no control, so a decline repaints nothing for it.
1085
+ continue;
1086
+ default:
1087
+ assertNever(operation);
1088
+ }
1089
+ }
1090
+ this.publish();
1091
+ }
1092
+ /**
1093
+ * Ends a confirmation, when one waits.
1094
+ *
1095
+ * The pending slot and the summary that stated it are one fact, so every path that makes the
1096
+ * staged write no longer answerable calls this rather than clearing the field: a cached summary
1097
+ * that survived would keep offering an Accept the session would refuse.
1098
+ */
1099
+ retirePending() {
1100
+ if (this.pendingProposal === undefined)
1101
+ return;
1102
+ this.pendingProposal = undefined;
1103
+ this.summary = undefined;
1104
+ }
1105
+ /**
1106
+ * Whether a proposal is the one the session is currently prepared to commit.
1107
+ *
1108
+ * A staged proposal carries the sequence that says so, and a candidate the host declined is
1109
+ * refused even though the engine still holds its derived state. A proposal from the `propose`
1110
+ * door has no sequence: it is committable while no staged write is pending, and once one is it
1111
+ * is the second write door the single pending proposal exists to prevent. Declining a proposal
1112
+ * that was never staged therefore never marks it declined: that door asked for a dry run, not
1113
+ * for a confirmation, and a bare discard leaves its result committable.
1114
+ */
1115
+ isLatestProposal(proposal) {
1116
+ if (this.declinedCandidates.has(proposal.candidate))
1117
+ return false;
1118
+ const sequence = sequenceOf(proposal);
1119
+ if (sequence !== undefined)
1120
+ return sequence === this.nextProposalSequence;
1121
+ return this.pendingProposal === undefined;
1122
+ }
1123
+ /** Whether the pending proposal is this one, by identity or by the sequence it carries. */
1124
+ isPending(proposal) {
1125
+ const pending = this.pendingProposal;
1126
+ if (pending === undefined)
1127
+ return false;
1128
+ if (proposal.candidate === pending.candidate)
1129
+ return true;
1130
+ const sequence = sequenceOf(proposal);
1131
+ return sequence !== undefined && sequence === pending.sequence;
1132
+ }
1133
+ /** The refusal a superseded proposal earns, naming the order the session holds. */
1134
+ supersededRefusal(proposal) {
1135
+ const sequence = sequenceOf(proposal);
1136
+ // Only a proposal that is actually pending is a newer answer to name. Once the confirmation
1137
+ // was applied or declined, a late proposal is refused without claiming another write waits.
1138
+ const latest = this.pendingProposal?.sequence;
1139
+ return {
1140
+ outcome: 'refused',
1141
+ code: 'PROPOSAL_SUPERSEDED',
1142
+ ...(sequence === undefined ? {} : { sequence }),
1143
+ ...(latest === undefined ? {} : { latest }),
1144
+ };
1145
+ }
1146
+ /**
1147
+ * Keeps the store's own evaluation inputs in step with a commit that changed them.
1148
+ *
1149
+ * The engine owns the committed context, environment and overlay, but a later render re-opens
1150
+ * it from the store's copies when the host's props state an input anew. Without this, an
1151
+ * accepted `context`, `env` or `access` operation would be replayed from the value it replaced
1152
+ * on the next re-open. `handle.batch` and `applyProposal` both reach it, so the two doors
1153
+ * cannot disagree about what the session is now evaluating with.
1154
+ */
1155
+ syncCommittedInputs(operations) {
1156
+ let context = this.session.inputs.context;
1157
+ let env = this.session.inputs.env;
1158
+ let overlay = this.session.inputs.overlay;
1159
+ let access = this.session.inputs.access;
1160
+ let touched = false;
1161
+ for (const operation of operations) {
1162
+ switch (operation.kind) {
1163
+ case 'context': {
1164
+ const name = operation.root.replace(/^context\./, '');
1165
+ const declaration = this.compiled.context?.roots.find((entry) => entry.path.replace(/^context\./, '') === name);
1166
+ // The engine refused an undeclared root, so the batch never committed and this walk
1167
+ // never runs. Skipping here keeps that refusal the only answer.
1168
+ if (declaration === undefined)
1169
+ continue;
1170
+ const stored = toWireValue(operation.value, `$.context.${name}`, {
1171
+ primitive: declaration.primitive,
1172
+ ...(declaration.items === undefined ? {} : { items: declaration.items }),
1173
+ });
1174
+ context = { ...(context ?? {}), [name]: stored };
1175
+ touched = true;
1176
+ continue;
1177
+ }
1178
+ case 'env': {
1179
+ const installed = {
1180
+ ...operation.env,
1181
+ ...(operation.env.capabilities === undefined
1182
+ ? {}
1183
+ : { capabilities: [...operation.env.capabilities] }),
1184
+ };
1185
+ env = installed;
1186
+ touched = true;
1187
+ continue;
1188
+ }
1189
+ case 'access': {
1190
+ // The engine owns the version and advances it once per access operation; the
1191
+ // committed answer is the one a re-open must replay.
1192
+ overlay = {
1193
+ ...toAccessOverlay(operation.overlay),
1194
+ accessVersion: this.session.engine.lastPass().accessVersion,
1195
+ };
1196
+ // A session resolves one access source, so an accepted overlay replaces the flattened
1197
+ // projection rather than leaving two answers for the same reference.
1198
+ access = undefined;
1199
+ touched = true;
1200
+ continue;
1201
+ }
1202
+ case 'value':
1203
+ case 'null':
1204
+ case 'remove':
1205
+ case 'append':
1206
+ case 'insert':
1207
+ case 'removeRow':
1208
+ case 'move':
1209
+ continue;
1210
+ default:
1211
+ assertNever(operation);
1212
+ }
1213
+ }
1214
+ if (!touched)
1215
+ return;
1216
+ // The engine refused no operation, so each declared input applied as the engine took it.
1217
+ this.imperativeContext = context;
1218
+ this.imperativeEnv = env;
1219
+ this.imperativeOverlay = overlay;
1220
+ this.session = {
1221
+ ...this.session,
1222
+ inputs: { ...this.session.inputs, context, env, overlay, access },
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Commits one user write, or stages it when the host asked to confirm a suggestion-bearing one.
1227
+ *
1228
+ * With no interceptor installed the operations reach the engine exactly as they always did. With
1229
+ * one, the write is previewed first: a change set that adds a blocker offering alternatives is
1230
+ * staged and reported instead of committed, and one that adds none commits the very state the
1231
+ * preview derived, so the previewed report, manifest and row keys are the committed ones.
1232
+ */
1233
+ writeThrough(operations, userWrote) {
1234
+ const intercept = this.writeInterceptor;
1235
+ if (intercept === undefined) {
1236
+ const outcome = this.session.engine.batch(operations);
1237
+ if (outcome.outcome === 'committed')
1238
+ this.retirePending();
1239
+ return { outcome, staged: false };
1240
+ }
1241
+ const binding = editedBinding(operations);
1242
+ if (binding === undefined) {
1243
+ const outcome = this.session.engine.batch(operations);
1244
+ if (outcome.outcome === 'committed')
1245
+ this.retirePending();
1246
+ return { outcome, staged: false };
1247
+ }
1248
+ const proposed = this.session.engine.propose(operations);
1249
+ if (proposed.outcome === 'refused')
1250
+ return { outcome: proposed, staged: false };
1251
+ if (!proposed.addedBlockers.some(offersAlternatives)) {
1252
+ const outcome = this.session.engine.commit(proposed.candidate);
1253
+ // A narrower write the host did not ask about still moves committed state, so a proposal
1254
+ // the user was confirming is no longer the write it confirmed.
1255
+ if (outcome.outcome === 'committed')
1256
+ this.retirePending();
1257
+ return { outcome, staged: false };
1258
+ }
1259
+ const candidateBinding = editedBinding(proposed.candidate.operations);
1260
+ if (candidateBinding === undefined) {
1261
+ throw new Error('a staged candidate always names its user-written binding');
1262
+ }
1263
+ this.nextProposalSequence += 1;
1264
+ // The whole delta, and both report digests inside it, are built when a host reads it. A
1265
+ // staged write a host confirms without inspecting seals neither report, so `delta` is the
1266
+ // engine's lazy property rather than a value this object computes eagerly.
1267
+ const proposal = Object.freeze({
1268
+ outcome: 'proposed',
1269
+ operations: proposed.candidate.operations,
1270
+ candidate: proposed.candidate,
1271
+ addedBlockers: proposed.addedBlockers,
1272
+ get delta() {
1273
+ return proposed.delta;
1274
+ },
1275
+ // Read the candidate's owned, frozen ref rather than aliasing the caller's input object.
1276
+ binding: candidateBinding,
1277
+ sequence: this.nextProposalSequence,
1278
+ });
1279
+ // Ordinary operations use the candidate's owned refs. The optional high-level write is a
1280
+ // store-private control ref, used when assigned-row operations erase the container spelling.
1281
+ this.proposalUserWrites.set(proposed.candidate, userWrote ?? proposed.candidate.operations.flatMap(userWriteRefs));
1282
+ // One proposal is pending at a time: the newer write replaces the one it supersedes, and the
1283
+ // summary states the replacement so a host repaints the confirmation it is now answering.
1284
+ this.pendingProposal = proposal;
1285
+ this.publishForm();
1286
+ intercept(proposal);
1287
+ return STAGED;
1288
+ }
1289
+ /** One binding's value before a write, so the write can tell whether the value moved. */
1290
+ valuesBefore(refs) {
1291
+ return refs.map((ref) => {
1292
+ try {
1293
+ return this.session.engine.getField(ref.fieldId, ref.rowKey).value;
1294
+ }
1295
+ catch {
1296
+ // A reference the engine will refuse is not a binding it can answer for; the write's own
1297
+ // refusal is that answer, not this capture's.
1298
+ return undefined;
1299
+ }
1300
+ });
1301
+ }
1302
+ /**
1303
+ * Records what a committed user write changed: the session's provenance, the dirty comparison,
1304
+ * the visit a deliberate write is, and the refusal the write answers.
1305
+ */
1306
+ recordUserWrites(userWrote, before) {
1307
+ for (const [index, ref] of userWrote.entries()) {
1308
+ const key = bindingKey(ref.fieldId, ref.rowKey);
1309
+ this.userWrites.add(key);
1310
+ // A write through `handle.setValue` is a write to the same binding a control writes, so
1311
+ // it marks the same visit: the two entry points must not disagree about whether an
1312
+ // identical write was an edit. One write, one answer.
1313
+ this.view.markChanged(key, ref);
1314
+ // Touched means the value *moved*. A write that commits the value already held is still
1315
+ // a change of provenance (the session now owns it), but it is not a visit the reveal
1316
+ // policy may treat as the user having answered anything.
1317
+ const previous = before[index];
1318
+ const next = valueAfter(this.session.engine, ref);
1319
+ if (previous !== undefined && next !== undefined && !sameValueState(previous, next)) {
1320
+ this.view.markEdited(key, ref);
1321
+ }
1322
+ // A successful write to the binding answers the entry the session refused, whether the
1323
+ // control or the handle issued it: the record now holds the value that replaced it, so
1324
+ // the control must not keep announcing the entry that did not.
1325
+ this.view.clearRefused(key);
1326
+ }
1327
+ }
1328
+ submit(onValid, onInvalid) {
1329
+ if (this.inFlight !== null)
1330
+ return this.inFlight;
1331
+ const run = this.runSubmit(onValid, onInvalid);
1332
+ this.inFlight = run;
1333
+ const clear = () => {
1334
+ if (this.inFlight === run)
1335
+ this.inFlight = null;
1336
+ };
1337
+ void run.then(clear, clear);
1338
+ return run;
1339
+ }
1340
+ async runSubmit(onValid, onInvalid) {
1341
+ this.submitCount += 1;
1342
+ this.isSubmitting = true;
1343
+ // RHF's `isSubmitSuccessful` answers the *last* attempt: a new attempt clears it before it
1344
+ // has decided, so a control that renders it cannot show the previous success beside this
1345
+ // attempt's failure.
1346
+ this.submitSucceeded = false;
1347
+ // The one time a deferred check is genuinely in flight: the submission may settle it.
1348
+ this.view.setSubmitting(true);
1349
+ this.snapshotEpoch += 1;
1350
+ try {
1351
+ const summary = this.summaryOf(this.session);
1352
+ // The one verdict, not `ready`: readiness is an input to it, and a gate's own `open`
1353
+ // badge is presentation. `SUBMIT` here still only proposes; the server re-derives.
1354
+ if (summary.verdict !== 'SUBMIT') {
1355
+ // Only the bindings that actually stop the submission are marked touched: a control
1356
+ // the user never visited must not be revealed as failed by someone else's submit.
1357
+ this.view.markTouchedAll(this.failingBindings());
1358
+ this.snapshotChanged();
1359
+ onInvalid?.(summary.errors, summary.blockers);
1360
+ return;
1361
+ }
1362
+ this.publish();
1363
+ // The body is the principal's answers only: a non-writable binding is the server's record,
1364
+ // so the accept door refuses it rather than treating the device's echo as a user write.
1365
+ await onValid(this.exportSubmission({ writableOnly: true }));
1366
+ // Reached only when the projection was exported and the host's handler returned: a
1367
+ // signature-covered refusal or a throwing handler is not a success, and the `finally`
1368
+ // below still clears `isSubmitting`.
1369
+ this.submitSucceeded = true;
1370
+ this.snapshotEpoch += 1;
1371
+ }
1372
+ finally {
1373
+ this.isSubmitting = false;
1374
+ this.view.setSubmitting(false);
1375
+ this.snapshotEpoch += 1;
1376
+ if (this.mounted)
1377
+ this.publish();
1378
+ }
1379
+ }
1380
+ /**
1381
+ * Every array field's addressable rows, as row-key tokens, memoised by the committed form
1382
+ * object. A pass that changed nothing keeps the form identity, so a keystroke's publish reuses
1383
+ * the index it built for the previous one.
1384
+ */
1385
+ addressableRows() {
1386
+ const form = this.session.engine.getFormState();
1387
+ if (this.rowIndex?.form === form)
1388
+ return this.rowIndex.rows;
1389
+ const rows = new Map();
1390
+ for (const field of form.fields) {
1391
+ if (field.addressableRows === undefined)
1392
+ continue;
1393
+ rows.set(field.fieldId, new Set(field.addressableRows.map((key) => rowKeyToken(key))));
1394
+ }
1395
+ this.rowIndex = { form, rows };
1396
+ return rows;
1397
+ }
1398
+ /**
1399
+ * Whether committed state still addresses one binding, so a derivation of it can answer.
1400
+ *
1401
+ * `reachable` is a supplier because a publish with no row-keyed subscriber must not pay for
1402
+ * the index at all; it is called only for a binding that names a row.
1403
+ */
1404
+ addresses(ref, reachable) {
1405
+ if (ref.rowKey === undefined)
1406
+ return true;
1407
+ // A member of an array is addressed by the container's rows: the member's own state
1408
+ // carries no row list, because the array holds it.
1409
+ const containerId = this.facts.get(ref.fieldId)?.arrayContainerId ?? ref.fieldId;
1410
+ return reachable().get(containerId)?.has(rowKeyToken(ref.rowKey)) ?? false;
1411
+ }
1412
+ /**
1413
+ * Drops the per-binding caches of a row committed state no longer addresses.
1414
+ *
1415
+ * The registration is deliberately left in place (see `publish`); the caches are not, because
1416
+ * a removed row's `FieldProps` holds its value and nothing would read them again. A row that
1417
+ * comes back re-derives, and derives into a session that no longer remembers the old object.
1418
+ * The user-write provenance goes too: the engine drops that row's write in the same commit, so
1419
+ * keeping the key would only grow the set until a reopen happened to prune it.
1420
+ */
1421
+ retireBinding(key, ref) {
1422
+ this.snapshots.retire(key);
1423
+ this.watched.retire(key);
1424
+ this.writers.retire(key);
1425
+ this.attemptWriters.delete(key);
1426
+ this.announceMemo.delete(key);
1427
+ this.view.retire(key);
1428
+ this.visibilityMemo.delete(key);
1429
+ this.arrays.retireRow(ref.fieldId, ref.rowKey);
1430
+ this.userWrites.delete(key);
1431
+ }
1432
+ /**
1433
+ * The binding keys a failed submit names: a blocking error or an unsatisfied requirement.
1434
+ *
1435
+ * The answer is read from the engine's committed state rather than from derived props,
1436
+ * deliberately: `propsOf` primes the published-snapshot cache, and a binding whose props a
1437
+ * submit had just changed would then look unchanged to the `publish` that follows, so a
1438
+ * control the user had already visited never heard that its failure was now revealed.
1439
+ */
1440
+ failingBindings() {
1441
+ const refs = new Map();
1442
+ const consider = (fieldId, rowKey) => {
1443
+ const state = this.session.engine.getField(fieldId, rowKey);
1444
+ if (state.visible && bindingErrors(state).invalid) {
1445
+ refs.set(bindingKey(fieldId, rowKey), bindingRef(fieldId, rowKey));
1446
+ }
1447
+ };
1448
+ for (const field of this.session.engine.getFormState().fields) {
1449
+ const itemMember = this.facts.get(field.fieldId)?.arrayContainerId !== undefined;
1450
+ if (!itemMember)
1451
+ consider(field.fieldId, undefined);
1452
+ for (const row of field.rows ?? [])
1453
+ consider(field.fieldId, row.rowKey);
1454
+ }
1455
+ return [...refs.values()];
1456
+ }
1457
+ /**
1458
+ * One binding's engine state, with the refusal kept for a key the store never registered.
1459
+ *
1460
+ * A binding the store keeps registered after its row left is read through the absent arm: a
1461
+ * mounted control must be able to render between the row leaving and the control unmounting,
1462
+ * and the read is not the place to refuse what the record did. A key no control ever registered
1463
+ * is a different answer: nothing in the session addresses it, so `getField` refuses it, and a
1464
+ * test or a host learns it typed the wrong key instead of reading a silent empty binding.
1465
+ */
1466
+ engineStateOf(session, fieldId, rowKey) {
1467
+ const dormant = rowKey !== undefined && this.subscriptions.count(bindingRef(fieldId, rowKey)) > 0;
1468
+ return dormant
1469
+ ? session.engine.getFieldOrAbsent(fieldId, rowKey)
1470
+ : session.engine.getField(fieldId, rowKey);
1471
+ }
1472
+ propsOf(session, fieldId, rowKey) {
1473
+ const facts = fieldFactsOf(this.facts, fieldId, rowKey, this.compiled.schemaId);
1474
+ const key = bindingKey(fieldId, rowKey);
1475
+ const state = this.engineStateOf(session, fieldId, rowKey);
1476
+ const base = this.snapshotOf(session, key, facts, state, fieldId, rowKey);
1477
+ return this.publishedProps(key, base, fieldId, rowKey);
1478
+ }
1479
+ /**
1480
+ * The snapshot-layer props of one binding, identity-stable while its published state holds.
1481
+ *
1482
+ * `publish` compares these — never the published extension, which is a different object by
1483
+ * construction — so a publish that moved no fact notifies nobody.
1484
+ */
1485
+ snapshotOf(session, key, facts, state, fieldId, rowKey) {
1486
+ const view = this.view.viewFor(key, this.submitCount > 0);
1487
+ const visibility = this.visibilityOf(session.engine, state, fieldId, rowKey, view.revealed);
1488
+ return this.snapshots.read(session.candidate, session === this.session, key, state, view, session.display, visibility, () => ({
1489
+ descriptor: facts.field,
1490
+ bindingKey: key,
1491
+ writers: this.writersOf(fieldId, rowKey),
1492
+ }));
1493
+ }
1494
+ /**
1495
+ * The props a control renders: the snapshot plus the members the derivation layer does not
1496
+ * own.
1497
+ *
1498
+ * The snapshot keeps its identity while a binding's published state holds, so the extended
1499
+ * object is cached against it: the same snapshot always publishes the same props, and a new
1500
+ * snapshot publishes once. The non-throwing writers come from the store's own stable cache.
1501
+ */
1502
+ publishedProps(key, base, fieldId, rowKey) {
1503
+ const cached = this.publishedPropsMemo.get(base);
1504
+ if (cached !== undefined)
1505
+ return cached;
1506
+ const writers = this.tryWritersOf(fieldId, rowKey);
1507
+ const published = Object.freeze({
1508
+ ...base,
1509
+ announce: this.announceFor(key, base.showError, base.visibleErrors),
1510
+ trySetValue: writers.trySetValue,
1511
+ trySetNull: writers.trySetNull,
1512
+ tryRemoveValue: writers.tryRemoveValue,
1513
+ });
1514
+ this.publishedPropsMemo.set(base, published);
1515
+ return published;
1516
+ }
1517
+ /**
1518
+ * The failures a control renders now, reused while the same failures hold.
1519
+ *
1520
+ * The list is `visibleErrors` once the control shows a failure, and the painted warnings
1521
+ * alone before that. Identity follows content rather than the snapshot: an edit that moves
1522
+ * no failure keeps the array the control already rendered.
1523
+ */
1524
+ announceFor(key, showError, visibleErrors) {
1525
+ const next = showError
1526
+ ? visibleErrors
1527
+ : Object.freeze(visibleErrors.filter(isPaintedWarning));
1528
+ const previous = this.announceMemo.get(key);
1529
+ if (previous !== undefined && sameFieldErrors(previous, next))
1530
+ return previous;
1531
+ this.announceMemo.set(key, next);
1532
+ return next;
1533
+ }
1534
+ valueStateOf(session, fieldId, rowKey) {
1535
+ fieldFactsOf(this.facts, fieldId, rowKey, this.compiled.schemaId);
1536
+ return this.watched.read(session.candidate, session === this.session, bindingKey(fieldId, rowKey), this.engineStateOf(session, fieldId, rowKey).value);
1537
+ }
1538
+ writersOf(fieldId, rowKey) {
1539
+ const key = bindingKey(fieldId, rowKey);
1540
+ const writers = this.writers.for(key, () => {
1541
+ const ref = bindingRef(fieldId, rowKey);
1542
+ return {
1543
+ // A control's writers answer nothing: whether the session staged the write is the
1544
+ // handle's and the host's question, never a control's.
1545
+ setValue: (value) => {
1546
+ this.write(ref, 'value', value);
1547
+ },
1548
+ setNull: () => {
1549
+ this.write(ref, 'null');
1550
+ },
1551
+ removeValue: () => {
1552
+ this.write(ref, 'remove');
1553
+ },
1554
+ onBlur: () => this.blur(fieldId, rowKey),
1555
+ };
1556
+ });
1557
+ if (!this.attemptWriters.has(key)) {
1558
+ const ref = bindingRef(fieldId, rowKey);
1559
+ this.attemptWriters.set(key, {
1560
+ trySetValue: (value) => this.attemptWrite(ref, 'value', value).outcome,
1561
+ trySetNull: () => this.attemptWrite(ref, 'null').outcome,
1562
+ tryRemoveValue: () => this.attemptWrite(ref, 'remove').outcome,
1563
+ });
1564
+ }
1565
+ return writers;
1566
+ }
1567
+ /** The stable non-throwing write callbacks for one binding; built beside `writersOf`. */
1568
+ tryWritersOf(fieldId, rowKey) {
1569
+ this.writersOf(fieldId, rowKey);
1570
+ const writers = this.attemptWriters.get(bindingKey(fieldId, rowKey));
1571
+ if (writers === undefined)
1572
+ throw new Error('a binding always has attempt writers');
1573
+ return writers;
1574
+ }
1575
+ /**
1576
+ * Writes one value as the user, refusing by throwing.
1577
+ *
1578
+ * The attempt is judged the same way `attemptWrite` judges it; a refusal the record never
1579
+ * took is raised as the runtime's structured write error, except for a duplicate row key,
1580
+ * which the attempt already announced beside its control and published.
1581
+ */
1582
+ write(ref, kind, value) {
1583
+ const attempted = this.attemptWrite(ref, kind, value);
1584
+ if (attempted.outcome.outcome === 'refused') {
1585
+ // The record never took the refused entry, so it is still valid; what failed is the value
1586
+ // the user just typed, which the attempt already announced and published.
1587
+ if (attempted.outcome.code === 'ROW_KEY_DUPLICATE')
1588
+ return attempted;
1589
+ throw writeRefusalError(attempted.outcome, attempted.cause);
1590
+ }
1591
+ return attempted;
1592
+ }
1593
+ /**
1594
+ * Writes one value as the user, returning the refusal instead of throwing it.
1595
+ *
1596
+ * The guard runs before the value is parsed, so a write the rendered state does not permit
1597
+ * is refused with its own code rather than by whatever the value happens to be. The value is
1598
+ * then parsed against its declaration before the engine sees it, so a control is refused with
1599
+ * the same `INVALID_VALUE` code the session handle reports, and the boundary diagnostic rides
1600
+ * along as the attempt's cause. The engine then judges the write with its own guard, the same
1601
+ * derivation the control rendered.
1602
+ */
1603
+ attemptWrite(ref, kind, value) {
1604
+ const facts = fieldFactsOf(this.facts, ref.fieldId, ref.rowKey, this.compiled.schemaId);
1605
+ const engine = this.session.engine;
1606
+ const state = engine.getField(ref.fieldId, ref.rowKey);
1607
+ const refusal = checkWrite({
1608
+ ref,
1609
+ origin: 'user',
1610
+ access: state.access,
1611
+ enabled: state.enabled,
1612
+ primitive: facts.field.primitive,
1613
+ item: facts.arrayContainerId !== undefined || ref.rowKey !== undefined,
1614
+ changed: true,
1615
+ });
1616
+ if (refusal !== undefined) {
1617
+ // The guard refusal carries the reference the write named; the handle reports the same
1618
+ // shape, so the control's non-throwing door and the session agree code for code.
1619
+ return {
1620
+ outcome: {
1621
+ outcome: 'refused',
1622
+ code: refusal.code,
1623
+ origin: refusal.origin,
1624
+ fieldId: refusal.fieldId,
1625
+ ...(refusal.rowKey === undefined ? {} : { rowKey: refusal.rowKey }),
1626
+ },
1627
+ };
1628
+ }
1629
+ const assigned = ref.rowKey === undefined &&
1630
+ facts.field.primitive === 'array' &&
1631
+ facts.field.rowKey?.mode === 'assigned';
1632
+ if (kind === 'value') {
1633
+ let parsed;
1634
+ try {
1635
+ parsed = toWireValue(value, `$.values.${ref.fieldId}`, declarationFor(facts, ref.rowKey));
1636
+ }
1637
+ catch (error) {
1638
+ if (!(error instanceof AxiomError))
1639
+ throw error;
1640
+ return {
1641
+ outcome: {
1642
+ outcome: 'refused',
1643
+ code: 'INVALID_VALUE',
1644
+ origin: 'user',
1645
+ fieldId: ref.fieldId,
1646
+ ...(ref.rowKey === undefined ? {} : { rowKey: ref.rowKey }),
1647
+ },
1648
+ cause: error,
1649
+ };
1650
+ }
1651
+ if (assigned) {
1652
+ // An assigned array's rows carry ids no positional replacement can invent, so a container
1653
+ // that changes the row count is expressed with the structural operations that mint them.
1654
+ return this.attemptWriteAssignedArray(facts.field.fieldId, parsed, ref, state);
1655
+ }
1656
+ return this.finishAttempt(ref, state, this.writeThrough([{ kind: 'value', ref, value: parsed, origin: 'user' }]));
1657
+ }
1658
+ if (assigned) {
1659
+ return this.attemptWriteAssignedArray(facts.field.fieldId, kind === 'null' ? null : undefined, ref, state);
1660
+ }
1661
+ return this.finishAttempt(ref, state, this.writeThrough([{ kind: kind === 'null' ? 'null' : 'remove', ref, origin: 'user' }]));
1662
+ }
1663
+ /**
1664
+ * Settles one engine verdict for a scalar write.
1665
+ *
1666
+ * A duplicate row key is announced beside its control and published, because the record never
1667
+ * took the entry and the control must name the entry that failed. Any other refusal is
1668
+ * returned for the caller: the throwing door raises it, the non-throwing door hands it back.
1669
+ * A commit records the provenance the engine cannot state — this binding holds a value the
1670
+ * user typed — and clears the refusal the write answered.
1671
+ */
1672
+ finishAttempt(ref, state, written) {
1673
+ const { outcome } = written;
1674
+ if (outcome.outcome === 'refused') {
1675
+ if (outcome.code === 'ROW_KEY_DUPLICATE') {
1676
+ // The record never took the entry, so it is still valid; what failed is the value the
1677
+ // user just typed. The control announces that beside itself instead of making React
1678
+ // unwind an event handler with an engine error it cannot render.
1679
+ const duplicate = outcome.rowKey ?? ref.rowKey ?? '';
1680
+ // A row-member binding has no `rowAddressing` of its own; read the enclosing array's mode
1681
+ // so natural/value duplicate keys carry `rowName` while assigned keys stay unnamed.
1682
+ const containerId = this.facts.get(ref.fieldId)?.arrayContainerId ?? ref.fieldId;
1683
+ const addressing = this.session.engine.getField(containerId).rowAddressing;
1684
+ const rowName = addressing === 'natural' || addressing === 'value' ? String(duplicate) : undefined;
1685
+ this.view.markRefused(bindingKey(ref.fieldId, ref.rowKey), {
1686
+ kind: 'row-key',
1687
+ blocking: false,
1688
+ status: 'FAIL',
1689
+ code: 'ROW_KEY_DUPLICATE',
1690
+ rowKey: duplicate,
1691
+ ...(rowName === undefined ? {} : { rowName }),
1692
+ });
1693
+ this.snapshotEpoch += 1;
1694
+ this.publish();
1695
+ }
1696
+ return { outcome };
1697
+ }
1698
+ // A staged write is the host's to accept: the record has not taken it, so it is neither a
1699
+ // dirty mark nor a visit the user has made.
1700
+ if (written.staged)
1701
+ return { outcome, staged: true };
1702
+ this.recordUserWrites([ref], [state.value]);
1703
+ this.snapshotChanged();
1704
+ return { outcome };
1705
+ }
1706
+ /**
1707
+ * Replaces one assigned array through the structural operations that own its row identity,
1708
+ * returning the refusal instead of throwing it.
1709
+ *
1710
+ * A value that is neither an array nor `null` reached past the declaration parse, so it is
1711
+ * still a programmer error and throws.
1712
+ */
1713
+ attemptWriteAssignedArray(fieldId, value, ref, state) {
1714
+ const current = this.session.engine.getField(fieldId).addressableRows ?? [];
1715
+ const removed = current.map((rowKey) => ({ kind: 'removeRow', fieldId, rowKey, origin: 'user' }));
1716
+ let written;
1717
+ if (value === undefined || value === null) {
1718
+ // Removing the rows first retires their manifest. The final operation then preserves the
1719
+ // distinction the wire contract makes between an authored null and an absent container.
1720
+ written = this.writeThrough([
1721
+ ...removed,
1722
+ value === null
1723
+ ? { kind: 'null', ref: { fieldId }, origin: 'user' }
1724
+ : { kind: 'remove', ref: { fieldId }, origin: 'user' },
1725
+ ], [ref]);
1726
+ }
1727
+ else {
1728
+ // The wire declaration of an array admits an array or `null`, so anything else is a caller
1729
+ // that bypassed the parse rather than a value the session can hold.
1730
+ const values = Array.isArray(value) ? value : undefined;
1731
+ if (values === undefined) {
1732
+ throw new AxiomError('ENGINE_ERROR', 'an array field holds an array or null', fieldId);
1733
+ }
1734
+ written =
1735
+ values.length === current.length
1736
+ ? this.writeThrough([{ kind: 'value', ref: { fieldId }, value, origin: 'user' }], [ref])
1737
+ : this.writeThrough([
1738
+ ...removed,
1739
+ ...values.map((item) => ({ kind: 'append', fieldId, value: item, origin: 'user' })),
1740
+ ], [ref]);
1741
+ }
1742
+ if (written.staged)
1743
+ return { outcome: written.outcome, staged: true };
1744
+ if (written.outcome.outcome === 'refused')
1745
+ return { outcome: written.outcome };
1746
+ this.recordUserWrites([ref], [state.value]);
1747
+ this.view.clearRefusals();
1748
+ this.snapshotChanged();
1749
+ return { outcome: written.outcome };
1750
+ }
1751
+ /** Records a blur on a binding the user could actually use, and publishes it. */
1752
+ blur(fieldId, rowKey) {
1753
+ const state = this.session.engine.getField(fieldId, rowKey);
1754
+ // A control the user could not use was never visited: marking it touched would reveal a
1755
+ // failure on a binding that cannot be corrected. `fillable` is the runtime's one answer for
1756
+ // that — visibility, access, the enabled rules, and the facts that stop a user write before
1757
+ // any of them (a writer owns the value, or it is a `signature_ref`). `enabled` alone is not
1758
+ // it: a `read_write` computed field is enabled and never writable.
1759
+ if (!state.fillable)
1760
+ return;
1761
+ this.view.markTouched(bindingKey(fieldId, rowKey), bindingRef(fieldId, rowKey));
1762
+ this.snapshotEpoch += 1;
1763
+ this.publish();
1764
+ }
1765
+ /**
1766
+ * One binding's visibility answer, structurally shared while the facts it states hold.
1767
+ *
1768
+ * The incomplete-rule set is derived from the current state of every field the binding's rules
1769
+ * read, so a write to a sibling can change it without replacing this binding's engine state.
1770
+ * The memo therefore compares the sets by value and reuses the previous object, which keeps a
1771
+ * publish from re-deriving props whose painted answer did not move.
1772
+ */
1773
+ visibilityOf(engine, state, fieldId, rowKey, revealedErrors) {
1774
+ const key = bindingKey(fieldId, rowKey);
1775
+ const incompleteRules = incompleteRulesOf(engine, this.facts, this.ruleReads, state, rowKey, (answeredKey) => this.view.isAnswered(answeredKey));
1776
+ const cached = this.visibilityMemo.get(key);
1777
+ if (cached !== undefined &&
1778
+ cached.state === state &&
1779
+ cached.revealedErrors === revealedErrors &&
1780
+ sameIdSet(cached.incompleteRules, incompleteRules)) {
1781
+ return cached.visibility;
1782
+ }
1783
+ const visibility = Object.freeze({
1784
+ // Reuse the cached set when its members are equal, so the memo's own identity comparison
1785
+ // can succeed on the next derivation.
1786
+ incompleteRules: cached !== undefined && sameIdSet(cached.incompleteRules, incompleteRules)
1787
+ ? cached.incompleteRules
1788
+ : Object.freeze(incompleteRules),
1789
+ revealedErrors,
1790
+ });
1791
+ this.visibilityMemo.set(key, {
1792
+ state,
1793
+ incompleteRules: visibility.incompleteRules,
1794
+ revealedErrors,
1795
+ visibility,
1796
+ });
1797
+ return visibility;
1798
+ }
1799
+ /**
1800
+ * Brings the sticky reveal set in line with committed state.
1801
+ *
1802
+ * A failure that is still true keeps its key even when the operand question that would decide
1803
+ * whether to paint it changed: a sentence the user has already seen must not flicker away.
1804
+ * A failure that is no longer true loses its key, so a later, different failure is judged by
1805
+ * the policy afresh rather than inheriting the old paint.
1806
+ */
1807
+ reconcileReveal() {
1808
+ const policy = this.session.display.reveal;
1809
+ if (policy !== 'touched')
1810
+ return;
1811
+ const submitted = this.submitCount > 0;
1812
+ const engine = this.session.engine;
1813
+ for (const { key, ref } of this.view.revealCandidates()) {
1814
+ let state;
1815
+ try {
1816
+ state = engine.getField(ref.fieldId, ref.rowKey);
1817
+ }
1818
+ catch {
1819
+ // The row was removed by the commit this publish is delivering. Its registration is
1820
+ // retired below by the publish loop, and a row that returns is a new row with no history.
1821
+ this.view.setRevealed(ref, EMPTY_REVEALED);
1822
+ continue;
1823
+ }
1824
+ const current = bindingErrors(state).errors;
1825
+ const previous = this.view.revealedOf(key);
1826
+ const next = new Set();
1827
+ if (state.visible) {
1828
+ const view = this.view.viewFor(key, submitted);
1829
+ const visibility = this.visibilityOf(engine, state, ref.fieldId, ref.rowKey, previous);
1830
+ for (const error of current) {
1831
+ // Only a blocking failure is something the session latches: a warning is painted
1832
+ // whenever it exists and needs no history, and access diagnostics are not failures.
1833
+ if (!error.blocking)
1834
+ continue;
1835
+ const failureKey = errorKey(error);
1836
+ // A key that survives is sticky: the failure is still true even if its operands no
1837
+ // longer make it answerable.
1838
+ if (previous.has(failureKey)) {
1839
+ next.add(failureKey);
1840
+ continue;
1841
+ }
1842
+ // A new failure is painted only once the policy lets it be: the binding has been
1843
+ // visited and every operand the rule reads has been supplied.
1844
+ const undecided = error.kind === 'validate' &&
1845
+ (error.status !== 'FAIL' || visibility.incompleteRules.has(error.ruleId));
1846
+ if (view.touched && !undecided)
1847
+ next.add(failureKey);
1848
+ }
1849
+ }
1850
+ this.view.setRevealed(ref, next);
1851
+ }
1852
+ }
1853
+ summaryOf(session) {
1854
+ const form = session.engine.getFormState();
1855
+ const committed = session === this.session;
1856
+ const cached = committed
1857
+ ? this.summary
1858
+ : this.candidateSummary?.owner === session.candidate
1859
+ ? this.candidateSummary.cache
1860
+ : undefined;
1861
+ if (cached !== undefined &&
1862
+ cached.form === form &&
1863
+ cached.submitCount === this.submitCount &&
1864
+ cached.isSubmitting === this.isSubmitting &&
1865
+ cached.submitSucceeded === this.submitSucceeded &&
1866
+ cached.epoch === this.snapshotEpoch &&
1867
+ cached.pendingProposal === this.pendingProposal) {
1868
+ return cached.summary;
1869
+ }
1870
+ const built = buildFormSummary({
1871
+ engine: session.engine,
1872
+ form,
1873
+ facts: this.facts,
1874
+ view: this.view,
1875
+ submitCount: this.submitCount,
1876
+ isSubmitting: this.isSubmitting,
1877
+ submitSucceeded: this.submitSucceeded,
1878
+ reveal: session.display.reveal,
1879
+ ruleReads: this.ruleReads,
1880
+ pendingProposal: this.pendingProposal,
1881
+ visibilityOf: (fieldId, rowKey) => this.visibilityOf(session.engine, session.engine.getField(fieldId, rowKey), fieldId, rowKey, this.view.revealedOf(bindingKey(fieldId, rowKey))),
1882
+ });
1883
+ // Candidate summaries share structure with committed state, but have their own cache slot:
1884
+ // an aborted render must not replace the snapshot a committed subscriber last read.
1885
+ const previous = cached ?? (committed ? undefined : this.summary);
1886
+ const summary = previous !== undefined && sameFormSummary(previous.summary, built) ? previous.summary : built;
1887
+ const next = {
1888
+ form,
1889
+ submitCount: this.submitCount,
1890
+ isSubmitting: this.isSubmitting,
1891
+ submitSucceeded: this.submitSucceeded,
1892
+ epoch: this.snapshotEpoch,
1893
+ pendingProposal: this.pendingProposal,
1894
+ summary,
1895
+ };
1896
+ if (committed)
1897
+ this.summary = next;
1898
+ else
1899
+ this.candidateSummary = { owner: session.candidate, cache: next };
1900
+ return summary;
1901
+ }
1902
+ publishForm() {
1903
+ if (this.formSubscriptions.size === 0)
1904
+ return;
1905
+ const summary = this.summaryOf(this.session);
1906
+ if (summary === this.published)
1907
+ return;
1908
+ this.published = summary;
1909
+ for (const listener of [...this.formSubscriptions])
1910
+ listener();
1911
+ }
1912
+ /**
1913
+ * Records that committed state moved on: nothing previewed survives it, and the next read
1914
+ * re-derives. A caller that publishes does so deliberately, so a reconfigure applied during a
1915
+ * render stays silent until the commit boundary delivers it.
1916
+ */
1917
+ markChanged() {
1918
+ this.previewed = undefined;
1919
+ this.snapshotEpoch += 1;
1920
+ }
1921
+ /** One committed-state change, delivered to its subscribers now. */
1922
+ snapshotChanged() {
1923
+ this.markChanged();
1924
+ this.publish();
1925
+ }
1926
+ /**
1927
+ * Baselines every binding from the record a session opened with.
1928
+ *
1929
+ * The record is read once here, not per derivation: the baseline is what `dirty` compares a
1930
+ * binding against, and only this moment and a reset define it.
1931
+ */
1932
+ captureBaseline(engine) {
1933
+ const form = engine.getFormState();
1934
+ this.view.capture(form, heldValuesOf(engine.values(), form, this.facts));
1935
+ }
1936
+ newCandidate(engine, inputs, display, overrides) {
1937
+ this.nextRevision += 1;
1938
+ return Object.freeze({ engine, inputs, overrides, display, revision: this.nextRevision });
1939
+ }
1940
+ newSession(engine, inputs, display, overrides) {
1941
+ const candidate = this.newCandidate(engine, inputs, display, overrides);
1942
+ this.previewed = candidate;
1943
+ return { engine, inputs, display, candidate };
1944
+ }
1945
+ sessionOf(candidate) {
1946
+ if (candidate === this.session.candidate)
1947
+ return this.session;
1948
+ return {
1949
+ engine: candidate.engine,
1950
+ inputs: candidate.inputs,
1951
+ display: candidate.display,
1952
+ candidate,
1953
+ };
1954
+ }
1955
+ sameView(candidate, inputs, display, overrides) {
1956
+ return (sameInputs(candidate.inputs, inputs) &&
1957
+ sameDisplay(candidate.display, display) &&
1958
+ sameOverrides(candidate.overrides, overrides));
1959
+ }
1960
+ /**
1961
+ * The inputs one evaluation runs with: the host's props, with the inputs an event handler
1962
+ * installed beside them.
1963
+ *
1964
+ * A prop is the authority for the input it states; an imperative `setAccess`/`setContext`/
1965
+ * `setEnv` stays in force only while the props name none, so a host that drives an input from
1966
+ * props is never overridden by its own earlier call.
1967
+ */
1968
+ effective(overrides) {
1969
+ const resolved = resolveSessionInputs(overrides);
1970
+ const inputs = resolved.overlay !== undefined ||
1971
+ resolved.access !== undefined ||
1972
+ this.imperativeOverlay === undefined
1973
+ ? resolved
1974
+ : { ...resolved, overlay: this.imperativeOverlay };
1975
+ return {
1976
+ ...inputs,
1977
+ optionDomains: this.optionDomains,
1978
+ ...(overrides.context === undefined && this.imperativeContext !== undefined
1979
+ ? { context: this.imperativeContext }
1980
+ : {}),
1981
+ ...(overrides.env === undefined && this.imperativeEnv !== undefined
1982
+ ? { env: this.imperativeEnv }
1983
+ : {}),
1984
+ };
1985
+ }
1986
+ defaultDisplay() {
1987
+ return {
1988
+ reveal: DEFAULT_POLICY,
1989
+ maskedDisplay: undefined,
1990
+ valueDisplay: undefined,
1991
+ idPrefix: this.idPrefix,
1992
+ };
1993
+ }
1994
+ /**
1995
+ * Replays the session writes a re-opened engine keeps.
1996
+ *
1997
+ * The host's current declaration comes first. Beside it travel the engine's references that
1998
+ * are the *user's* own writes, and nothing else: a host claim the props no longer state is
1999
+ * dropped, so a revoked unlock does not become session-owned, while a claim the user has since
2000
+ * written at is kept — the engine cannot tell the two apart, and subtracting it blanks the
2001
+ * control mid-edit. Only `reset()` retires a user write.
2002
+ */
2003
+ writesFor(inputs) {
2004
+ const engineWrites = this.session.engine.sessionWrites();
2005
+ const live = new Set(engineWrites.map(writeKey));
2006
+ for (const key of this.userWrites) {
2007
+ // A binding the engine no longer reports was removed with its row: its entry would only
2008
+ // grow the set without ever matching a claim again.
2009
+ if (!live.has(key))
2010
+ this.userWrites.delete(key);
2011
+ }
2012
+ const claimed = new Set(this.session.inputs.sessionWrites.map(writeKey));
2013
+ const writes = new Map();
2014
+ for (const ref of inputs.sessionWrites)
2015
+ writes.set(writeKey(ref), ref);
2016
+ for (const ref of engineWrites) {
2017
+ const key = writeKey(ref);
2018
+ if (writes.has(key))
2019
+ continue;
2020
+ if (claimed.has(key) && !this.userWrites.has(key))
2021
+ continue;
2022
+ writes.set(key, ref);
2023
+ }
2024
+ return [...writes.values()];
2025
+ }
2026
+ open(inputs, values, sessionWrites, identity) {
2027
+ return openEngine(this.compiled, inputs, values, sessionWrites, this.idFactory, identity);
2028
+ }
2029
+ }
2030
+ /**
2031
+ * The host source one field declares, refusing a field the caller cannot page.
2032
+ *
2033
+ * A `field` source takes its domain from another field's array, without a loader; asking for
2034
+ * pages of one is a programming error, named rather than answered with an empty domain.
2035
+ */
2036
+ function hostOptionSource(source, fieldId) {
2037
+ if (source?.kind !== 'host') {
2038
+ throw new AxiomError('ENGINE_ERROR', `${JSON.stringify(fieldId)} declares no host option source, so it has no pages to load`, fieldId);
2039
+ }
2040
+ return source;
2041
+ }
2042
+ /**
2043
+ * One dependency value, spelled so two bases differ exactly when the values differ.
2044
+ *
2045
+ * The wire contract's equality is member-order-insensitive (`sameWireValue`), so the text has to
2046
+ * be canonical: `JSON.stringify` spells `{a,b}` and `{b,a}` differently for one value, and a
2047
+ * dependency that is a record would then reload every page of the list on a render that changed
2048
+ * nothing. The restricted canonical form is the same text the engine hashes, so the basis cannot
2049
+ * disagree with the wire contract about when two values are the same.
2050
+ */
2051
+ function valueSignature(value) {
2052
+ return value === undefined ? '-' : canonicalizeRestricted(value);
2053
+ }
2054
+ /**
2055
+ * Whether a revealed failure paints before the control shows a failure.
2056
+ *
2057
+ * A decided warning is visible without making the control invalid. A deferred check is a
2058
+ * handoff the device has not decided, never a sentence a control paints.
2059
+ */
2060
+ function isPaintedWarning(error) {
2061
+ return error.kind === 'validate' && error.severity === 'warn' && error.status !== 'DEFERRED';
2062
+ }
2063
+ /** Whether two value states state the same value, for the "did the value move" question. */
2064
+ function sameValueState(left, right) {
2065
+ if (left.kind !== right.kind)
2066
+ return false;
2067
+ if (left.kind === 'value')
2068
+ return right.kind === 'value' && sameWireValue(left.value, right.value);
2069
+ if (left.kind === 'withheld')
2070
+ return right.kind === 'withheld' && left.reason === right.reason;
2071
+ return true;
2072
+ }
2073
+ /**
2074
+ * One binding's value after a write, or `undefined` when committed state no longer addresses it.
2075
+ *
2076
+ * A write may re-key a row and retire the reference it was issued for. The write still committed;
2077
+ * what it cannot answer is whether the old binding's value moved, and a retired binding has no
2078
+ * touch fact to carry.
2079
+ */
2080
+ function valueAfter(engine, ref) {
2081
+ try {
2082
+ return engine.getField(ref.fieldId, ref.rowKey).value;
2083
+ }
2084
+ catch {
2085
+ return undefined;
2086
+ }
2087
+ }
2088
+ /** The binding key one session write names, so a host claim and an engine write can be matched. */
2089
+ function writeKey(ref) {
2090
+ return bindingKey(ref.fieldId, ref.rowKey);
2091
+ }
2092
+ /** The shared empty read map of an artifact whose dependency inspection refused to order it. */
2093
+ const NO_RULE_READS = new Map();
2094
+ /** The empty reveal set, shared so a retired row's entry is cleared without an allocation. */
2095
+ const EMPTY_REVEALED = Object.freeze(new Set());
2096
+ /**
2097
+ * What a staged write answers: the record has not taken it, and nothing was refused.
2098
+ *
2099
+ * `queued` is the outcome union's "not applied yet" arm, which is exactly the fact: applying the
2100
+ * proposal is the only thing that writes it.
2101
+ */
2102
+ const STAGED = Object.freeze({
2103
+ outcome: Object.freeze({ outcome: 'queued' }),
2104
+ staged: true,
2105
+ });
2106
+ /**
2107
+ * Every rule's declared reads, from the artifact's own dependency inspection.
2108
+ *
2109
+ * `inspectDeps` caches its answer against the compiled object, so this map is built once per
2110
+ * artifact and the incomplete-operand question never walks an expression again. An artifact the
2111
+ * inspection refuses has no order to derive reads from; the empty map then makes every rule's
2112
+ * operands "complete", which can only paint a failure, never hide one the engine decided.
2113
+ */
2114
+ function ruleReadsOf(compiled) {
2115
+ const inspection = inspectDeps(compiled);
2116
+ if (!inspection.ok)
2117
+ return NO_RULE_READS;
2118
+ const reads = new Map();
2119
+ for (const rule of inspection.report.rules)
2120
+ reads.set(rule.ruleId, rule.reads);
2121
+ return reads;
2122
+ }
2123
+ /**
2124
+ * The bindings one operation writes as the user, which the session owns from then on.
2125
+ *
2126
+ * A structural operation is a row's arrival or departure rather than a value the session wrote,
2127
+ * and a context, environment or access change owns no binding at all, so neither records one.
2128
+ */
2129
+ function userWriteRefs(operation) {
2130
+ switch (operation.kind) {
2131
+ case 'value':
2132
+ case 'null':
2133
+ case 'remove':
2134
+ return operation.origin === 'user' ? [operation.ref] : [];
2135
+ case 'context':
2136
+ case 'env':
2137
+ case 'access':
2138
+ case 'append':
2139
+ case 'insert':
2140
+ case 'removeRow':
2141
+ case 'move':
2142
+ return [];
2143
+ default:
2144
+ return assertNever(operation);
2145
+ }
2146
+ }
2147
+ /**
2148
+ * The monotonic sequence one staged proposal carries, or `undefined` for a proposal the
2149
+ * `propose` door derived outside the staging machine.
2150
+ *
2151
+ * The member is read through a guard rather than a cast: `Proposal` deliberately does not state
2152
+ * it, because a proposal that was never staged has no order to compare.
2153
+ */
2154
+ function sequenceOf(proposal) {
2155
+ if (!('sequence' in proposal))
2156
+ return undefined;
2157
+ const sequence = proposal['sequence'];
2158
+ return typeof sequence === 'number' ? sequence : undefined;
2159
+ }
2160
+ function sameDisplay(left, right) {
2161
+ // The prefix is constant for a session, and compared anyway: a display that names a different
2162
+ // one is a display belonging to another form, not an unchanged one.
2163
+ if (left.idPrefix !== right.idPrefix)
2164
+ return false;
2165
+ if (left.reveal !== right.reveal)
2166
+ return false;
2167
+ if (left.valueDisplay !== right.valueDisplay)
2168
+ return false;
2169
+ return sameMaskedDisplay(left.maskedDisplay, right.maskedDisplay);
2170
+ }
2171
+ function sameMaskedDisplay(left, right) {
2172
+ if (left === right)
2173
+ return true;
2174
+ if (left === undefined || right === undefined)
2175
+ return false;
2176
+ const keys = Object.keys(left);
2177
+ return keys.length === Object.keys(right).length && keys.every((key) => left[key] === right[key]);
2178
+ }
2179
+ //# sourceMappingURL=form-store.js.map