attaform 0.27.6 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/dist/abstract.d.mts +5 -4
  2. package/dist/abstract.mjs +4 -3
  3. package/dist/chunks/fingerprint.mjs +0 -1
  4. package/dist/chunks/fingerprint2.mjs +1 -2
  5. package/dist/dev/abstract.mjs +4 -0
  6. package/dist/{chunks → dev/chunks}/dev-key-collision-warnings.mjs +0 -1
  7. package/dist/{chunks → dev/chunks}/devtools.mjs +5 -6
  8. package/dist/{chunks/fingerprint.cjs → dev/chunks/fingerprint.mjs} +7 -10
  9. package/dist/{chunks/fingerprint2.cjs → dev/chunks/fingerprint2.mjs} +32 -35
  10. package/dist/dev/directive.mjs +1 -0
  11. package/dist/dev/history.mjs +89 -0
  12. package/dist/dev/index.mjs +5 -0
  13. package/dist/dev/runtime/plugins/attaform.mjs +40 -0
  14. package/dist/{shared/attaform.D6tk90Rc.cjs → dev/shared/attaform-dev.6qxD-Yqo.mjs} +187 -43
  15. package/dist/{shared/attaform.CQN9R62B.cjs → dev/shared/attaform-dev.BJGA_UOS.mjs} +1 -4
  16. package/dist/{shared/attaform.DYEr28Pt.mjs → dev/shared/attaform-dev.BR8u0YOZ.mjs} +6 -7
  17. package/dist/dev/shared/attaform-dev.BXE2cr0L.mjs +220 -0
  18. package/dist/dev/shared/attaform-dev.By4PRjt0.mjs +248 -0
  19. package/dist/{shared/attaform.B1ZYt2Li.mjs → dev/shared/attaform-dev.D2I8e_Mm.mjs} +132 -568
  20. package/dist/dev/shared/attaform-dev.Dr2YzS5B.mjs +197 -0
  21. package/dist/{shared/attaform.nMaz2C5P.mjs → dev/shared/attaform-dev.P7cseiEG.mjs} +178 -397
  22. package/dist/{shared/attaform.CKH2lGdL.mjs → dev/shared/attaform-dev.WmuhD_CZ.mjs} +3944 -5056
  23. package/dist/{shared/attaform.DMxM2kol.mjs → dev/shared/attaform-dev.oYrkP9dj.mjs} +160 -508
  24. package/dist/dev/zod-v3.mjs +17 -0
  25. package/dist/dev/zod-v4.mjs +16 -0
  26. package/dist/dev/zod.mjs +5 -0
  27. package/dist/directive.d.mts +20 -0
  28. package/dist/directive.mjs +1 -0
  29. package/dist/esbuild.mjs +0 -1
  30. package/dist/history.d.mts +59 -0
  31. package/dist/history.mjs +89 -0
  32. package/dist/index.d.mts +11 -5
  33. package/dist/index.mjs +5 -4
  34. package/dist/nuxt.d.mts +1 -1
  35. package/dist/nuxt.mjs +5 -2
  36. package/dist/rollup.mjs +0 -1
  37. package/dist/rspack.d.mts +6 -1
  38. package/dist/rspack.mjs +0 -1
  39. package/dist/runtime/components/AttaformDevtoolsPanel.vue +9 -8
  40. package/dist/runtime/plugins/attaform.mjs +1 -2
  41. package/dist/shared/{attaform.Fp3sCrVs.d.ts → attaform.B4VkS43-.d.mts} +2 -2
  42. package/dist/shared/{attaform.DrvMscNX.cjs → attaform.B8k8JrmK.mjs} +4073 -5630
  43. package/dist/shared/attaform.BJGA_UOS.mjs +0 -1
  44. package/dist/shared/{attaform.CoR4mWfv.mjs → attaform.C09fpdLS.mjs} +172 -16
  45. package/dist/shared/{attaform.D8kliaKw.cjs → attaform.CJP3RkGa.mjs} +141 -590
  46. package/dist/shared/{attaform.DniawQLP.d.cts → attaform.Cgu-hdSb.d.mts} +268 -68
  47. package/dist/shared/attaform.Cs2Rbdlo.mjs +0 -1
  48. package/dist/shared/{attaform.CHlJLAiv.d.mts → attaform.D5V4tZWq.d.mts} +69 -179
  49. package/dist/shared/{attaform.B9Wyhfro.cjs → attaform.D6DCnnQu.mjs} +11 -16
  50. package/dist/shared/attaform.DhnPb6nK.mjs +0 -1
  51. package/dist/shared/attaform.Dq4vWxuG.mjs +197 -0
  52. package/dist/shared/attaform.JfSWdEcb.d.mts +44 -0
  53. package/dist/shared/attaform.KvlEedlF.mjs +0 -1
  54. package/dist/shared/{attaform.DdQN7sgN.cjs → attaform.NLmerepI.mjs} +175 -557
  55. package/dist/shared/attaform.h0i6LijT.mjs +242 -0
  56. package/dist/shared/{attaform.Biytrv0-.cjs → attaform.uLbun31C.mjs} +204 -544
  57. package/dist/shared/attaform.v0fQtWyA.mjs +0 -1
  58. package/dist/shared/attaform.wfY8XFvm.mjs +197 -0
  59. package/dist/transforms.mjs +0 -1
  60. package/dist/vite.d.mts +17 -5
  61. package/dist/vite.mjs +24 -2
  62. package/dist/webpack.d.mts +6 -1
  63. package/dist/webpack.mjs +0 -1
  64. package/dist/zod-v3.d.mts +11 -6
  65. package/dist/zod-v3.mjs +17 -4
  66. package/dist/zod-v4.d.mts +12 -6
  67. package/dist/zod-v4.mjs +16 -4
  68. package/dist/zod.d.mts +4 -3
  69. package/dist/zod.mjs +5 -4
  70. package/package.json +23 -8
  71. package/skills/attaform/SKILL.md +2 -1
  72. package/dist/abstract.cjs +0 -48
  73. package/dist/abstract.cjs.map +0 -1
  74. package/dist/abstract.d.cts +0 -42
  75. package/dist/abstract.d.ts +0 -42
  76. package/dist/abstract.mjs.map +0 -1
  77. package/dist/chunks/dev-key-collision-warnings.cjs +0 -25
  78. package/dist/chunks/dev-key-collision-warnings.cjs.map +0 -1
  79. package/dist/chunks/dev-key-collision-warnings.mjs.map +0 -1
  80. package/dist/chunks/devtools.cjs +0 -157
  81. package/dist/chunks/devtools.cjs.map +0 -1
  82. package/dist/chunks/devtools.mjs.map +0 -1
  83. package/dist/chunks/fingerprint.cjs.map +0 -1
  84. package/dist/chunks/fingerprint.mjs.map +0 -1
  85. package/dist/chunks/fingerprint2.cjs.map +0 -1
  86. package/dist/chunks/fingerprint2.mjs.map +0 -1
  87. package/dist/esbuild.cjs +0 -28
  88. package/dist/esbuild.cjs.map +0 -1
  89. package/dist/esbuild.d.cts +0 -56
  90. package/dist/esbuild.d.ts +0 -56
  91. package/dist/esbuild.mjs.map +0 -1
  92. package/dist/index.cjs +0 -51
  93. package/dist/index.cjs.map +0 -1
  94. package/dist/index.d.cts +0 -249
  95. package/dist/index.d.ts +0 -249
  96. package/dist/index.mjs.map +0 -1
  97. package/dist/nuxt.cjs +0 -84
  98. package/dist/nuxt.cjs.map +0 -1
  99. package/dist/nuxt.d.cts +0 -66
  100. package/dist/nuxt.d.ts +0 -66
  101. package/dist/nuxt.mjs.map +0 -1
  102. package/dist/rollup.cjs +0 -24
  103. package/dist/rollup.cjs.map +0 -1
  104. package/dist/rollup.d.cts +0 -35
  105. package/dist/rollup.d.ts +0 -35
  106. package/dist/rollup.mjs.map +0 -1
  107. package/dist/rspack.cjs +0 -10
  108. package/dist/rspack.cjs.map +0 -1
  109. package/dist/rspack.d.cts +0 -40
  110. package/dist/rspack.d.ts +0 -40
  111. package/dist/rspack.mjs.map +0 -1
  112. package/dist/runtime/components/AttaformDevtoolsPanel.vue.d.ts +0 -7
  113. package/dist/runtime/components/DevtoolsValueTree.vue.d.ts +0 -35
  114. package/dist/runtime/plugins/attaform.cjs +0 -43
  115. package/dist/runtime/plugins/attaform.cjs.map +0 -1
  116. package/dist/runtime/plugins/attaform.d.cts +0 -5
  117. package/dist/runtime/plugins/attaform.d.ts +0 -5
  118. package/dist/runtime/plugins/attaform.mjs.map +0 -1
  119. package/dist/shared/attaform.B1ZYt2Li.mjs.map +0 -1
  120. package/dist/shared/attaform.B9Wyhfro.cjs.map +0 -1
  121. package/dist/shared/attaform.BGDV42hI.d.cts +0 -232
  122. package/dist/shared/attaform.BJGA_UOS.mjs.map +0 -1
  123. package/dist/shared/attaform.Biytrv0-.cjs.map +0 -1
  124. package/dist/shared/attaform.Bn0IzhD_.cjs +0 -800
  125. package/dist/shared/attaform.Bn0IzhD_.cjs.map +0 -1
  126. package/dist/shared/attaform.C9fPTxjB.d.cts +0 -41
  127. package/dist/shared/attaform.C9fPTxjB.d.ts +0 -41
  128. package/dist/shared/attaform.CKH2lGdL.mjs.map +0 -1
  129. package/dist/shared/attaform.CQN9R62B.cjs.map +0 -1
  130. package/dist/shared/attaform.CoR4mWfv.mjs.map +0 -1
  131. package/dist/shared/attaform.Cs2Rbdlo.mjs.map +0 -1
  132. package/dist/shared/attaform.D6tk90Rc.cjs.map +0 -1
  133. package/dist/shared/attaform.D8kliaKw.cjs.map +0 -1
  134. package/dist/shared/attaform.DLknk9nF.d.mts +0 -232
  135. package/dist/shared/attaform.DMxM2kol.mjs.map +0 -1
  136. package/dist/shared/attaform.DRUT703x.d.cts +0 -56
  137. package/dist/shared/attaform.DRUT703x.d.ts +0 -56
  138. package/dist/shared/attaform.DYEr28Pt.mjs.map +0 -1
  139. package/dist/shared/attaform.DdQN7sgN.cjs.map +0 -1
  140. package/dist/shared/attaform.DhnPb6nK.mjs.map +0 -1
  141. package/dist/shared/attaform.DniawQLP.d.mts +0 -4763
  142. package/dist/shared/attaform.DniawQLP.d.ts +0 -4763
  143. package/dist/shared/attaform.DoQm_Vkd.cjs +0 -58
  144. package/dist/shared/attaform.DoQm_Vkd.cjs.map +0 -1
  145. package/dist/shared/attaform.DrvMscNX.cjs.map +0 -1
  146. package/dist/shared/attaform.F2Q8iv38.d.ts +0 -2494
  147. package/dist/shared/attaform.FmqKO1Ex.d.cts +0 -2494
  148. package/dist/shared/attaform.KvlEedlF.mjs.map +0 -1
  149. package/dist/shared/attaform.RaTzp1WF.cjs +0 -26
  150. package/dist/shared/attaform.RaTzp1WF.cjs.map +0 -1
  151. package/dist/shared/attaform.nMaz2C5P.mjs.map +0 -1
  152. package/dist/shared/attaform.v0fQtWyA.mjs.map +0 -1
  153. package/dist/shared/attaform.yUrz7C2z.cjs +0 -29
  154. package/dist/shared/attaform.yUrz7C2z.cjs.map +0 -1
  155. package/dist/transforms.cjs +0 -12
  156. package/dist/transforms.cjs.map +0 -1
  157. package/dist/transforms.d.cts +0 -73
  158. package/dist/transforms.d.ts +0 -73
  159. package/dist/transforms.mjs.map +0 -1
  160. package/dist/vite.cjs +0 -363
  161. package/dist/vite.cjs.map +0 -1
  162. package/dist/vite.d.cts +0 -133
  163. package/dist/vite.d.ts +0 -133
  164. package/dist/vite.mjs.map +0 -1
  165. package/dist/webpack.cjs +0 -10
  166. package/dist/webpack.cjs.map +0 -1
  167. package/dist/webpack.d.cts +0 -37
  168. package/dist/webpack.d.ts +0 -37
  169. package/dist/webpack.mjs.map +0 -1
  170. package/dist/zod-v3.cjs +0 -53
  171. package/dist/zod-v3.cjs.map +0 -1
  172. package/dist/zod-v3.d.cts +0 -246
  173. package/dist/zod-v3.d.ts +0 -246
  174. package/dist/zod-v3.mjs.map +0 -1
  175. package/dist/zod-v4.cjs +0 -55
  176. package/dist/zod-v4.cjs.map +0 -1
  177. package/dist/zod-v4.d.cts +0 -172
  178. package/dist/zod-v4.d.ts +0 -172
  179. package/dist/zod-v4.mjs.map +0 -1
  180. package/dist/zod.cjs +0 -51
  181. package/dist/zod.cjs.map +0 -1
  182. package/dist/zod.d.cts +0 -7
  183. package/dist/zod.d.ts +0 -7
  184. package/dist/zod.mjs.map +0 -1
@@ -1,2494 +0,0 @@
1
- import { G as GenericForm, F as FormKey, a as UseFormReturnType, a4 as RegisterValue, T as PathKey, k as DisplayCtx, w as GetDisplayState, l as DisplayMachine, S as Path, a9 as SlimPrimitiveKind, C as CoercionEntry, e as CoercionRegistry, af as ValidationError, A as AbstractSchema, aj as WriteMeta, h as DeepPartial, ak as WriteShape, as as TransformAbortHolder, ad as ValidateOn, d as AttaformDefaults, at as RegisterModelDynamicCustomDirective } from './attaform.DniawQLP.cjs';
2
- import { Ref, ComputedRef, App, InjectionKey, Plugin } from 'vue';
3
-
4
- /**
5
- * Options accepted by `injectForm` when passing an object instead of
6
- * a bare key string. `__ssrAccessed: true` is set by the Phase 3
7
- * `attaform-vite` transform on descendant calls whose template reads
8
- * the injected form's reactive state — it tells the runtime to
9
- * enqueue the form for SSR prefetch and register the descendant's
10
- * `onServerPrefetch` hook. Consumers may set it manually as the
11
- * escape hatch when the transform isn't installed or doesn't see
12
- * the reference.
13
- */
14
- type InjectFormInput = {
15
- readonly key?: FormKey;
16
- /**
17
- * Set by the Vite transform when this `injectForm` call site sits in
18
- * a component whose template / script reads the form's reactive
19
- * state. On the server, this enqueues the form for SSR prefetch and
20
- * wires `onServerPrefetch` so the descendant awaits the activation
21
- * promise before its render emits HTML.
22
- *
23
- * @internal Transform-emitted. Manual use is the documented escape
24
- * hatch when the transform can't reach the reference (dynamic
25
- * property access, untransformed bundlers).
26
- */
27
- readonly __ssrAccessed?: boolean;
28
- };
29
- /**
30
- * Access an existing form from a descendant component without passing
31
- * it through props. Counterpart to `useForm` — `useForm` creates and
32
- * provides; `injectForm` looks up via Vue's inject mechanism.
33
- *
34
- * Three ways to call it:
35
- *
36
- * ```ts
37
- * // Reach the nearest ancestor's anonymous useForm() call.
38
- * const form = injectForm<SignupShape>()
39
- *
40
- * // Reach a specific form by its key — works from anywhere in the app.
41
- * const cart = injectForm<CartShape>('cart')
42
- *
43
- * // Options form. The Vite transform emits this with `__ssrAccessed: true`
44
- * // when the descendant's template / script reads the form's reactive
45
- * // state, so the descendant participates in SSR prefetch coordination.
46
- * const cart = injectForm<CartShape>({ key: 'cart', __ssrAccessed: true })
47
- * ```
48
- *
49
- * Resolution rules (no-key form):
50
- * - Closest ambient ancestor wins.
51
- * - Only anonymous `useForm()` (no `key`) fills the ambient slot;
52
- * keyed forms are reachable only via `injectForm(key)`.
53
- * - Inherits the resolved ancestor's `formInstanceId`.
54
- *
55
- * Resolution rules (keyed form): registry lookup by string key,
56
- * independent of component-tree position.
57
- *
58
- * Returns `null` when no matching form exists (no ambient ancestor, or
59
- * the named key isn't registered yet). A dev-mode warning points at the
60
- * call site, lists the registered keys, and flags the mount-timing case
61
- * (a form created by a child or sibling isn't registered until its own
62
- * setup runs). Always narrow before using:
63
- *
64
- * ```ts
65
- * const form = injectForm<Shape>('signup')
66
- * if (!form) return
67
- * form.register('email')
68
- * ```
69
- *
70
- * Pass the `Form` generic explicitly — Vue's provide/inject erases
71
- * generics, so the library can't recover the shape automatically.
72
- *
73
- * The form is kept alive for this component's lifetime; once every
74
- * consumer unmounts, the form is cleaned up automatically.
75
- */
76
- declare function injectForm<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(input?: FormKey | InjectFormInput): UseFormReturnType<Form, GetValueFormType> | null;
77
-
78
- /**
79
- * Re-bind a parent's `v-register` onto an inner native element. Use
80
- * inside a component that wraps a single form field whose root is
81
- * NOT the input itself (e.g. a labelled-row that renders `<label>`
82
- * around the input).
83
- *
84
- * ```vue
85
- * <!-- Parent -->
86
- * <MyInput v-register="form.register('email')" />
87
- *
88
- * <!-- MyInput.vue -->
89
- * <script setup lang="ts">
90
- * import { useRegister } from 'attaform'
91
- * const rv = useRegister()
92
- * // rv.path / rv.segments / rv.formKey / rv.formInstanceId / rv.innerRef
93
- * // are all reachable directly — no `.value` unwrap.
94
- * </script>
95
- *
96
- * <template>
97
- * <label class="field">
98
- * <span>Email</span>
99
- * <input v-register="rv" />
100
- * </label>
101
- * </template>
102
- * ```
103
- *
104
- * Returns a hybrid Proxy: it answers `__v_isRef` / `.value` like a
105
- * Vue `Ref<RegisterValue | undefined>` (so templates auto-unwrap
106
- * correctly and `v-register="rv"` feeds the underlying RV to the
107
- * directive — preserving the directive's path-migration diff across
108
- * renders), AND every other property read pierces to the captured
109
- * RV's field (so `rv.path` works directly in script setup). Reads
110
- * inside reactive scopes (`computed` / `watchEffect`) track the
111
- * underlying `shallowRef`, so `rv.path` re-runs when the parent
112
- * rebinds to a different path.
113
- *
114
- * Unbound state: when the parent didn't pass `v-register`, every
115
- * piercing read returns `undefined` at runtime, and the return type
116
- * surfaces this honestly as `UseRegisterReturn<V> | undefined`.
117
- * Consumers defend with optional chaining (`rv?.formKey`,
118
- * `rv?.segments`); the directive accepts `undefined` peacefully (its
119
- * binding value type is already `RegisterValue<V> | undefined`), so
120
- * `v-register="rv"` works whether or not a parent has bound. The
121
- * composable's `onMounted` warn fires once per instance to surface
122
- * the misuse case at runtime.
123
- *
124
- * Diagnostic: in dev mode, a single `console.warn` fires per instance
125
- * at `onMounted` if the captured value is still `undefined` — by then
126
- * the parent has had its full mount lifecycle to bind, so a missing
127
- * binding is conclusive misuse. The warn does NOT fire on every read
128
- * of the proxy, and is intentionally silent under SSR
129
- * (`renderToString` skips `onMounted`); the CSR hydration pass
130
- * surfaces the same diagnostic without double-counting through Nuxt's
131
- * `dev:ssr-logs` channel.
132
- *
133
- * When the wrapper's root IS the input itself, Vue's attribute
134
- * fallthrough handles the binding and `useRegister` is unnecessary.
135
- * For wrappers that bind multiple fields (compound forms), use
136
- * `injectForm<Form>(key?)` and call `ctx.register(...)` directly.
137
- */
138
-
139
- /**
140
- * Return type of `useRegister()`. Hybrid of `RegisterValue<V>` (so
141
- * `rv.path` / `rv.segments` / `rv.formKey` etc. work directly in
142
- * script setup) and `Ref<RegisterValue<V> | undefined>` (so Vue's
143
- * template auto-unwrap surfaces the underlying RV to `v-register`
144
- * and the directive's path-migration diff sees the real RV across
145
- * renders).
146
- *
147
- * The two surfaces don't clash at the type level: `RegisterValue`
148
- * doesn't carry a `value` field, and `Ref<T>`'s `value: T` becomes
149
- * the hybrid's only `.value`. Older code that read `rv.value?.path`
150
- * keeps working; new code can write `rv.path` directly.
151
- */
152
- type UseRegisterReturn<V = unknown> = RegisterValue<V> & Ref<RegisterValue<V> | undefined>;
153
- declare function useRegister<V = unknown>(): UseRegisterReturn<V> | undefined;
154
-
155
- /**
156
- * Per-form display engine: owns the clock and the timers that the pure
157
- * `getDisplayState` reducer policy needs, so the reducer itself stays a
158
- * deterministic `(prev, ctx) => next` function.
159
- *
160
- * It keeps a `Map` of the machines that are still *active* (a spinner is
161
- * showing, a verdict is being held, or a `reviewAt` deadline is pending),
162
- * a single reactive `tick` ref, and a single `setTimeout` aimed at the
163
- * nearest `reviewAt` across every active field. When a field-state
164
- * computed reads `resolve`, it subscribes to `tick`; when the timer
165
- * fires, `tick` bumps and every dependent computed re-runs the reducer,
166
- * so a field whose deadline elapsed transitions (verdict → spinner, or
167
- * spinner → settled verdict) without any per-field watcher.
168
- *
169
- * Eviction: a machine is dropped once it reaches a terminal *idle* state
170
- * with no pending review. Error / success / pending machines are retained
171
- * so the reducer can hold the prior verdict under the show-delay window of
172
- * the *next* validation streak (no success → idle → success flicker). The
173
- * retained set is bounded by the rendered non-idle fields; none of them
174
- * arm a timer, so retention costs memory, never CPU.
175
- *
176
- * Untrusted reducer: `getDisplayState` is consumer-overridable, so the
177
- * engine treats the returned `reviewAt` as untrusted. A non-finite deadline
178
- * (NaN / ±Infinity from a custom predicate's bad arithmetic) is ignored
179
- * rather than handed to `setTimeout`, where it coerces to 0 and spins; an
180
- * over-large finite deadline is clamped below the 32-bit `setTimeout`
181
- * overflow; and the timer refuses to re-arm for the exact deadline it just
182
- * fired, so a predicate re-emitting a fixed or past `reviewAt` can't drive an
183
- * infinite fire loop. None of these arise from the library default, which
184
- * always advances its deadline or drops it.
185
- *
186
- * Background tabs: `setTimeout` is throttled to >= 1s while a tab is hidden,
187
- * so a min-visible hold can overshoot. A `visibilitychange` listener bumps
188
- * the clock on return to the foreground, so any overdue deadline resolves at
189
- * once instead of lingering.
190
- *
191
- * SSR: no clock, no timers, no listener. With `now` frozen and nothing
192
- * validating at render, the reducer returns the plain verdict (never
193
- * pending) and the engine stores nothing, so the server HTML and the
194
- * client's first render agree — no hydration mismatch on the display
195
- * projection.
196
- */
197
- type DisplayEngine = {
198
- /**
199
- * Resolve a path's next `DisplayMachine`. Subscribes the calling
200
- * computed to the engine clock, threads the path's previous machine
201
- * through `reducer`, persists or evicts the result, and re-arms the
202
- * single timer to the nearest deadline.
203
- */
204
- resolve(key: PathKey, ctx: DisplayCtx, reducer: GetDisplayState): DisplayMachine;
205
- /** Drop every retained machine and cancel the timer (used by `reset()`). */
206
- clear(): void;
207
- /** Tear down for good: `clear()` plus detaching the visibility listener. */
208
- dispose(): void;
209
- /** Introspection for tests: count of retained machines. */
210
- size(): number;
211
- /** Introspection for tests: whether a path currently has a retained machine. */
212
- has(key: PathKey): boolean;
213
- /** Introspection for tests: whether a deadline timer is currently armed. */
214
- hasTimer(): boolean;
215
- };
216
-
217
- /**
218
- * Per-path field status. Replaced wholesale (not mutated in place) on
219
- * every change. Five semantic groups:
220
- *
221
- * - `connected` — is a DOM element registered for this path?
222
- * - `focused` / `blurred` — DOM-state flags. `null` while no element
223
- * is connected (no DOM means the concepts don't apply); plain
224
- * booleans once connected, with the invariant `blurred === !focused`
225
- * enforced by `markFocused`.
226
- * - `touched` — focus/blur history, not DOM state. Always a plain
227
- * boolean: `false` at registration, sticky `true` after first blur,
228
- * cleared only by `form.reset()` / `form.resetField(path)`. Persists
229
- * across disconnects so v-if'd-away fields don't lose their touched
230
- * state on rehide (wizard "show review of touched fields" patterns
231
- * rely on this).
232
- * - `interacted` — value-mutation history, not DOM state. Plain
233
- * boolean: `false` at registration, sticky `true` once the user
234
- * issues a value edit through the directive's input listeners
235
- * (never on hydration, default seeding, or programmatic setValue);
236
- * cleared with `touched` by `form.reset()` / `form.resetField(path)`.
237
- * - `blurredAfterInteraction` — the first blur that follows a value
238
- * edit (the field has been edited and then left). Plain boolean,
239
- * sticky `true`. A tab-through blur with no prior edit does NOT set
240
- * it (`interacted` is still false at that blur). Composes
241
- * `interacted` with the departure; drives the default display gate.
242
- */
243
- type FieldRecord = {
244
- readonly path: Path;
245
- readonly updatedAt: string | null;
246
- readonly connected: boolean;
247
- readonly focused: boolean | null;
248
- readonly blurred: boolean | null;
249
- readonly touched: boolean;
250
- readonly interacted: boolean;
251
- readonly blurredAfterInteraction: boolean;
252
- };
253
- /** Per-path DOM element tracking. Client-only. */
254
- type ElementRecord = {
255
- /**
256
- * Original Path captured at first registration. Stored alongside the
257
- * elements Set so the DOM-order sort cache can recover the structured
258
- * Path without round-tripping through `JSON.parse(pathKey)`.
259
- */
260
- readonly path: Path;
261
- readonly elements: Set<HTMLElement>;
262
- };
263
- /**
264
- * Per-path record stored in `originals`. Pairing `segments` with the tracked
265
- * value means `dirty` and `resetField`'s container loop don't have to
266
- * `JSON.parse(pathKey)` on every iteration — the canonical Path is already
267
- * sitting next to the value it belongs to. PathKey still keys the Map (the
268
- * stable string is the only collision-free identifier), but downstream
269
- * iteration reads `segments` directly.
270
- */
271
- type OriginalsRecord = {
272
- readonly segments: Path;
273
- readonly value: unknown;
274
- };
275
-
276
- /**
277
- * Schema-driven coercion of user-typed DOM values at the v-register
278
- * directive layer. When the slim schema declares a numeric or
279
- * boolean type at a path, the directive coerces incoming string
280
- * values (`'25'` → `25`, `'true'` → `true`) before the slim-primitive
281
- * gate sees the write — making the schema authoritative for storage
282
- * shape and freeing consumers from sprinkling `.number` modifiers
283
- * across templates.
284
- *
285
- * Coercion is consumer-extensible: a `CoercionRegistry` is just an
286
- * `Array<CoercionEntry>` keyed at config time by `(input, output)`
287
- * `SlimPrimitiveKind` literals. The library ships
288
- * `defaultCoercionRules` (string→number, string→boolean) and
289
- * `defineCoercion` for type-narrowed authoring; consumers spread the
290
- * defaults to extend or supply their own array to replace.
291
- *
292
- * Coercion applies ONLY to user-typed DOM values flowing through
293
- * the directive's assigner. Programmatic writes (`form.setValue`,
294
- * `setValueWithInternalPath`) bypass coercion — they're authoritative
295
- * writes whose strict typing is on the caller. This mirrors the
296
- * `transforms` pipeline's user-input-only contract.
297
- */
298
-
299
- /**
300
- * Type-narrowing helper for authoring entries. At runtime it's
301
- * identity; at compile time it preserves the `input` / `output`
302
- * literal types so `transform`'s parameter is narrowed to the
303
- * runtime type instead of widening to `SlimRuntimeOf<SlimPrimitiveKind>`.
304
- *
305
- * Without this helper, authoring `{ input: 'string', output:
306
- * 'number', transform: (s) => ... }` against the broader
307
- * `CoercionEntry` widens `s` to `string | number | boolean | ...`,
308
- * forcing a cast in every transform body. `defineCoercion` is the
309
- * opaque-free idiom.
310
- */
311
- declare function defineCoercion<I extends SlimPrimitiveKind, O extends SlimPrimitiveKind>(entry: CoercionEntry<I, O>): CoercionEntry<I, O>;
312
- /**
313
- * Internal index built from a `CoercionRegistry` at config-resolve
314
- * time. Keyed by `${input}->${output}` for O(1) per-keystroke
315
- * dispatch. The authoring shape (array, ergonomic, type-narrowing-
316
- * friendly) and the dispatch shape (Map, fast) decouple cleanly.
317
- */
318
- type CoercionIndex = ReadonlyMap<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>;
319
- /**
320
- * The library's built-in registry. Two cells: string→number and
321
- * string→boolean. Re-exported so consumers can spread it when
322
- * supplying a custom registry that extends defaults.
323
- */
324
- declare const defaultCoercionRules: CoercionRegistry;
325
-
326
- type FormStore<F extends GenericForm, G extends GenericForm = F> = {
327
- readonly formKey: FormKey;
328
- readonly form: Ref<F>;
329
- readonly fields: Map<PathKey, FieldRecord>;
330
- readonly elements: Map<PathKey, ElementRecord>;
331
- /**
332
- * Schema-driven errors. Written ONLY by the schema validation pipeline:
333
- * `scheduleFieldValidation`, `handleSubmit`, the construction-time seed,
334
- * history restore, and hydration. Cleared by `reset` / `resetField` and by
335
- * a successful submit. `setErrors` / `clearErrors` do NOT touch this Map.
336
- */
337
- readonly schemaErrors: Map<PathKey, ValidationError[]>;
338
- /**
339
- * User-injected errors. Written ONLY by the `setErrors` / `clearErrors`
340
- * API surface (and history / hydration replay). Survives schema revalidation and
341
- * successful submits — the consumer owns its lifetime explicitly.
342
- */
343
- readonly userErrors: Map<PathKey, ValidationError[]>;
344
- /**
345
- * Reactively-derived "No value supplied" errors. Pure function of
346
- * `(blankPaths, schema.isRequiredAtPath)` — no writers, no clears.
347
- * Membership tracks `blankPaths` automatically: typing a value into
348
- * a blank required numeric field removes the path from `blankPaths`
349
- * and the derived error vanishes; clearing the numeric input re-adds
350
- * the path and the error reappears. The `errors` proxy and
351
- * `getErrorsForPath` merge this map in alongside `schemaErrors` and
352
- * `userErrors`, so consumers see the "this required field is empty"
353
- * error the moment it's true — no `validate()` / `handleSubmit`
354
- * call required. Honors the founding principle that
355
- * `errors = f(schema, state)`.
356
- *
357
- * Most entries flow through this map for `number` / `bigint` leaves
358
- * (where the side-channel is needed to distinguish "user typed 0"
359
- * from "user supplied nothing"). String / boolean leaves only land
360
- * here when the consumer explicitly opted in via the `unset`
361
- * sentinel — see `docs/validation/blank.md`.
362
- */
363
- readonly derivedBlankErrors: ComputedRef<ReadonlyMap<PathKey, ValidationError[]>>;
364
- readonly originals: Map<PathKey, OriginalsRecord>;
365
- /**
366
- * Reactive set of paths whose displayed state should be EMPTY even
367
- * though storage holds a real, schema-conformant value (the slim
368
- * default). It exists exclusively to record **storage / display
369
- * divergence** — the case where the runtime can't tell "user typed
370
- * 0" from "user supplied nothing" by looking at storage alone.
371
- *
372
- * The mechanism shines for `number` / `bigint`: storage holds the
373
- * slim default (`0` / `0n`) but the DOM input shows `''`, so the
374
- * directive's input listener marks the path here on clear. Strings
375
- * and booleans don't need it — `''` storage equals `''` display,
376
- * `false` storage equals unchecked display — so they're never
377
- * auto-marked. Consumers can still mark any primitive leaf
378
- * explicitly via the `unset` sentinel (`defaultValues: { x: unset }`,
379
- * `setValue('x', unset)`, `reset({ x: unset })`); the mark is then
380
- * a documented signal of consumer intent rather than runtime
381
- * inference.
382
- *
383
- * Reads (`displayValue` computed, `fields.<path>.blank`,
384
- * `derivedBlankErrors` computed) track via Vue 3.5's reactive Set
385
- * handlers. Writes happen inside `setValueAtPath` (gate-hook
386
- * bookkeeping: `blank: true` meta adds the path; any other write
387
- * removes it) and `reset`.
388
- *
389
- * Storage NEVER reflects this set — calculations and reads against
390
- * `form.value` see the slim default. The set is purely a UI/intent
391
- * channel that `derivedBlankErrors` consults to surface
392
- * "No value supplied" errors for required schemas.
393
- *
394
- * See `docs/validation/blank.md` for the conceptual model.
395
- */
396
- readonly blankPaths: Set<PathKey>;
397
- /**
398
- * Snapshot of `blankPaths` captured at construction (and
399
- * re-captured on `reset(args)`). Used by dirty calculation: a path
400
- * whose membership differs from the snapshot is dirty even if
401
- * storage matches the original. Eagerly populated to avoid a "dirty
402
- * on first read" race after construction.
403
- */
404
- readonly originalBlankPaths: Set<PathKey>;
405
- readonly schema: AbstractSchema<F, G>;
406
- /**
407
- * Server-side flag, plumbed in from `registry.ssr`. The
408
- * `register()`-returned `markConnectedOptimistically()` reads this
409
- * before flipping `connected: true`; on the client it's a no-op so
410
- * the eventual directive lifecycle remains the source of truth.
411
- */
412
- readonly ssr: boolean;
413
- /**
414
- * Resolved `getDisplayState` predicate driving `field.displayState`,
415
- * the `show*` booleans, and their `form.meta` rollups. Resolved once
416
- * at construction via `resolveGetDisplayState(options.getDisplayState)`;
417
- * `undefined` config falls through to `defaultDisplayState`. The
418
- * field-state computeds read the resolved function directly on every
419
- * read.
420
- */
421
- readonly getDisplayState: GetDisplayState;
422
- /**
423
- * Per-form display engine: owns the clock and the single timer the timed
424
- * `getDisplayState` reducer policy needs, keeping the reducer itself a
425
- * pure `(prev, ctx) => next` function. The field-state computeds route
426
- * every `displayState` read through `displayEngine.resolve(...)`, which
427
- * threads the path's previous machine, persists or evicts the result, and
428
- * re-arms the nearest-deadline timer. Constructed once at form
429
- * construction; torn down via `registerCleanup` on store eviction.
430
- */
431
- readonly displayEngine: DisplayEngine;
432
- readonly submitting: Ref<boolean>;
433
- readonly activeSubmissions: Ref<number>;
434
- readonly submissionAttempts: Ref<number>;
435
- /**
436
- * `true` once a `handleSubmit` callback resolved without throwing.
437
- * Independent of `submissionAttempts` — a failed submit increments
438
- * attempts but leaves `submitted` at `false`. Cleared by `reset()`
439
- * alongside the rest of the submission surface.
440
- */
441
- readonly submitted: Ref<boolean>;
442
- readonly submitError: Ref<Error | null>;
443
- readonly departAttempts: Ref<number>;
444
- /**
445
- * Effective data-freeze state: `true` when either the form's own
446
- * `disabled` config resolves truthy or `externalLock` is set. Read at
447
- * the write chokepoint (`setValueAtPath`), the register value's
448
- * `disabled`, and the field display predicate.
449
- */
450
- readonly effectiveDisabled: ComputedRef<boolean>;
451
- /**
452
- * Wizard-driven freeze channel. `useWizard` sets this `true` for a
453
- * locked step's member form; ORed into `effectiveDisabled` so the
454
- * wizard lock is authoritative and a member form cannot escape it by
455
- * passing `disabled: false`. Default `false`.
456
- */
457
- readonly externalLock: Ref<boolean>;
458
- /**
459
- * `true` while a function-form `defaultValues` factory is in flight.
460
- * Stays `false` for plain-value `defaultValues`. Shared across every
461
- * `useForm({ key })` call that resolves to this store — the second
462
- * caller sees the first caller's hydration state.
463
- */
464
- readonly hydrating: Ref<boolean>;
465
- /**
466
- * Error from the most recent function-form `defaultValues` factory.
467
- * Normalized to a `ValidationError` (code `atta:hydration-failed`) so the
468
- * shape matches `form.errors` / `form.meta.errors` entries. `null` when
469
- * no factory has fired or the last one succeeded.
470
- */
471
- readonly hydrateError: Ref<ValidationError | null>;
472
- /**
473
- * The function-form `defaultValues` factory, captured at the first
474
- * `useForm({ key })` call that wired this store. `undefined` for
475
- * plain-value forms. Read by `form.rehydrate()`.
476
- */
477
- readonly defaultValuesFactory: Ref<(() => unknown | Promise<unknown>) | undefined>;
478
- /**
479
- * `true` when this store carries an SSR prefetch queue (server path
480
- * where `state.activate()` must enqueue intent before deciding
481
- * whether to fire). The flag lets `buildFormApi` skip the lazy
482
- * activation gate for forms with no factory AND no SSR prefetch —
483
- * the common client-side case where `gated()` is otherwise pure
484
- * reactive overhead on every public method call.
485
- */
486
- readonly hasSsrPrefetch: boolean;
487
- /**
488
- * `true` once the form's effective defaults have been applied —
489
- * sync `defaultValues` at construction, or async factory whose
490
- * settle completed. Stays `false` for dormant lazy forms until they
491
- * activate. Read by `useWizard` to decide whether seed status or
492
- * live meta should surface.
493
- */
494
- readonly defaultsResolved: Ref<boolean>;
495
- /**
496
- * `true` once the captured async factory has been kicked off (set
497
- * synchronously by `activate()`, before the factory itself resolves).
498
- * Distinct from `defaultsResolved`, which only flips after the factory
499
- * settles. The pair lets the API surface tell "we've started" apart
500
- * from "we're done."
501
- */
502
- readonly activated: Ref<boolean>;
503
- /**
504
- * In-flight activation promise. Concurrent callers (cross-component
505
- * SSR consumers, recursive factory reads, parallel `activate()`
506
- * calls) receive the same promise, ensuring the factory runs once
507
- * even under contention.
508
- */
509
- readonly activationPromise: Ref<Promise<void> | undefined>;
510
- /**
511
- * Idempotent activation entrypoint. Fires the captured function-form
512
- * `defaultValues` factory on first call and stores the in-flight
513
- * promise. Subsequent calls return the same promise until the factory
514
- * settles; thereafter calls return `Promise.resolve()`. Plain-value
515
- * forms (no factory captured) always return a resolved promise. The
516
- * public API surface routes all reactive interactions (getters and
517
- * methods, except `key`) through this entrypoint so the form
518
- * activates on first use.
519
- */
520
- activate(): Promise<void>;
521
- /**
522
- * Re-fire the captured function-form `defaultValues` factory. Throws
523
- * synchronously when no factory was captured (plain-value form).
524
- * Resolves after `hydrating` flips back to `false`; consumers can
525
- * `await form.rehydrate()` to gate UI on the fresh load.
526
- *
527
- * Does NOT touch dirty / touched / submit state — chain
528
- * `form.reset()` if you want a clean baseline.
529
- */
530
- rehydrate(): Promise<void>;
531
- /**
532
- * Incremented by every `reset()` call. The submit wrapper captures
533
- * this at entry and skips writing `submitError` from a catch that
534
- * fires *after* a reset — otherwise a reset-during-submit would
535
- * visibly clear `submitError` and then have it reappear when the
536
- * in-flight promise rejects.
537
- */
538
- readonly submissionGeneration: Ref<number>;
539
- /**
540
- * Counts in-flight validation calls across every `validate()` ref and
541
- * every `validateAsync(...)` / `handleSubmit` pre-check. `validating`
542
- * on the public API mirrors `activeValidations.value > 0`. Tracked
543
- * separately from submissions because a validate-while-submitting
544
- * (e.g. a debounced field check overlapping a submit) needs to show
545
- * the union of both surfaces.
546
- */
547
- readonly activeValidations: Ref<number>;
548
- /**
549
- * `true` once the form has completed at least one validation pass
550
- * — flips when `activeValidations` returns to 0 from any positive
551
- * value. Until that happens, `meta.valid` and `field.valid` report
552
- * `false` even when `schemaErrors.size === 0`, because the absence
553
- * of errors at frame 1 is just "we haven't checked yet," not "we
554
- * checked and it's clean."
555
- *
556
- * This closes the brief flash window for schemas where the slim
557
- * default-derivation parse strips refinements (`.refine`,
558
- * `.superRefine`, async validators): the slim parse passes, no
559
- * construction-time errors land, and the queued microtask hasn't
560
- * run yet — so without the gate, frame 1 paints the form as
561
- * "valid" before the real verdict arrives a tick later.
562
- *
563
- * Initialized to `!strict`: non-strict consumers opt out of the
564
- * validation pipeline by design, so locking them on
565
- * `firstValidationDone === false` would defeat the opt-out.
566
- * Reset is left untouched — the post-reset validation flips it
567
- * back true on completion, same as the construction-time path.
568
- */
569
- readonly firstValidationDone: Ref<boolean>;
570
- /**
571
- * `true` when the sub-schema rooted at `path` (or any of its
572
- * descendants) declares async work — composes
573
- * `schema.getSchemasAtPath(path)` with each candidate's
574
- * `needsAsyncValidation()`, memoised per canonical path key for
575
- * the lifetime of the FormStore. Used by `meta.valid` /
576
- * `field.valid` to skip the `firstValidationDone` gate on subtrees
577
- * that are fully synchronous: their verdict resolves at construction
578
- * (or on the next per-field run) without waiting on a microtask, so
579
- * honouring the form-wide gate would just play dumb about a known
580
- * answer.
581
- */
582
- pathHasAsyncValidation(path: Path): boolean;
583
- /**
584
- * Precomputed-key shortcut for `pathHasAsyncValidation`. The
585
- * canonical key is required and must correspond to `segments`; the
586
- * helper skips the `canonicalizePath` round-trip so descendant-walk
587
- * loops (whose Map iteration already yields the canonical key) can
588
- * read the async-gate verdict without a per-leaf canonicalize.
589
- */
590
- pathHasAsyncValidationByKey(key: PathKey, segments: Path): boolean;
591
- /**
592
- * Per-path counter of in-flight field-level validation runs.
593
- * `field.validating` on `FieldState` mirrors
594
- * `(fieldValidationCounts.get(key) ?? 0) > 0`.
595
- *
596
- * Incremented at the same point as `activeValidations` inside
597
- * `scheduleFieldValidation`'s `run` closure (right before the schema
598
- * call) and decremented in the matching `.finally` — so the per-path
599
- * bookkeeping is exactly co-extensive with the form-wide counter for
600
- * the field-scheduled branch. Whole-form `validate()` /
601
- * `validateAsync()` runs touch `activeValidations` only; they don't
602
- * have a single field path and so don't contribute here.
603
- *
604
- * Counter (not Set) because two runs for the same path can briefly
605
- * overlap: when an in-flight run is aborted and a new run starts,
606
- * the new run increments before the aborted run's `.finally`
607
- * decrements. With `> 0` semantics the field stays "validating"
608
- * across the abort/restart boundary.
609
- *
610
- * Reactive Map: Vue 3's `reactive(new Map())` proxy makes `.get()`,
611
- * `.has()`, and `.size` track per-key, so the FieldState
612
- * computed only re-runs when the count for ITS key changes.
613
- */
614
- readonly fieldValidationCounts: Map<PathKey, number>;
615
- /**
616
- * Per-path `Date.now()` stamp marking when the field's LATEST validation
617
- * run started, re-anchored on every run start (every increment), deleted
618
- * on the `→ 0` edge. The display reducer reads it as `ctx.validatingSince`
619
- * to time the anti-flash spinner, which measures `now - validatingSince`:
620
- * re-anchoring on each run means a burst of keystrokes (each aborting the
621
- * prior run and starting a new one) keeps pushing the stamp forward, so the
622
- * spinner stays suppressed until the user pauses rather than surfacing
623
- * mid-typing. Anchoring only at the streak start would pin it to the first
624
- * keystroke, because with `debounceMs: 0` the aborted run's decrement lands
625
- * after the next run's increment and the count never returns to 0 between
626
- * fast keystrokes. The field-state container walk takes the descendant-min
627
- * so a row spinner anchors at its earliest still-active leaf. Runtime-only,
628
- * never hydrated, like the counts. REACTIVE: the display computed reads this
629
- * (as `ctx.validatingSince`) but not the `validating` flag, and a long
630
- * validation that settles with an unchanged verdict (same error, still
631
- * invalid) leaves `errors` / `valid` untouched — so a non-reactive map would
632
- * leave a held `pending` spinner stranded after the run ends, until some
633
- * unrelated reactive change happened to re-run the computed. Reactivity ties
634
- * the computed to both the streak start (set) and end (delete).
635
- */
636
- readonly fieldValidatingSince: Map<PathKey, number>;
637
- /**
638
- * Per-path counter of in-flight async-transform runs (the async
639
- * branch of the `register({ transforms })` pipeline). `> 0` drives
640
- * `field.transforming` / `field.busy`. Counter, not flag, for the
641
- * same overlap reason as `fieldValidationCounts`, except a superseding
642
- * input releases the prior run synchronously before incrementing the
643
- * new one — so the count is the live in-flight depth at the path
644
- * (effectively 0 or 1). Reactive Map, like the validation counters.
645
- */
646
- readonly fieldTransformCounts: Map<PathKey, number>;
647
- /**
648
- * Per-path `ssr ? 0 : Date.now()` stamp marking when the path's latest
649
- * async transform opened; the display reducer reads it (as
650
- * `ctx.transformingSince`) to time the gated busy spinner. Mirrors
651
- * `fieldValidatingSince` exactly: re-anchored on each run start,
652
- * deleted on the `→ 0` edge, reactive for the held-spinner reason.
653
- */
654
- readonly fieldTransformingSince: Map<PathKey, number>;
655
- /**
656
- * Per-path latest async-transform failure (a rejected transform, or a
657
- * resolved value the write gate refused), surfaced as
658
- * `field.transformError`. Cleared when a fresh run opens at the path
659
- * and on `reset()`. A channel separate from validation `errors`.
660
- */
661
- readonly transformErrors: Map<PathKey, Error | null>;
662
- /**
663
- * Form-wide count of in-flight async-transform runs. Drives the
664
- * `settleTransforms` quiescence guard and the `handleSubmit` drain
665
- * barrier. `Math.max(0, …)`-clamped on release so a doubled decrement
666
- * (a run's own `endTransform` after a synchronous cancel release)
667
- * can't drive it negative.
668
- */
669
- readonly activeTransforms: Ref<number>;
670
- /**
671
- * Replace the form value wholesale. Optional `meta` is forwarded to
672
- * every `onFormChange` listener so they can decide whether THIS write
673
- * is one they care about (e.g. history tagging a hydration replay).
674
- */
675
- applyFormReplacement(next: F, meta?: WriteMeta): void;
676
- /**
677
- * Set a single path's value. `meta` is forwarded to listeners via
678
- * `applyFormReplacement` (see above). Public `form.setValue` passes no
679
- * meta.
680
- *
681
- * Returns `false` when the slim-primitive gate rejects the write
682
- * (the value's primitive shape doesn't match the schema's slim
683
- * shape at the path). The store is unchanged in that case.
684
- */
685
- setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean;
686
- getValueAtPath(path: Path): unknown;
687
- /**
688
- * Stable identity for the array element at `path`. An array element
689
- * (numeric last segment) carries its allocated identity token,
690
- * maintained by `array-identity.ts` across structural mutations.
691
- * Empty for any non-array-element path: a record entry, a
692
- * fixed-object field, a container, or the root. Backs `FieldState.key`.
693
- */
694
- arrayElementKey(path: Path): string;
695
- reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void;
696
- resetField(path: Path): void;
697
- setSchemaErrorsForPath(path: Path, errors: ValidationError[]): void;
698
- setAllSchemaErrors(errors: readonly ValidationError[]): void;
699
- clearSchemaErrors(path?: Path): void;
700
- /**
701
- * Replace `schemaErrors` under `path` with `errors`, keying each
702
- * error by its OWN absolute path. Used by validation pipelines
703
- * (scheduleFieldValidation, validateAsync, handleSubmit, reset)
704
- * to commit a parse result wholesale — entries not in the new
705
- * pass get dropped from the subtree, surviving keys update in
706
- * place to preserve insertion order. Pass `path === []` for the
707
- * whole-form scope.
708
- */
709
- applySchemaErrorsForSubtree(path: Path, errors: ValidationError[]): void;
710
- setAllUserErrors(errors: readonly ValidationError[]): void;
711
- setUserErrorsForPath(path: Path, errors: readonly ValidationError[]): void;
712
- clearUserErrors(path?: Path): void;
713
- /**
714
- * Merged read — returns `[...schemaErrors[path], ...userErrors[path]]`.
715
- * Schema errors come first (structural validation before business logic),
716
- * matching the iteration order for `getFirstErrorElement` and the
717
- * top-level `errors` drillable Proxy.
718
- */
719
- getErrorsForPath(path: Path): ValidationError[];
720
- /**
721
- * Returns a stable schema-declaration ordinal for `key`, assigning a
722
- * fresh one if the path hasn't been seen before. Drives
723
- * `form.meta.errors` sort order so the aggregate is a function of the
724
- * SET of errors currently present (not the temporal order their
725
- * Map keys were last `set`). Construction-time seed walks every leaf
726
- * in the schema's slim default; runtime callers (DU variant 2, dynamic
727
- * array indices, refines targeting cross-field paths) pick up
728
- * first-encounter ordinals and keep them for the form's lifetime.
729
- */
730
- ensurePathOrdinal(key: PathKey): number;
731
- /**
732
- * Register `element` as a binding for `path`, tagged with the calling
733
- * `useForm()` instance's `formInstanceId`. The ID is the disambiguator
734
- * used by `getFirstErrorElement` to scope focus / scroll to elements
735
- * THIS form instance owns — important when two `useForm()` calls share
736
- * a `key` (e.g. sidebar + main rendering the same form), since both
737
- * write into one shared element store.
738
- */
739
- registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean;
740
- deregisterElement(path: Path, element: HTMLElement): number;
741
- /**
742
- * Optional `meta.instance` carries per-`useForm()`-instance overrides
743
- * for `validateOn` / `debounceMs` so the blur-trigger respects the
744
- * caller's config when sibling instances share a FormStore.
745
- */
746
- markFocused(path: Path, focused: boolean, meta?: {
747
- readonly instance?: WriteMeta['instance'];
748
- }): void;
749
- /**
750
- * Flip `interacted: true` on a leaf — the sticky value-mutation flag.
751
- * Driven by the directive's input listeners (via the RegisterValue's
752
- * `markInteracted`); idempotent, never set by programmatic writes.
753
- */
754
- markInteracted(path: Path): void;
755
- /**
756
- * Walk every active-variant leaf under `segments` and flip
757
- * `touched: true`. Powers `form.touch(path?)`. Idempotent;
758
- * does not mutate value / focused / blurred or trigger validation.
759
- */
760
- touchAtPath(segments: Path): void;
761
- /**
762
- * Walk every active-variant leaf under `segments` and flip the full
763
- * interaction ladder (`touched` / `interacted` /
764
- * `blurredAfterInteraction`), as though the user had focused,
765
- * edited, and left each one. Powers `form.interact(path?)`.
766
- * Idempotent; does not mutate value / focused / blurred. Returns
767
- * whether any leaf resolved, so the caller can skip validation and
768
- * dev-warn on an empty path.
769
- */
770
- interactAtPath(segments: Path): boolean;
771
- /**
772
- * SSR-only optimistic mark: flip `connected: true` on the field
773
- * record without an actual DOM element. Called by the `vRegisterHint`
774
- * compile-time transform via `RegisterValue.markConnectedOptimistically()`
775
- * for every element rendered with `v-register`. Idempotent + no-op on
776
- * the client (the directive's `created` hook is the authoritative
777
- * source there).
778
- */
779
- markConnectedOptimistically(path: Path): void;
780
- /**
781
- * Client-side connected mark for a `v-register` component host that binds
782
- * value via the v-model channel but has no single inner control to latch
783
- * (a composite widget, or none found). The directive calls it on mount
784
- * (`true`) and unmount (`false`). Distinct from the SSR-only
785
- * `markConnectedOptimistically`; idempotent on the leading edge.
786
- *
787
- * `hostEl` (the host root) is recorded on connect as this path's
788
- * focus-first-error anchor, scoped to `formInstanceId` the same way a
789
- * registered control is. A no-latch host enters no `elements` record, so
790
- * without this it is absent from `getFirstErrorElement`'s walk; the anchor
791
- * lets that walk resolve a focus target from the host subtree.
792
- */
793
- markHostConnected(path: Path, connected: boolean, hostEl: HTMLElement, formInstanceId: string): void;
794
- /**
795
- * Leaf-only pristine check. `originals` is populated via
796
- * `diffAndApply`'s `added` patches, which fire only on primitive
797
- * leaves — a container path (e.g. `['profile']`) that isn't in
798
- * `originals` returns `true` here even when a descendant is dirty.
799
- * Callers that need container semantics should either loop over
800
- * leaves or walk `originals` manually. The public `getFieldState`
801
- * surface is typed to accept leaf paths only, so in practice this
802
- * isn't exposed to consumers.
803
- */
804
- isPristineAtPath(path: Path): boolean;
805
- /**
806
- * Precomputed-key shortcut for `isPristineAtPath`. The canonical
807
- * key is required and must correspond to `segments`; the helper
808
- * skips the `canonicalizePath` round-trip so descendant-walk loops
809
- * (whose Map iteration already yields the canonical key) can read
810
- * the pristine verdict without a per-leaf canonicalize.
811
- */
812
- isPristineAtPathByKey(key: PathKey, segments: Path): boolean;
813
- /**
814
- * Whether any tracked array under `path` has changed shape — a reorder,
815
- * insert, or removal — relative to its construction/reset baseline. The
816
- * structural half of `dirty`: per-element baselines travel with their
817
- * element across a mutation, so a positional value comparison alone can
818
- * no longer see the shape change.
819
- */
820
- hasStructuralChangeUnder(path: Path): boolean;
821
- /**
822
- * Whether a baseline-present container under `path` was replaced wholesale by
823
- * a non-container (e.g. `setValue('profile', undefined)`) and is still absent.
824
- * The other half of removal-driven `dirty`: such a subtree's leaves vanish
825
- * from the live value, so neither the present-leaf walk nor the array tracker
826
- * can see the loss. Self-filters by current liveness, so a refilled path stops
827
- * counting.
828
- */
829
- hasRemovedSubtreeUnder(path: Path): boolean;
830
- getFieldRecord(path: Path): FieldRecord | undefined;
831
- getOriginalAtPath(path: Path): unknown;
832
- /**
833
- * Returns the first errored field's first connected, visible DOM
834
- * element scoped to `formInstanceId` — the target that
835
- * `focusFirstError` / `scrollToFirstError` act on. "First" is
836
- * VISUAL-first (DOM-tree order via `compareDocumentPosition`), not
837
- * schema-declaration order, so a field rendered above another in the
838
- * template focuses first regardless of which one the schema declared
839
- * earlier. CSS `order:` flexbox/grid reordering is NOT respected
840
- * (DOM-tree order wins) — documented as a tradeoff against forcing
841
- * sync layout on every comparison.
842
- *
843
- * The `formInstanceId` filter scopes focus to elements registered
844
- * through THIS form instance. When two `useForm({ key })` calls share
845
- * a key, both register into the same element store; without the
846
- * filter, the sidebar form's submit could focus the main form's
847
- * input. With it, each `useForm()` callsite focuses only its own
848
- * elements.
849
- *
850
- * Returns `null` when every errored path has no currently-attached
851
- * element registered to this instance (fields behind `v-if="false"`,
852
- * unmounted components, or a hidden `display:none` parent). Callers
853
- * get the choice of no-op or a dev-only warning.
854
- */
855
- getFirstErrorElement(formInstanceId: string): {
856
- path: Path;
857
- element: HTMLElement;
858
- } | null;
859
- /**
860
- * Cancel every in-flight field-level validation run — clears timers
861
- * for debounced 'change' runs that haven't fired, latches `aborted`
862
- * for runs whose async parse is in flight. Called by `handleSubmit`
863
- * at entry (submit validation is authoritative) and by `reset()`.
864
- */
865
- cancelFieldValidation(): void;
866
- /**
867
- * Open an async-transform run at `key` — bump the run token, increment
868
- * the in-flight counters, stamp `transformingSince`, clear any prior
869
- * `transformError`, register `holder` for later abort. Returns the run
870
- * token. See `InternalRegisterValue.beginTransform`.
871
- */
872
- beginTransform(key: PathKey, holder: TransformAbortHolder): number;
873
- /** `true` while `token` is the live async-transform run at `key`. */
874
- isCurrentTransform(key: PathKey, token: number): boolean;
875
- /**
876
- * Close the run `token` at `key`: release the counters (no-op if the
877
- * run was already released by a supersede / cancel) and flush settled
878
- * `settleTransforms` waiters.
879
- */
880
- endTransform(key: PathKey, token: number): void;
881
- /** Record a per-field normalization failure at `key` (`field.transformError`). */
882
- setTransformError(key: PathKey, err: Error): void;
883
- /**
884
- * Abort + release every in-flight async-transform run (all paths) and
885
- * clear `transformErrors`. Mirrors `cancelFieldValidation`; called by
886
- * `reset()` and store teardown.
887
- */
888
- cancelTransforms(): void;
889
- /**
890
- * Path-scoped counterpart to `cancelTransforms`: abort + release only
891
- * the runs at-or-under `prefix`, clearing their `transformError`.
892
- * Called by `resetField`.
893
- */
894
- cancelTransformsUnder(prefix: Path): void;
895
- /**
896
- * Resolve once async transforms are quiescent — globally (`path`
897
- * omitted) or at-or-under `path`. Resolve-never-reject. See
898
- * `UseFormReturnType.settleTransforms`.
899
- */
900
- settleTransforms(path?: string | Path): Promise<void>;
901
- /**
902
- * Kick off (or schedule) a field-level validation run for `path`. Pass
903
- * `path = []` to cover the whole form; `applySchemaErrorsForSubtree`
904
- * then wipes every `schemaErrors` entry and replaces them with the
905
- * adapter's full async response. Used by persistence's post-hydration
906
- * revalidation and by the construction-time async-refine seed.
907
- *
908
- * `immediate: true` skips the debounce window — the runtime kicks off
909
- * the adapter call on the next microtask. Internal callsites use this
910
- * for one-shot triggers; the per-keystroke writers pass `false` to
911
- * coalesce rapid mutations under the configured debounceMs.
912
- *
913
- * `override` carries per-`useForm()`-instance values: when provided,
914
- * the scheduler honors `override.mode` instead of the store's
915
- * captured `validateOn`, and `override.debounceMs` instead of the
916
- * store's captured `debounceMs`. Used so sibling instances sharing a
917
- * FormStore can each validate on their own cadence.
918
- */
919
- scheduleFieldValidation(path: Path, immediate: boolean, override?: {
920
- readonly mode?: ValidateOn;
921
- readonly debounceMs?: number;
922
- }): void;
923
- /**
924
- * Subscribe to every `applyFormReplacement`. Fires synchronously
925
- * after `form.value` has been swapped to `next` and all field /
926
- * originals bookkeeping has run. Used by undo/redo to hook the single
927
- * mutation funnel. The optional `meta` carries the originating call
928
- * site's intent; subscribers that don't care about meta can ignore the
929
- * parameter. Returns an unsubscribe function.
930
- */
931
- onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void;
932
- /**
933
- * Subscribe to successful submissions. Fires after the consumer's
934
- * `onSubmit` callback has resolved — not on validation failure,
935
- * not on callback throw. The DevTools panel rides this to surface a
936
- * submit event. Returns an unsubscribe function.
937
- */
938
- onSubmitSuccess(listener: () => void): () => void;
939
- /**
940
- * Subscribe to `reset()` calls. Fires AFTER reset has replaced
941
- * the form and cleared errors + lifecycle, so listeners see the
942
- * fresh post-reset state. Used by the history module to drop the
943
- * undo/redo stack on reset. Returns an unsubscribe function.
944
- */
945
- onReset(listener: () => void): () => void;
946
- /**
947
- * Internal: notify submit-success subscribers. Called by
948
- * `handleSubmit` in `process-form.ts` once the user callback has
949
- * resolved. Consumers shouldn't call this directly.
950
- */
951
- emitSubmitSuccess(): void;
952
- /**
953
- * Register a teardown function whose lifetime is bound to the
954
- * FormStore itself (not a consumer's Vue effect scope). Called by
955
- * `dispose()` when the last consumer unmounts. Used by persistence /
956
- * history wiring so their subscribers aren't detached prematurely
957
- * when only the first consumer unmounts but others remain.
958
- */
959
- registerCleanup(fn: () => void): void;
960
- /**
961
- * Register an async drain function. Called by the registry before
962
- * `dispose()` so async background work — chiefly the persistence
963
- * layer's debounced storage writes — has a chance to settle without
964
- * losing the last keystroke. Each registered function is awaited in
965
- * parallel; failures are swallowed to keep eviction reliable.
966
- */
967
- registerDrain(fn: () => Promise<void>): void;
968
- /**
969
- * Drain async work registered via `registerDrain`. Resolves once
970
- * every registered drain has settled (in parallel). Safe to call
971
- * repeatedly — registered drains decide their own idempotency.
972
- */
973
- awaitPendingWrites(): Promise<void>;
974
- /**
975
- * Cache for per-state modules (history, persistence) that must
976
- * outlive any single consumer. Subsequent `useForm` / `injectForm`
977
- * calls for the same key read from this map so the public API shape
978
- * is identical regardless of mount order. Keyed by a string identifier
979
- * owned by the caller (e.g. `'history'`).
980
- */
981
- readonly modules: Map<string, unknown>;
982
- /**
983
- * Resolved schema-coercion index — the merged config from
984
- * `createAttaform({ defaults: { coerce } })` ∪ `useForm({ coerce })`,
985
- * keyed by `${input}->${output}` for O(1) per-keystroke dispatch.
986
- * Empty Map when coercion is disabled. Read at `register()` time
987
- * by `buildCoerceFn` to bake the per-path coerce closure on
988
- * `RegisterValue.coerce`.
989
- */
990
- readonly coerceIndex: CoercionIndex;
991
- /**
992
- * Tear down non-reactive resources owned by this FormStore. Invoked
993
- * by the registry when the last consumer unmounts. Cancels pending
994
- * field-validation timers, drops every subscriber, and fires each
995
- * cleanup hook registered via `registerCleanup`.
996
- */
997
- dispose(): void;
998
- };
999
-
1000
- /**
1001
- * Public types for `useWizard` — the multistep-form orchestrator.
1002
- *
1003
- * The wizard is built around an ordered list of step slots. Each slot
1004
- * resolves to a participating form: an existing `useForm` reference, a
1005
- * bare string key (desugared to a noop form so affordance steps
1006
- * participate uniformly), an eagerly-evaluated function slot for
1007
- * runtime branching, or a `lazy()`-wrapped function slot that caches
1008
- * its resolution and re-fires only on its own tracked deps.
1009
- *
1010
- * The wizard surface is loosely keyed (`Record<FormKey, …>`).
1011
- * Cross-component flows threaded through `injectWizard` lose lexical
1012
- * key knowledge anyway, so the public read surface is a string-keyed
1013
- * record. Typed per-form access flows back through the original form
1014
- * refs and through `wizard.handleSubmit`'s `ctx.get(formRef)` accessor.
1015
- */
1016
-
1017
- /**
1018
- * Minimum structural shape the wizard requires from a participating
1019
- * form. Constraining to the full `UseFormReturnType` would force
1020
- * contravariant unification of the storage / read shapes across all
1021
- * steps; the wizard does not care about those — it routes by `key` at
1022
- * runtime and exposes the original form objects untouched.
1023
- */
1024
- type AnyForm = {
1025
- readonly key: FormKey;
1026
- };
1027
- /**
1028
- * Per-form summary surface — what `wizard.statuses[key]` exposes (and
1029
- * what `defaultStatuses` seeds). Distinct from `form.meta`: `FormStatus`
1030
- * is the cross-step rollup optimized for template ergonomics
1031
- * (`{{ wizard.statuses.cargo.valid }}`), while `form.meta` carries the
1032
- * full per-form lifecycle surface.
1033
- *
1034
- * Field semantics:
1035
- * - `valid` — `form.meta.valid`. `false` while errors exist or while
1036
- * the first-validation-done gate has not flipped.
1037
- * - `dirty` — `form.meta.dirty`. `true` once any value differs from
1038
- * the original defaults.
1039
- * - `submitted` — `form.meta.submitted`. `true` once a `handleSubmit`
1040
- * callback has resolved without throwing. A failed submit
1041
- * (validation or callback rejection) leaves this `false`;
1042
- * `submissionAttempts > 0` is the "user has tried" signal.
1043
- * - `errorCount` — `form.meta.errorCount`. Count of active validation
1044
- * errors (zero when valid).
1045
- * - `locked`: `true` when this step sits after an uncleared gate. Its
1046
- * member form is frozen (data writes no-op) and navigation to it is
1047
- * refused, so a stepper can render it as an unreachable step. `false`
1048
- * when no gate seals it. Orthogonal to `gate`: the first uncleared
1049
- * gate reads `locked: false` (you must reach it to clear it), while a
1050
- * later gate sealed behind it reads both `gate: 'uncleared'` and
1051
- * `locked: true`.
1052
- * - `gate`: this step's own role as a hard prerequisite. `null` when the
1053
- * step is not a `gate()`; `'uncleared'` while its member form is
1054
- * unconfirmed (so it seals every later step); `'cleared'` once
1055
- * confirmed by a clean member submit or seeded cleared via
1056
- * `defaultStatuses`. Reflects the live compiled shape, so a conditional
1057
- * `gate()` that a function slot drops resolves to `null`.
1058
- *
1059
- * Noop forms generated for string slots surface as default-valid
1060
- * (`{ valid: true, dirty: false, submitted: false, errorCount: 0, locked: false, gate: null }`),
1061
- * unless the string slot is a `gate('...')`, whose `gate` tracks the
1062
- * in-session acknowledgment.
1063
- */
1064
- type FormStatus = {
1065
- readonly valid: boolean;
1066
- readonly dirty: boolean;
1067
- readonly submitted: boolean;
1068
- readonly errorCount: number;
1069
- readonly locked: boolean;
1070
- readonly gate: 'cleared' | 'uncleared' | null;
1071
- };
1072
- /**
1073
- * Seed shape accepted by `useWizard({ defaultStatuses })`. Every field is
1074
- * optional; an omitted meta field falls back to the pending sentinel on
1075
- * read.
1076
- *
1077
- * `locked` is never accepted: it is purely live-derived (sealed behind an
1078
- * earlier uncleared gate) and overlaid on every status read, so a seeded
1079
- * value would be ignored.
1080
- *
1081
- * `gate` is a WRITE-only seed, not a status field echoed back on read. A
1082
- * seed of `'cleared'` latches the gate's cleared state once at construction
1083
- * (an SSR restore of a confirmed prerequisite); the live `gate` overlay
1084
- * then owns the read. `'uncleared'` is the default and seeds nothing. Only
1085
- * a step that compiles to a `gate()` honors it — other keys ignore it.
1086
- */
1087
- type FormStatusSeed = {
1088
- readonly valid?: boolean;
1089
- readonly dirty?: boolean;
1090
- readonly submitted?: boolean;
1091
- readonly errorCount?: number;
1092
- readonly gate?: 'cleared' | 'uncleared';
1093
- };
1094
- /**
1095
- * Flat error shape returned per form by `wizard.allErrors[key]`. Each
1096
- * entry carries the formKey + path tuple so consumers can route to the
1097
- * offending field from a wizard-wide error summary.
1098
- */
1099
- type WizardAggregateError = {
1100
- readonly formKey: FormKey;
1101
- readonly path: ReadonlyArray<string | number>;
1102
- readonly message: string;
1103
- readonly code?: string;
1104
- };
1105
- /**
1106
- * Mirror of `form.values`' call-or-read pattern, one level deep.
1107
- * Drillable as `wizard.statuses.cargo.valid` (readable), as
1108
- * `wizard.statuses('cargo')` (callable single-key), or as
1109
- * `wizard.statuses()` (callable no-arg returns the whole record).
1110
- */
1111
- type WizardStatusesProxy<S extends Record<string, FormStatus>> = ((key?: keyof S) => FormStatus | S) & Readonly<S>;
1112
- /**
1113
- * One compiled position in the wizard's flow. The wizard surface
1114
- * exposes an ordered array of these as `wizard.steps`, plus a
1115
- * `wizard.forms` record keyed by `step.key` for direct lookup.
1116
- *
1117
- * String slots in the source `steps` array desugar to noop forms
1118
- * before compilation, so every compiled step carries a `form`
1119
- * regardless of source kind.
1120
- */
1121
- type CompiledStep = {
1122
- readonly key: FormKey;
1123
- readonly form: AnyForm;
1124
- };
1125
- /**
1126
- * Shape of a participating form as seen from inside a function slot's
1127
- * `ctx.forms[key]` lookup. Adds `values` to the structural `AnyForm`
1128
- * minimum so routing decisions can read live form state.
1129
- *
1130
- * Values are typed loose because the wizard does not generically thread
1131
- * each step's schema through `ctx.forms`. For typed access inside slot
1132
- * bodies, close over the original form ref instead of routing through
1133
- * `ctx.forms`.
1134
- */
1135
- type WizardCtxForm = AnyForm & {
1136
- readonly values: Readonly<Record<string, unknown>>;
1137
- };
1138
- /**
1139
- * Context object passed to function slots in the `steps` array. The
1140
- * `forms` record exposes the wizard's statically-known forms (every
1141
- * top-level `AnyForm` slot plus every noop form synthesized for a
1142
- * top-level string slot). `currentKey` mirrors the live wizard step.
1143
- *
1144
- * Function slots re-evaluate reactively when the values they read
1145
- * mutate (typically `ctx.forms.<key>.values.<path>`). The `forms`
1146
- * accumulator itself is stable across re-evaluations so the slot's
1147
- * lookup identity stays referentially equal. Effectful slot bodies
1148
- * should be avoided; routing decisions live here.
1149
- */
1150
- type WizardCtx = {
1151
- readonly forms: Readonly<Record<FormKey, WizardCtxForm>>;
1152
- readonly currentKey: FormKey | undefined;
1153
- };
1154
- /**
1155
- * What a function slot or a `lazy()` / `gate()` resolver may yield: a
1156
- * participating form, a bare affordance key, a nested `lazy()` / `gate()`
1157
- * wrapper (so the two compose in either order), or `null` / `undefined`
1158
- * to drop the position from the compiled list.
1159
- */
1160
- type SlotResolution<Ctx = WizardCtx> = AnyForm | string | null | undefined | LazyMarker<Ctx> | GateMarker;
1161
- /**
1162
- * Internal phantom brand for `LazyMarker`. The runtime brand symbol
1163
- * lives in `core/wizard-lazy.ts`; this declaration keeps the marker
1164
- * type unforgeable without circular module imports.
1165
- */
1166
- declare const _lazyBrand: unique symbol;
1167
- /**
1168
- * Brand-typed marker returned by `lazy((ctx) => …)`. Wrapping a
1169
- * function slot in `lazy()` gives that slot its own memoization cache:
1170
- * the resolver fires once on the first compile pass, and the result
1171
- * stays cached until one of the resolver's own tracked reactive reads
1172
- * changes (or `wizard.reset()` invalidates the cache). Heavy or
1173
- * one-shot lookups (network-backed factories, expensive derivations)
1174
- * do not re-fire because an unrelated slot's deps changed.
1175
- *
1176
- * Construct via the `lazy()` helper exported from the same entry as
1177
- * `useWizard`. The marker is opaque at the type level; consumers do
1178
- * not assemble it directly.
1179
- */
1180
- type LazyMarker<Ctx = WizardCtx> = {
1181
- readonly [_lazyBrand]: true;
1182
- readonly resolve: (ctx: Ctx) => SlotResolution<Ctx>;
1183
- };
1184
- /**
1185
- * Internal phantom brand for `GateMarker`. The runtime brand symbol
1186
- * lives in `core/wizard-gate.ts`; this declaration keeps the marker
1187
- * type unforgeable without circular module imports.
1188
- */
1189
- declare const _gateBrand: unique symbol;
1190
- /**
1191
- * Brand-typed marker returned by `gate(step)`. Wrapping a slot in
1192
- * `gate()` makes it a hard prerequisite: an uncleared gate seals every
1193
- * step positioned after it, and the gate's own form is the only way
1194
- * past. A gate clears on a member form's clean submit (confirmation),
1195
- * never on a value merely going valid (intent), and its form freezes
1196
- * once cleared so a back-navigation is a read-only review.
1197
- *
1198
- * `Inner` carries the wrapped slot's static type so `gate` stays
1199
- * transparent to the type machinery: `gate(form)` still contributes the
1200
- * form's key to `wizard.forms` and still counts as a guaranteed step,
1201
- * while `gate(lazy(fn))` stays maybe-absent exactly like the lazy slot
1202
- * it wraps. See {@link UnwrapGate}.
1203
- *
1204
- * Construct via the `gate()` helper exported from the same entry as
1205
- * `useWizard`. The marker is opaque at the type level; consumers do not
1206
- * assemble it directly.
1207
- */
1208
- type GateMarker<Inner = unknown> = {
1209
- readonly [_gateBrand]: true;
1210
- readonly inner: Inner;
1211
- };
1212
- /**
1213
- * Strip every `gate()` wrapper off a slot type, exposing the inner
1214
- * slot's static shape. A gate is identity-on-shape — it changes runtime
1215
- * reachability, never the compiled type — so the forms map and the
1216
- * non-empty-tuple predicate both unwrap it before inspecting a slot.
1217
- * Recursive, so a doubly-wrapped `gate(gate(form))` still resolves to
1218
- * `form`. This is what makes `gate(lazy(s))` and `lazy((ctx) => gate(s))`
1219
- * agree at the type level as well as at runtime.
1220
- */
1221
- type UnwrapGate<T> = T extends GateMarker<infer Inner> ? UnwrapGate<Inner> : T;
1222
- /**
1223
- * One position in the source `useWizard({ steps })` array. Each slot
1224
- * resolves to a compiled `{ key, form }` step, or drops out:
1225
- *
1226
- * - `AnyForm` — a form declared via `useForm`. Surfaced as-is.
1227
- * - `string` — bare key. The wizard generates a noop form
1228
- * under the hood so the external surface stays
1229
- * uniform across affordance positions (intro,
1230
- * terms, congratulations, review surfaces).
1231
- * - `null` / `undefined` — a literal absence, dropped from the compiled
1232
- * list. Lets a conditional step read inline as
1233
- * `cond ? form : null` without pre-filtering the
1234
- * array.
1235
- * - function — eager slot, re-evaluates reactively. Returns a
1236
- * `SlotResolution`, or `null` / `undefined` to
1237
- * drop the slot from the compiled list.
1238
- * - `LazyMarker` — memoized function slot (see `lazy`).
1239
- * - `GateMarker` — hard-prerequisite wrapper (see `gate`). Wraps
1240
- * any of the above; transparent to the compiled
1241
- * step's type, opaque to reachability.
1242
- */
1243
- type StepSlot<Ctx = WizardCtx> = AnyForm | string | null | undefined | ((ctx: Ctx) => SlotResolution<Ctx>) | LazyMarker<Ctx> | GateMarker;
1244
- /**
1245
- * Shape returned by the `restore` callback. Carries the active step's
1246
- * key; intentionally open-ended (object form) so future additions land
1247
- * without a callback-signature break.
1248
- */
1249
- type WizardRestoreState = {
1250
- readonly step?: FormKey;
1251
- };
1252
- /**
1253
- * `restore` callback signature. Invoked at construction and watched
1254
- * reactively via `watchEffect` so external state changes (browser
1255
- * back/forward, cross-tab events, route changes) re-apply through the
1256
- * wizard. Returning `undefined` falls through to the first step.
1257
- */
1258
- type WizardRestoreFn = () => WizardRestoreState | undefined;
1259
- /**
1260
- * `persist` callback signature. Invoked whenever `wizard.currentStep`
1261
- * changes; the wizard diffs against the last persisted value to break
1262
- * the restore-persist loop, so the callback only fires when the active
1263
- * step actually moves.
1264
- */
1265
- type WizardPersistFn = (state: WizardRestoreState) => void;
1266
- /**
1267
- * Submit context passed to the `onSubmit` callback registered via
1268
- * `wizard.handleSubmit(onSubmit, onError?)`. `handleSubmit` always
1269
- * processes the whole step list, so `values` carries every form's
1270
- * parsed output regardless of which step fired the submit.
1271
- *
1272
- * - `values` — namespaced aggregate keyed by form key, mirroring
1273
- * `wizard.allValues`. Reflects parsed output for every
1274
- * form whose validation has settled; noops contribute an
1275
- * empty record.
1276
- * - `get(form)` — typed accessor that reads the parsed output for a
1277
- * specific form ref. Works across cross-component graphs
1278
- * because the form ref carries its schema info.
1279
- * - `currentKey` — key of the step that fired this submission.
1280
- * - `isFinal` — `true` when `currentKey` is the last position in
1281
- * `wizard.steps`. Positional only: it reports where the
1282
- * submit fired, never what got validated. A user who steps
1283
- * back, edits, and submits from the middle sees
1284
- * `isFinal === false`, yet the whole list is still
1285
- * processed and `done` still latches on success.
1286
- */
1287
- type WizardSubmitContext = {
1288
- readonly values: Readonly<Record<FormKey, unknown>>;
1289
- readonly get: <F extends AnyForm>(form: F) => F extends {
1290
- readonly values: infer V;
1291
- } ? V : unknown;
1292
- readonly currentKey: FormKey;
1293
- readonly isFinal: boolean;
1294
- };
1295
- /**
1296
- * `onSubmit` callback registered via `wizard.handleSubmit`. Sync or
1297
- * async; the returned promise gates `wizard.submitting`.
1298
- */
1299
- type WizardOnSubmit = (ctx: WizardSubmitContext) => void | Promise<void>;
1300
- /**
1301
- * Optional `onError` callback registered via `wizard.handleSubmit`.
1302
- * Receives the aggregate error list spanning EVERY step (handleSubmit
1303
- * validates the whole wizard), so a failed submit surfaces every form's
1304
- * errors at once, not just the active step's. Entries originate from
1305
- * per-form validation, activation failures (`atta:activation-failed`),
1306
- * and a submit callback that left errors on a processed step (the
1307
- * `setErrors(...); return` server-rejection path). Sync or async; the
1308
- * returned promise gates `wizard.submitting`.
1309
- */
1310
- type WizardOnError = (errors: readonly WizardAggregateError[]) => void | Promise<void>;
1311
- /**
1312
- * Options for `useWizard({ steps, … })`. `steps` is the only required
1313
- * field; the rest are optional and default sensibly for the common
1314
- * URL-synchronized wizard case.
1315
- */
1316
- type WizardOptions = {
1317
- /**
1318
- * Ordered list of slots that compile into the wizard's positional
1319
- * step list. See `StepSlot` for the per-slot shape contract.
1320
- */
1321
- readonly steps: ReadonlyArray<StepSlot>;
1322
- /**
1323
- * Identifier used to register the wizard handle in the per-app
1324
- * registry. Descendant components call `injectWizard(key)` to reach
1325
- * the same wizard without prop-threading. Anonymous wizards (option
1326
- * omitted) get a synthetic `__atta:anon-wizard:<id>` key resolved
1327
- * via `useId()` so SSR-rendered and client-hydrated trees agree on
1328
- * the same registry entry; the synthetic key is opaque and
1329
- * descendants reach an anonymous wizard via ambient `injectWizard()`
1330
- * rather than by key.
1331
- *
1332
- * Duplicate-key registration is first-wins-silently (dev-warn on the
1333
- * second registration) to mirror `useForm`'s shared-key behavior.
1334
- * The dev-warn fires only for explicit keys — two anonymous wizards
1335
- * are guaranteed distinct synthetic keys, so the warning never
1336
- * misfires on independent anonymous wizards on the same page.
1337
- */
1338
- readonly key?: string;
1339
- /**
1340
- * Seed status payload used while a form is pre-resolved (async
1341
- * `defaultValues` in flight, or wizard-deferred non-current).
1342
- * Mirrors `defaultValues`' trichotomy: plain object, sync factory,
1343
- * or async factory.
1344
- *
1345
- * Status resolution priority per form:
1346
- * 1. `store.defaultsResolved === true` → derive from `form.meta`
1347
- * 2. else noop form → built-in always-valid status
1348
- * 3. else seed value for this key → seed over the pending sentinel
1349
- * 4. else → pending sentinel
1350
- *
1351
- * `locked` is never seeded: it is computed live from the wizard's gates
1352
- * and overlaid on every status read. `gate: 'cleared'` IS honored, but as
1353
- * a one-shot seed of the gate's cleared latch at construction (an SSR
1354
- * restore of a confirmed prerequisite), not as a status field echoed on
1355
- * read — the live `gate` overlay owns the read. Only a step that compiles
1356
- * to a `gate()` honors it. See `FormStatusSeed`.
1357
- *
1358
- * SSR note: the async factory resolves after hydration (client-only), so
1359
- * a gate seeded through it clears post-hydration. For a gate that must
1360
- * render open on the first server byte, use the plain or sync-factory
1361
- * form (resolve server truth in the page's `setup` await).
1362
- *
1363
- * Unknown keys in the seed object dev-warn so a stale resume payload
1364
- * surfaces at construction.
1365
- */
1366
- readonly defaultStatuses?: Record<string, FormStatusSeed> | (() => Record<string, FormStatusSeed>) | (() => Promise<Record<string, FormStatusSeed>>);
1367
- /**
1368
- * Optional progress override. When omitted, the wizard exposes
1369
- * `progress` as `valid_step_count / count` (normalised to `[0, 1]`).
1370
- * When provided, the returned number is used as-is — the consumer is
1371
- * responsible for any normalisation.
1372
- *
1373
- * The override is invoked inside a Vue `computed` so it must be
1374
- * synchronous and may only read reactive sources.
1375
- */
1376
- readonly progress?: (steps: ReadonlyArray<CompiledStep>) => number;
1377
- /**
1378
- * When `wizard.handleSubmit` finds errors, automatically focus the
1379
- * first failing form: jump to its step and invoke its
1380
- * `applyInvalidSubmitPolicy()` (focus / scroll per the form's own
1381
- * `onInvalidSubmit` configuration). Default `true`; pass `false` to
1382
- * keep the active step where the user left it and handle navigation
1383
- * manually in the `onError` callback.
1384
- */
1385
- readonly focusFirstError?: boolean;
1386
- /**
1387
- * Source of truth for the active step. Invoked at construction and
1388
- * re-evaluated reactively via `watchEffect`. Default callback reads
1389
- * `?step=<key>` from the URL via `wizard-history.ts`; pass `false`
1390
- * to disable URL sync, or provide a custom callback for non-router
1391
- * persistence (localStorage, broadcast channel, etc.).
1392
- */
1393
- readonly restore?: WizardRestoreFn | false;
1394
- /**
1395
- * Destination for the active step. Invoked whenever `currentStep`
1396
- * changes, with a diff check to break the restore-persist loop.
1397
- * Default callback writes `?step=<key>` via `wizard-history.ts`;
1398
- * pass `false` to disable persistence, or provide a custom callback
1399
- * to scope the param name or write to alternate storage.
1400
- */
1401
- readonly persist?: WizardPersistFn | false;
1402
- };
1403
- /**
1404
- * True when a single slot is guaranteed to contribute exactly one
1405
- * compiled step: a bare form or affordance string that is neither
1406
- * nullish nor a (maybe-absent) function / `lazy()` slot. One of these
1407
- * anywhere in the tuple proves the compiled list is non-empty.
1408
- */
1409
- type IsGuaranteedStep<T, U = UnwrapGate<T>> = [null] extends [U] ? false : [undefined] extends [U] ? false : U extends LazyMarker | ((...args: unknown[]) => unknown) ? false : U extends string ? true : U extends {
1410
- readonly key: string;
1411
- } ? true : false;
1412
- /**
1413
- * Predicate: is the steps tuple statically guaranteed to compile to a
1414
- * non-empty list? True when at least one element is a guaranteed step
1415
- * (see `IsGuaranteedStep`). Function / `lazy()` slots may resolve to
1416
- * nothing, and `null` / `undefined` (a literal absence or a
1417
- * `cond ? form : null` union) is an explicit drop, so none of those
1418
- * prove non-emptiness; a tuple of only maybe-absent slots stays
1419
- * honestly `| undefined`.
1420
- *
1421
- * Used to narrow `currentStep` / `activeForm` to their non-`undefined`
1422
- * shapes in the common-case wizard, while keeping the honest union
1423
- * everywhere a runtime drop is reachable.
1424
- */
1425
- type StaticallyNonEmpty<S> = S extends readonly [infer First, ...infer Rest] ? IsGuaranteedStep<First> extends true ? true : StaticallyNonEmpty<Rest> : false;
1426
- /** Active step's key, narrowed to `string` when `S` is statically safe. */
1427
- type CurrentStepOf<S> = StaticallyNonEmpty<S> extends true ? FormKey : FormKey | undefined;
1428
- /**
1429
- * Active step's form handle, schema-erased to `UseFormReturnType<GenericForm>`
1430
- * and narrowed to non-`undefined` when `S` is statically safe. The runtime
1431
- * value is a live facade over the active step, so reads (`.values`, `.meta`,
1432
- * `.history`) and `.handleSubmit` always target the current step. Values are
1433
- * loose here because the active step's schema is not statically known; reach
1434
- * for the original form ref or `ctx.get(ref)` when you need typed per-step
1435
- * values.
1436
- */
1437
- type ActiveFormOf<S> = StaticallyNonEmpty<S> extends true ? UseFormReturnType<GenericForm> : UseFormReturnType<GenericForm> | undefined;
1438
- /**
1439
- * Per-slot contribution to {@link FormsRecordOf}. Unwraps a `gate()`
1440
- * wrapper (transparent to the compiled type) and strips a `null` /
1441
- * `undefined` (a literal absence or a `cond ? form : null` union) off the
1442
- * slot first, so both a conditionally-present form and a `gate(form)`
1443
- * still map to their key and stay concretely typed on `wizard.forms`; a
1444
- * purely nullish slot contributes nothing.
1445
- */
1446
- type SlotRecord<First, U = UnwrapGate<First>, F = Exclude<U, null | undefined>> = [F] extends [
1447
- never
1448
- ] ? unknown : F extends string ? {
1449
- readonly [P in F]: AnyForm;
1450
- } : F extends {
1451
- readonly key: infer K extends string;
1452
- } ? {
1453
- readonly [P in K]: F;
1454
- } : unknown;
1455
- /**
1456
- * Recursive tuple walk that builds the static portion of
1457
- * `wizard.forms`. Each step slot contributes to the record:
1458
- *
1459
- * - **String slot** (`'review'`): the literal becomes the record key
1460
- * and the value is `AnyForm` (the noop form synthesized for the
1461
- * affordance position is opaque at the type level).
1462
- * - **Form slot** (a `useForm` reference with a literal `key` field):
1463
- * the form's own `key` becomes the record key, and the value is
1464
- * the concrete form handle type — so drilling
1465
- * `wizard.forms.shipping.values.address` carries the schema-derived
1466
- * field types through. A form kept behind a `cond ? form : null`
1467
- * conditional still maps to its key.
1468
- * - **`null` / `undefined` slot**: contributes nothing.
1469
- * - **Function / `lazy()` slot**: contributes nothing to the static
1470
- * map. Runtime-resolved forms are still reachable via the
1471
- * catch-all index signature on `WizardForms` (typed as `AnyForm`).
1472
- * - **`gate()` slot**: transparent — unwrapped to the slot it wraps, so
1473
- * `gate(form)` contributes the form's key and `gate(lazy(fn))`
1474
- * contributes nothing, exactly like the wrapped slot on its own.
1475
- *
1476
- * Recursion is bounded by the tuple length; real-world wizards land
1477
- * well below the TS instantiation budget.
1478
- */
1479
- type FormsRecordOf<S> = S extends readonly [
1480
- infer First,
1481
- ...infer Rest extends ReadonlyArray<StepSlot>
1482
- ] ? SlotRecord<First> & FormsRecordOf<Rest> : unknown;
1483
- /**
1484
- * `wizard.forms` typed view. Combines the static per-step type map
1485
- * with a catch-all `Record<FormKey, AnyForm>` fallback so:
1486
- *
1487
- * - Statically known slot keys → concrete form type via `FormsRecordOf`
1488
- * - Any other string key → `AnyForm` via the index signature
1489
- *
1490
- * The intersection collapses to the concrete form for statically
1491
- * known keys (because the concrete form type extends `AnyForm`) and
1492
- * to `AnyForm` for unknown keys.
1493
- */
1494
- type WizardForms<S> = FormsRecordOf<S> & Readonly<Record<FormKey, AnyForm>>;
1495
- /**
1496
- * Return shape of `useWizard({ steps, … })`. Every reactive read is a
1497
- * plain getter (no `.value`) — `wizard.currentStep`, `wizard.progress`,
1498
- * `wizard.allValues` track inside `computed` / template effects
1499
- * directly.
1500
- *
1501
- * Parameterized by the steps tuple `S` so active-position fields
1502
- * (`currentStep`, `activeForm`) narrow to non-undefined for the common
1503
- * case (all positional Form / string slots) and stay as honest unions
1504
- * when a function or `lazy()` slot can drop the compiled position at
1505
- * runtime. The `const` type parameter on `useWizard` preserves literal
1506
- * tuple types without consumer-side `as const`, so the narrowing
1507
- * happens automatically from the call site.
1508
- *
1509
- * - `currentStep` — key of the active step. Narrows to `string` when
1510
- * the steps tuple is statically guaranteed to
1511
- * compile to a non-empty list (all positional
1512
- * Form / string slots, no function or `lazy()`
1513
- * slots). Otherwise reads as `string | undefined`
1514
- * so the degenerate case (empty list at runtime)
1515
- * surfaces honestly.
1516
- * - `activeForm` — a LIVE view of the active step's form. Operating
1517
- * through it always targets the current step, so a
1518
- * handler captured once at setup
1519
- * (`wizard.activeForm.handleSubmit(() =>
1520
- * wizard.next())`) retargets as the wizard advances.
1521
- * No longer `===` the raw per-step handle; reach for
1522
- * `wizard.forms[key]` when you need raw identity.
1523
- * Same `undefined` narrowing as `currentStep`. Noop
1524
- * forms cover string slots in the normal path.
1525
- * - `activeIndex` — 0-based position of the active step.
1526
- * - `isFinalStep` — `true` when `currentStep === steps[count - 1].key`.
1527
- * - `steps` — ordered list of compiled `{ key, form }` slots.
1528
- * - `forms` — record indexable by step key; the value is the
1529
- * full form handle resolved for that slot.
1530
- * - `count` — `steps.length`.
1531
- * - `statuses` — callable readonly proxy over the per-key
1532
- * `FormStatus` record. Noop-form keys always read
1533
- * as default-valid.
1534
- * - `allValues` — namespaced aggregate of each form's values, keyed
1535
- * by step key.
1536
- * - `allErrors` — namespaced aggregate of each form's validation
1537
- * errors, keyed by step key. Noop forms map to an
1538
- * empty list.
1539
- * - `progress` — normalised step-validity ratio (or the consumer's
1540
- * `progress` override). Forward-looking: noops count
1541
- * as always-valid.
1542
- * - `canAdvance` — `true` when `activeIndex < count - 1`. Pure
1543
- * positional check; navigation never gates on
1544
- * validity.
1545
- * - `canGoBack` — `true` when `activeIndex > 0`.
1546
- * - `complete` — `isFinalStep && every step's form is valid`.
1547
- * Forward-looking; reactive to current form
1548
- * validity. Gates "Finish button enable" style UI.
1549
- * - `done` — monotonic latch: flips `true` the first time a
1550
- * `handleSubmit` resolves without throwing AND leaves
1551
- * no errors set on any step, and stays `true` through
1552
- * subsequent edits or invalidations. A callback that
1553
- * calls `setErrors` and returns (the documented
1554
- * server-rejection path) is a failed submit, so it
1555
- * does not flip `done`. Only `reset()` flips it back.
1556
- * Gates "show success card" style UI that should
1557
- * reflect submission history rather than current
1558
- * validity.
1559
- * - `submitting` — `true` while a `wizard.handleSubmit` call is in
1560
- * flight. Global re-entrance guard: every
1561
- * navigation method also refuses while this is on.
1562
- * - `submissionAttempts` — count of `wizard.handleSubmit` invocations
1563
- * (success or failure). Always bumps, including on
1564
- * noop-form steps.
1565
- * - `submitError` — the error THROWN by the most recent
1566
- * `wizard.handleSubmit` callback (or its `onError`),
1567
- * coerced to a real `Error`. Mirrors
1568
- * `form.meta.submitError`: this is the unexpected-throw
1569
- * channel, so an expected rejection handled via
1570
- * `setErrors` (no throw) surfaces through the error
1571
- * surface and `onError` instead, leaving this `null`.
1572
- * Cleared at submit entry and by `reset()`, parked here
1573
- * rather than re-thrown, so the handler resolves and
1574
- * never manufactures a `window` unhandledrejection.
1575
- * `null` on success.
1576
- * - `visited` — append-only breadcrumb of navigated step keys.
1577
- * `back()` does not pop; the trail is the audit
1578
- * log, not the back-stack.
1579
- * - `next/back/goTo` — pure navigation. Refuses while `submitting`.
1580
- * - `tryNext()` — submit the active step, and once that submit
1581
- * resolves clean, advance; invalid input keeps the pin
1582
- * put under the form's standard error reveal (first
1583
- * error focused, display state advanced). The advance
1584
- * runs after the submit settles, so a `gate()` on the
1585
- * active step clears in a single call. Inline-bindable
1586
- * (`@click="wizard.tryNext()"`); resolves to whether
1587
- * the pin moved. No-ops to `false` on a degenerate or
1588
- * final-step wizard (finish via `handleSubmit`).
1589
- * - `handleSubmit(onSubmit, onError?)` — always validates the entire
1590
- * step list, from any step, and never advances the
1591
- * pin: on success it latches `done`; on any error it
1592
- * focuses the first failing step and fires `onError`
1593
- * with errors spanning every step. To gate advancing
1594
- * a step on its own validity, compose with the active
1595
- * form's submit: `activeForm.handleSubmit(() =>
1596
- * wizard.next())`. Returns an event handler suitable
1597
- * for `<form @submit>` or imperative use.
1598
- * - `reset()` — zeros wizard lifecycle (`submissionAttempts`,
1599
- * `visited`), resets every form, returns
1600
- * `currentStep` to `steps[0].key`, and invokes
1601
- * `persist` with the cleared state. Re-applies the
1602
- * `defaultStatuses` gate seed, so a reboot returns to
1603
- * the seeded initial clearance, not fully sealed.
1604
- * - `relock(key, commit)` — re-seal a cleared gate, contingent on
1605
- * `commit`. Awaits `commit` (a server-side revoke) and
1606
- * re-seals only if it resolves clean, so the gate reflects
1607
- * server-confirmed truth the same way a clearing submit
1608
- * does; a thrown `commit` leaves it as-is. Seal-only (never
1609
- * opens a gate), so it cannot become the leading-signal
1610
- * foot-gun `gate()` exists to prevent. `commit` is required
1611
- * (pass `() => {}` for a deliberate client-only re-seal).
1612
- * Resolves whether the gate ended up sealed; never rejects.
1613
- * Resolves `false` (dev-warn) on a non-gate key.
1614
- */
1615
- type UseWizardReturnType<S extends ReadonlyArray<StepSlot> = ReadonlyArray<StepSlot>> = {
1616
- readonly key: string;
1617
- readonly currentStep: CurrentStepOf<S>;
1618
- readonly activeForm: ActiveFormOf<S>;
1619
- readonly activeIndex: number;
1620
- readonly isFinalStep: boolean;
1621
- readonly steps: ReadonlyArray<CompiledStep>;
1622
- readonly forms: WizardForms<S>;
1623
- readonly count: number;
1624
- readonly statuses: WizardStatusesProxy<Record<string, FormStatus>>;
1625
- readonly allValues: Readonly<Record<FormKey, unknown>>;
1626
- readonly allErrors: Readonly<Record<FormKey, readonly WizardAggregateError[]>>;
1627
- readonly progress: number;
1628
- readonly canAdvance: boolean;
1629
- readonly canGoBack: boolean;
1630
- readonly complete: boolean;
1631
- readonly done: boolean;
1632
- readonly submitting: boolean;
1633
- readonly submissionAttempts: number;
1634
- readonly submitError: Error | null;
1635
- readonly visited: readonly FormKey[];
1636
- readonly next: () => Promise<void>;
1637
- readonly back: () => void;
1638
- readonly goTo: (key: string) => void;
1639
- readonly tryNext: () => Promise<boolean>;
1640
- readonly handleSubmit: (onSubmit: WizardOnSubmit, onError?: WizardOnError) => (event?: Event) => Promise<void>;
1641
- readonly reset: () => void;
1642
- readonly relock: (key: FormKey, commit: () => void | Promise<void>) => Promise<boolean>;
1643
- };
1644
-
1645
- /**
1646
- * Portable SSR detection. The plugin captures this value at install time and
1647
- * exposes it via the registry so every runtime branch reads a single source
1648
- * of truth instead of sniffing `import.meta.*` (bundler-specific) at each
1649
- * call site.
1650
- *
1651
- * Consumers can override the heuristic explicitly via
1652
- * `createAttaform({ ssr: true })`; the default handles the common
1653
- * Node-vs-browser split without relying on any bundler-injected flag.
1654
- */
1655
- interface SSRDetectOptions {
1656
- /**
1657
- * Force SSR-vs-client mode, bypassing the `typeof window` heuristic.
1658
- * `true` activates the SSR code paths (no devtools, no persistence
1659
- * wiring, payload serialisation enabled); `false` forces client mode.
1660
- * The Nuxt plugin sets this from `import.meta.server` so SSR detection
1661
- * never depends on whether `window` is polyfilled. Tests that need to
1662
- * exercise the SSR code paths under jsdom pass `ssr: true`.
1663
- */
1664
- ssr?: boolean;
1665
- }
1666
-
1667
- /**
1668
- * Per-Vue-app container for all form state instances. Each
1669
- * `app.use(createAttaform())` call gets its own registry,
1670
- * so the library runs under bare Vue 3 + SSR (via
1671
- * `@vue/server-renderer`) and Nuxt with the same code path.
1672
- *
1673
- * Each form's state lives in `forms: Map<FormKey, FormStore<GenericForm>>`.
1674
- * The type relaxation at storage time is necessary because different
1675
- * forms in the same app have different `Form` generics; callers recover
1676
- * the specific form type via `useForm`'s overloads.
1677
- */
1678
- /**
1679
- * Serialised snapshot of one form's state, captured by
1680
- * `renderAttaformState` for SSR and replayed by
1681
- * `hydrateAttaformState` on the client. Round-trips through
1682
- * JSON-safe tuples; field references are intentionally omitted
1683
- * (DOM nodes don't survive serialisation).
1684
- */
1685
- type SerializedFormData = {
1686
- /** The form's value at snapshot time. */
1687
- readonly form: unknown;
1688
- /**
1689
- * Errors produced by the schema at snapshot time. Replayed into
1690
- * the client form's error state at hydration; cleared on
1691
- * successful re-validation client-side.
1692
- */
1693
- readonly schemaErrors: ReadonlyArray<readonly [string, unknown]>;
1694
- /**
1695
- * Errors set explicitly via `setErrors` (typically a server
1696
- * response) at snapshot time. Replayed at hydration; persists across
1697
- * client-side re-validation.
1698
- */
1699
- readonly userErrors: ReadonlyArray<readonly [string, unknown]>;
1700
- /** Per-field metadata (timestamps, raw values, connection flags) captured at snapshot time. */
1701
- readonly fields: ReadonlyArray<readonly [string, unknown]>;
1702
- /**
1703
- * Path keys that were in the form's `blankPaths` set at
1704
- * snapshot time. Round-trips the "displayed empty" UI state across
1705
- * the SSR boundary — without it, the client briefly renders
1706
- * `String(slim-default)` (e.g. `'0'`) for fields the server
1707
- * rendered as blank. Optional in the wire format so older payload
1708
- * shapes deserialise cleanly.
1709
- */
1710
- readonly blankPaths?: ReadonlyArray<string>;
1711
- };
1712
- type PendingHydration = Map<FormKey, SerializedFormData>;
1713
- /**
1714
- * The library's per-Vue-app container. One `AttaformRegistry` is
1715
- * created per `app.use(createAttaform())` call.
1716
- *
1717
- * Most consumers never touch this directly — `useForm` and
1718
- * `injectForm` reach the registry on your behalf. Access it
1719
- * explicitly only when wiring SSR or a custom plugin integration.
1720
- */
1721
- type AttaformRegistry = {
1722
- /**
1723
- * Live forms keyed by `FormKey`.
1724
- * @internal
1725
- */
1726
- readonly forms: Map<FormKey, FormStore<GenericForm>>;
1727
- /**
1728
- * Live wizards keyed by the consumer-supplied `key` option. Populated
1729
- * by `useWizard(entryForm, { key })`; consulted by `injectWizard(key)` to
1730
- * resolve cross-component wizard handles. Anonymous wizards (no
1731
- * `key`) do NOT register here — they're reachable only via ambient
1732
- * provide/inject.
1733
- * @internal
1734
- */
1735
- readonly wizards: Map<string, UseWizardReturnType>;
1736
- /**
1737
- * Snapshots staged by `hydrateAttaformState` waiting to be consumed by the next `useForm` call.
1738
- * @internal
1739
- */
1740
- readonly pendingHydration: PendingHydration;
1741
- /** `true` while running on the server during SSR; `false` on the client. */
1742
- readonly ssr: boolean;
1743
- /** App-level defaults applied to every `useForm` call. */
1744
- readonly defaults: AttaformDefaults;
1745
- /**
1746
- * Track a consumer of `key`. Returns a dispose function — call it
1747
- * when the consumer unmounts. The form is evicted automatically
1748
- * when the last consumer disposes, so long-running SPAs don't
1749
- * leak detached state across navigations.
1750
- * @internal
1751
- */
1752
- readonly trackConsumer: (key: FormKey) => () => void;
1753
- /**
1754
- * Track a consumer of wizard `key`. Returns a dispose function — call
1755
- * it when the consumer unmounts. The wizard handle is evicted from
1756
- * `wizards` once the last consumer disposes, mirroring the form
1757
- * consumer-counting mechanics. Anonymous wizards never enter this
1758
- * counter (they have no key to count under).
1759
- * @internal
1760
- */
1761
- readonly trackWizardConsumer: (key: string) => () => void;
1762
- /**
1763
- * Mark a form as eligible for SSR prefetch. The form's
1764
- * `onServerPrefetch` hook consults `shouldPrefetch(key)` and runs the
1765
- * captured `defaultValues` factory only when this set contains the
1766
- * key (and the skip set does not). Set by `form.activate()`,
1767
- * `useWizard`'s current-step auto-mark, and the future Vite transform.
1768
- * @internal
1769
- */
1770
- readonly enqueuePrefetch: (key: FormKey) => void;
1771
- /**
1772
- * Mark a form as ineligible for SSR prefetch. Overrides `enqueuePrefetch`.
1773
- * Used by `useWizard` to keep non-current steps dormant on the
1774
- * server even when a transform mark or stray `activate()` would
1775
- * otherwise enqueue them — the wizard's "user isn't on this step"
1776
- * signal wins.
1777
- * @internal
1778
- */
1779
- readonly skipPrefetch: (key: FormKey) => void;
1780
- /**
1781
- * Whether `key`'s SSR prefetch should run. Returns `true` iff the key
1782
- * is enqueued AND not skipped.
1783
- * @internal
1784
- */
1785
- readonly shouldPrefetch: (key: FormKey) => boolean;
1786
- /**
1787
- * Wait for all pending persistence writes across every live form
1788
- * to settle. Useful for SSR shutdown and integration tests that
1789
- * need a deterministic teardown.
1790
- * @internal
1791
- */
1792
- readonly shutdown: () => Promise<void>;
1793
- };
1794
- /**
1795
- * The Vue `InjectionKey` under which the registry is provided on the
1796
- * app. Most consumers never need this — `useForm` and
1797
- * `injectForm` resolve the registry automatically.
1798
- */
1799
- declare const kAttaformRegistry: InjectionKey<AttaformRegistry>;
1800
- declare module 'vue' {
1801
- interface App {
1802
- /** @internal */
1803
- _attaform?: AttaformRegistry;
1804
- }
1805
- }
1806
- /** Options for `createRegistry`. */
1807
- type CreateRegistryOptions = SSRDetectOptions & {
1808
- /**
1809
- * App-level defaults applied to every `useForm` call. Per-form
1810
- * options always win. Omitted is equivalent to `{}`.
1811
- */
1812
- defaults?: AttaformDefaults;
1813
- };
1814
- /**
1815
- * Create a fresh `AttaformRegistry`. `createAttaform()` calls
1816
- * this internally — most consumers never need to call it directly.
1817
- * Use it when building a custom plugin that doesn't want the
1818
- * `createAttaform` plugin's auto-install behaviour (e.g. test
1819
- * harnesses, embedded apps).
1820
- */
1821
- declare function createRegistry(options?: CreateRegistryOptions): AttaformRegistry;
1822
- /**
1823
- * Look up the current app's registry from inside a component's
1824
- * `setup()` (or any synchronous code on the setup call stack).
1825
- *
1826
- * Most consumers don't need this — `useForm` and `injectForm`
1827
- * call it on your behalf. Reach for it directly when building
1828
- * custom integrations that need the raw registry.
1829
- *
1830
- * Throws:
1831
- * - `OutsideSetupError` when called outside a Vue setup context
1832
- * (e.g. from an event handler or async callback). Move the call
1833
- * into setup, or trigger it from a child component.
1834
- * - `RegistryNotInstalledError` when called inside setup but the
1835
- * plugin wasn't installed. Add
1836
- * `app.use(createAttaform())` to your app entry.
1837
- */
1838
- declare function useRegistry(): AttaformRegistry;
1839
- /**
1840
- * Look up a Vue app's registry by `App` reference. Used by
1841
- * SSR helpers (`renderAttaformState`, `hydrateAttaformState`) that
1842
- * run outside a component setup context.
1843
- *
1844
- * Throws `RegistryNotInstalledError` when the app hasn't been wired
1845
- * with `createAttaform()`.
1846
- */
1847
- declare function getRegistryFromApp(app: App): AttaformRegistry;
1848
-
1849
- /**
1850
- * Multistep-form orchestrator built around an ordered list of step slots.
1851
- * Each slot resolves to a participating form: an existing `useForm`
1852
- * reference, a bare string key (desugared to a noop form so affordance
1853
- * steps participate uniformly), an eagerly-evaluated function slot for
1854
- * runtime branching, or a `lazy()`-wrapped function slot that caches
1855
- * its resolution and re-fires only on its own tracked deps.
1856
- *
1857
- * The wizard's surface is read-only from the consumer's side:
1858
- * navigation (`next` / `back` / `goTo`) walks positional indices,
1859
- * `handleSubmit` validates the whole step list from any step and never
1860
- * advances (gate advance with `activeForm.handleSubmit(() =>
1861
- * wizard.next())`), and URL synchronization rides on `restore` /
1862
- * `persist` callbacks that default to `?step=<key>`.
1863
- */
1864
- declare function useWizard<const S extends ReadonlyArray<StepSlot>>(options: WizardOptions & {
1865
- readonly steps: S;
1866
- }): UseWizardReturnType<S>;
1867
-
1868
- /**
1869
- * Options accepted by `injectWizard` when passing an object instead of
1870
- * a bare key string. Mirrors `injectForm`'s `InjectFormInput` shape so
1871
- * the two composables present an identical call surface.
1872
- */
1873
- type InjectWizardInput = {
1874
- readonly key?: string | undefined;
1875
- };
1876
- /**
1877
- * Access an existing wizard handle from a descendant component without
1878
- * passing it through props. Counterpart to `useWizard` — `useWizard`
1879
- * creates and provides; `injectWizard` looks up via Vue's inject
1880
- * mechanism or the per-app registry.
1881
- *
1882
- * Three ways to call it:
1883
- *
1884
- * ```ts
1885
- * // Reach the nearest ancestor's useWizard call (ambient).
1886
- * const wizard = injectWizard()
1887
- *
1888
- * // Reach a specific wizard by its key — works from anywhere in the app.
1889
- * const signup = injectWizard('signup-wizard')
1890
- *
1891
- * // Object form (equivalent; convenient for spread).
1892
- * const signup = injectWizard({ key: 'signup-wizard' })
1893
- * ```
1894
- *
1895
- * Resolution rules (no-key form):
1896
- * - Closest ambient ancestor wins via `provide(kAttaformAncestorWizard)`.
1897
- * - Only anonymous (no-`key`) `useWizard()` calls fill the ambient
1898
- * slot. Descendants of a keyed wizard must address it explicitly
1899
- * via `injectWizard('the-key')`. Mirrors `useForm`'s ambient gate.
1900
- *
1901
- * Resolution rules (keyed form): registry lookup by string key,
1902
- * independent of component-tree position. The wizard must have been
1903
- * constructed with `useWizard({ steps, key })` to be reachable.
1904
- *
1905
- * Returns `null` when no matching wizard exists (no ambient ancestor,
1906
- * or the named key isn't registered yet). A dev-mode warning points at
1907
- * the call site, lists the registered keys, and flags the mount-timing
1908
- * case (a wizard created by a child or sibling isn't registered until
1909
- * its own setup runs). Always narrow before using:
1910
- *
1911
- * ```ts
1912
- * const wizard = injectWizard('signup')
1913
- * if (!wizard) return
1914
- * wizard.next()
1915
- * ```
1916
- *
1917
- * Consumer ref-counting: keyed lookups pin the wizard handle in the
1918
- * registry for this component's lifetime, so the handle survives even
1919
- * if the parent `useWizard` component unmounts before the child does.
1920
- * Once every consumer disposes, the registry evicts the entry on the
1921
- * next microtask. Ambient lookups don't ref-count — the parent
1922
- * `useWizard`'s scope owns the lifetime.
1923
- */
1924
- declare function injectWizard(input?: string | InjectWizardInput): UseWizardReturnType | null;
1925
-
1926
- /**
1927
- * Wrap a function slot in `lazy()` to give that slot its own memoized
1928
- * cache, distinct from the wizard-wide step compiler.
1929
- *
1930
- * Default function slots in `useWizard({ steps })` re-evaluate whenever
1931
- * the compiled step list re-evaluates, including when an unrelated
1932
- * slot's reactive deps change. That keeps the rail correct but can
1933
- * trigger spurious work in a resolver that is expensive (a network
1934
- * lookup, a heavy schema derivation, an async-derived factory).
1935
- *
1936
- * `lazy()` isolates each wrapped slot behind its own cache. The
1937
- * resolver runs eagerly on the first compile pass; subsequent reads
1938
- * reuse the cached form. The cache invalidates only when one of the
1939
- * resolver's own tracked reactive dependencies changes (Vue's
1940
- * `computed` semantics applied to a slot), or when `wizard.reset()`
1941
- * triggers a global re-compile:
1942
- *
1943
- * const wizard = useWizard({
1944
- * steps: [
1945
- * account,
1946
- * lazy((ctx) => loadShippingForm(ctx.forms.account.values.region)),
1947
- * confirm,
1948
- * ],
1949
- * })
1950
- *
1951
- * Resolution semantics:
1952
- * - Eager at construction so `wizard.steps` and SSR markup are honest
1953
- * from t=0.
1954
- * - Memoized: the resolver re-fires only when one of its own tracked
1955
- * reads changes. An unrelated slot re-evaluating does not re-fire
1956
- * this one.
1957
- * - `wizard.reset()` clears every lazy slot's cache so a reboot truly
1958
- * resolves from scratch.
1959
- * - Resolving to `null` or `undefined` drops the slot from the compiled
1960
- * list until the resolver next re-fires.
1961
- * - The resolver may return a `gate()` wrapper, so a lazy slot can gate
1962
- * what it resolves to; `lazy((ctx) => gate(s))` and `gate(lazy(s))`
1963
- * resolve identically.
1964
- *
1965
- * The runtime brand returned by `lazy()` is opaque. Use
1966
- * {@link isLazyMarker} to detect it.
1967
- */
1968
- declare function lazy<Ctx = WizardCtx>(resolve: (ctx: Ctx) => SlotResolution<Ctx>): LazyMarker<Ctx>;
1969
-
1970
- /**
1971
- * Wrap a step slot in `gate()` to make it a hard prerequisite: while the
1972
- * gate is uncleared, every step positioned after it is inaccessible, and
1973
- * the gate's own form is the only way past.
1974
- *
1975
- * A gate is safe by construction. It does not hand the consumer a
1976
- * predicate to key on; it bakes the correct semantics in:
1977
- *
1978
- * - **Confirmation, not intent.** The gate clears only when a member
1979
- * form submits clean, never when a value merely goes valid. Checking
1980
- * the box does nothing; submitting the consent step is what opens the
1981
- * rail. This is the whole reason `gate()` exists: a leading value
1982
- * signal lets a downstream step collect data before the prerequisite
1983
- * is confirmed.
1984
- * - **Linear-forward.** An uncleared gate seals every step after it.
1985
- * Order places it: put `gate(step)` immediately before what it
1986
- * guards. Everything downstream is both un-navigable and, through the
1987
- * `disabled` data freeze, un-fillable, so a deep link, the browser
1988
- * back button, or a stray `goTo` all redirect to the gate.
1989
- * - **Freeze-after-clear.** A cleared gate's own form freezes, so
1990
- * navigating back to it is a read-only review with no withdrawal
1991
- * path. There is no re-lock dance.
1992
- *
1993
- * Wrap any slot kind:
1994
- *
1995
- * const wizard = useWizard({ steps: [gate(consent), shipping, payment] })
1996
- *
1997
- * A **form** gate (`gate(consentForm)`) clears when its form submits
1998
- * clean, and is treated as pre-cleared on reload when its member form
1999
- * rehydrates already valid (a persisted consent), so a seeded-valid gate
2000
- * SSR-renders open. A bare-string **affordance** gate (`gate('terms')`)
2001
- * clears on acknowledgment (advancing past it), and re-prompts each
2002
- * session because that acknowledgment is ephemeral.
2003
- *
2004
- * Conditional gates come from composition, not an options bag:
2005
- *
2006
- * () => (transfer.values.amount > 10_000 ? gate(kyc) : kyc)
2007
- *
2008
- * `gate()` composes with `lazy()` in either order:
2009
- * `gate(lazy(fn))` and `lazy((ctx) => gate(fn(ctx)))` resolve
2010
- * identically.
2011
- *
2012
- * The runtime brand returned by `gate()` is opaque. Use
2013
- * {@link isGateMarker} to detect it.
2014
- */
2015
- declare function gate<const Inner extends StepSlot>(step: Inner): GateMarker<Inner>;
2016
-
2017
- /**
2018
- * Stable identifiers for library-emitted `ValidationError` codes.
2019
- *
2020
- * Convention: `<scope>:<kebab-case-identifier>`. Three scopes are
2021
- * recognised by the library:
2022
- *
2023
- * - `atta:` — emitted by the framework-agnostic core (this map).
2024
- * - `zod:` — emitted by the Zod adapter; computed inline from
2025
- * `issue.code` (e.g. `zod:too_small`). No enum here because
2026
- * Zod's code list evolves.
2027
- * - consumer-defined — anything the consumer's backend / app stamps
2028
- * onto a `ValidationError` (a server response handed to `setErrors`,
2029
- * or a code passed inline). Pick a scope (`api:`, `auth:`, etc.) and
2030
- * stay consistent.
2031
- *
2032
- * Use these constants in tests and error-routing UI:
2033
- *
2034
- * ```ts
2035
- * if (error.code === AttaformErrorCode.NoValueSupplied) {
2036
- * // user hasn't filled this field
2037
- * }
2038
- * ```
2039
- */
2040
- declare const AttaformErrorCode: {
2041
- /** A required field is in the blank set — user hasn't supplied a value. */
2042
- readonly NoValueSupplied: "atta:no-value-supplied";
2043
- /** The schema adapter's `validateAtPath` threw synchronously. */
2044
- readonly AdapterThrew: "atta:adapter-threw";
2045
- /**
2046
- * User code inside a `z.preprocess`, `.refine`, or `.transform`
2047
- * threw (sync or async). The adapter caught the throw and surfaced
2048
- * it as a `ValidationError` at the field path so the form's normal
2049
- * error pipeline handles it instead of leaking as an unhandled
2050
- * rejection or routing through `submitError`.
2051
- */
2052
- readonly ValidatorThrew: "atta:validator-threw";
2053
- /**
2054
- * A function-form `defaultValues` factory threw or its promise
2055
- * rejected. The runtime captures the raw error on `form.hydrateError`
2056
- * and ALSO surfaces a form-level `ValidationError` (path `[]`) so
2057
- * the standard error pipeline carries the signal. Critical for the
2058
- * SSR round-trip: `hydrateError` itself does not ride the wire
2059
- * payload, but `schemaErrors` does, so the client sees the failure
2060
- * after rehydration without an extra channel.
2061
- */
2062
- readonly HydrationFailed: "atta:hydration-failed";
2063
- /** The supplied path didn't resolve to any node in the schema. */
2064
- readonly PathNotFound: "atta:path-not-found";
2065
- /**
2066
- * A walked form's `activate()` (async `defaultValues` factory) threw
2067
- * during `wizard.handleSubmit`'s path walk. Surfaced as a synthetic
2068
- * `ValidationError` at the form-level path (`[]`) so the wizard's
2069
- * aggregate error pipeline can carry the failure alongside ordinary
2070
- * validation errors. The raw factory error remains on
2071
- * `form.hydrateError` for retry UX.
2072
- */
2073
- readonly ActivationFailed: "atta:activation-failed";
2074
- /**
2075
- * Default code stamped on a manual error set through `form.setErrors`
2076
- * when the caller omits an explicit `code`. The `setErrors` input is
2077
- * lenient (`code` optional), so this is the fallback that keeps every
2078
- * produced `ValidationError` carrying a stable, branchable identifier.
2079
- * Override it per error by passing your own `code` (`api:…`, `auth:…`).
2080
- */
2081
- readonly UserError: "atta:user-error";
2082
- /**
2083
- * Stamped on a `ValidationError` synthesized from a throw or rejection
2084
- * out of a `handleSubmit` `onSubmit` callback. The raw error also lands
2085
- * on `form.meta.submitError` (a raw-`Error` inspection channel); this
2086
- * code marks the copy piped into the user-error layer so the failure
2087
- * also surfaces on `form.errors` / `meta.ownErrors` / `firstOwnError`
2088
- * where the UI already reads. A throw carrying its own `path` / `code`
2089
- * keeps them; a bare `Error` or a non-Error throw defaults here at the
2090
- * form-level path `[]`.
2091
- */
2092
- readonly SubmitError: "atta:submit-error";
2093
- /**
2094
- * Synthesized by `wizard.handleSubmit` when the whole-wizard submit
2095
- * would otherwise succeed but a `gate()` step is still uncleared. A
2096
- * gate clears only on its member form's clean submit (confirmation), so
2097
- * a downstream step that happens to be valid-by-default must not let the
2098
- * wizard finish past an unconfirmed prerequisite. Emitted at the gate
2099
- * form's key (path `[]`) so the aggregate error pipeline routes focus to
2100
- * the gate, and `done` never latches.
2101
- */
2102
- readonly GateNotCleared: "atta:gate-not-cleared";
2103
- };
2104
- type AttaformErrorCode = (typeof AttaformErrorCode)[keyof typeof AttaformErrorCode];
2105
-
2106
- /**
2107
- * Options for `createAttaform()`.
2108
- */
2109
- type AttaformPluginOptions = SSRDetectOptions & {
2110
- /**
2111
- * Whether to install the Vue DevTools integration. Default `true`.
2112
- * The integration is dev-only: the `import('./devtools')` sits behind
2113
- * the `__DEV__` flag, so a consumer's production build folds it out
2114
- * entirely (no devtools chunk shipped, no fetch attempted). In
2115
- * development the DevTools peer is loaded lazily and a missing peer
2116
- * fails silently. Pass `false` to skip the integration even in dev.
2117
- */
2118
- devtools?: boolean;
2119
- /**
2120
- * App-level defaults applied to every `useForm` call in this app.
2121
- * Per-form options always win. See `AttaformDefaults` for
2122
- * the supported option set and the merge rules.
2123
- *
2124
- * ```ts
2125
- * app.use(
2126
- * createAttaform({
2127
- * defaults: { debounceMs: 100 },
2128
- * })
2129
- * )
2130
- * ```
2131
- */
2132
- defaults?: AttaformDefaults;
2133
- };
2134
- /**
2135
- * Create the Vue plugin that installs the form library on a Vue
2136
- * application. Required only when you want app-wide options
2137
- * (`defaults`, `devtools: false`, `ssr: true`) — for the default
2138
- * setup, `useForm` / `injectForm` / `useRegister` lazy-install the
2139
- * registry on first use.
2140
- *
2141
- * ```ts
2142
- * import { createApp } from 'vue'
2143
- * import { createAttaform } from 'attaform'
2144
- *
2145
- * createApp(App)
2146
- * .use(createAttaform({ defaults: { debounceMs: 100 } }))
2147
- * .mount('#app')
2148
- * ```
2149
- *
2150
- * Under SSR with bare Vue 3, install explicitly with `{ ssr: true }`
2151
- * from your server entry — the SSR serialization helpers
2152
- * (`renderAttaformState` / `hydrateAttaformState`) require an
2153
- * already-attached registry and don't trigger lazy install. Under
2154
- * Nuxt, install via `attaform/nuxt` instead — the Nuxt module wires
2155
- * both server and client automatically.
2156
- *
2157
- * Installing more than once on the same app is a no-op (the second
2158
- * call logs a dev-mode warning).
2159
- */
2160
- declare function createAttaform(options?: AttaformPluginOptions): Plugin;
2161
-
2162
- /**
2163
- * Serialised snapshot of every form in a Vue app, produced by
2164
- * `renderAttaformState` and consumed by `hydrateAttaformState`.
2165
- *
2166
- * JSON-safe — pass to `JSON.stringify`, `devalue`, or any other
2167
- * serialiser before embedding in your SSR payload.
2168
- */
2169
- type SerializedAttaformState = {
2170
- /** Tuples of `[formKey, snapshot]` for every form in the app. */
2171
- readonly forms: ReadonlyArray<readonly [FormKey, SerializedFormData]>;
2172
- };
2173
- /**
2174
- * Snapshot every form on a Vue app for SSR. Call from your server
2175
- * entry after rendering the app:
2176
- *
2177
- * ```ts
2178
- * import { renderToString } from '@vue/server-renderer'
2179
- * import { renderAttaformState, escapeForInlineScript } from 'attaform'
2180
- *
2181
- * const html = await renderToString(app)
2182
- * const state = renderAttaformState(app)
2183
- * const payload = escapeForInlineScript(JSON.stringify(state))
2184
- *
2185
- * return `
2186
- * ${html}
2187
- * <script>window.__ATTAFORM_STATE__ = ${payload}</script>
2188
- * `
2189
- * ```
2190
- *
2191
- * Pair with `hydrateAttaformState` on the client to restore the
2192
- * forms in their server-rendered state. Nuxt users don't need this —
2193
- * `attaform/nuxt` wires SSR automatically.
2194
- */
2195
- declare function renderAttaformState(app: App): SerializedAttaformState;
2196
- /**
2197
- * Restore forms from a server-rendered snapshot on the client. Call
2198
- * from your client entry before mounting:
2199
- *
2200
- * ```ts
2201
- * import { createApp } from 'vue'
2202
- * import { createAttaform, hydrateAttaformState } from 'attaform'
2203
- *
2204
- * const app = createApp(App).use(createAttaform())
2205
- * hydrateAttaformState(app, window.__ATTAFORM_STATE__)
2206
- * app.mount('#app')
2207
- * ```
2208
- *
2209
- * The next `useForm({ key })` call for each serialised form picks up
2210
- * the snapshot transparently — no further action is required.
2211
- */
2212
- declare function hydrateAttaformState(app: App, payload: SerializedAttaformState): void;
2213
-
2214
- /**
2215
- * Escape a JSON string so it's safe to embed inside an inline
2216
- * `<script>` tag during SSR. Plain `JSON.stringify` is not safe — a
2217
- * form value containing the literal substring `</script>` would
2218
- * break out of the script tag.
2219
- *
2220
- * ```ts
2221
- * const payload = escapeForInlineScript(JSON.stringify(renderAttaformState(app)))
2222
- * // `<script>window.__ATTAFORM_STATE__ = ${payload}</script>` is safe.
2223
- * ```
2224
- *
2225
- * Output remains valid JSON — `JSON.parse` round-trips back to the
2226
- * original value on the client.
2227
- */
2228
- declare function escapeForInlineScript(json: string): string;
2229
-
2230
- /**
2231
- * Symbol slot used by custom directive integrations to install an
2232
- * assigner on the bound element. Read by the v-register directive
2233
- * when a DOM event fires:
2234
- *
2235
- * ```ts
2236
- * import { assignKey } from 'attaform'
2237
- * el[assignKey] = (value) => myCustomWriter(value)
2238
- * ```
2239
- *
2240
- * Most consumers never need this — the built-in directives wire
2241
- * default assigners for text inputs, checkboxes, radios, and selects.
2242
- */
2243
- declare const assignKey: unique symbol;
2244
-
2245
- /**
2246
- * The `v-register` directive. Bind a form field to a native input,
2247
- * select, textarea, checkbox, or radio:
2248
- *
2249
- * ```vue
2250
- * <input v-register="form.register('email')" />
2251
- * <select v-register="form.register('country')">
2252
- * <option value="us">US</option>
2253
- * <option value="uk">UK</option>
2254
- * </select>
2255
- * ```
2256
- *
2257
- * The directive picks the right binding strategy automatically based
2258
- * on the element's `tagName` and `type`. Registered globally by
2259
- * `createAttaform()`. Most consumers never import it directly, but
2260
- * it's exposed for advanced integrations that wire directives
2261
- * manually.
2262
- */
2263
- declare const vRegister: RegisterModelDynamicCustomDirective;
2264
-
2265
- /**
2266
- * Type guard for a `RegisterValue`. Returns `true` when `val` looks
2267
- * like the object returned from `form.register(path)`.
2268
- *
2269
- * ```ts
2270
- * if (isRegisterValue(slotValue)) {
2271
- * // slotValue.innerRef is now a Ref<unknown>
2272
- * }
2273
- * ```
2274
- *
2275
- * Useful when building wrapper components that accept either a
2276
- * `RegisterValue` or a plain ref via the same prop.
2277
- */
2278
- declare function isRegisterValue<Value = unknown>(val: unknown): val is RegisterValue<Value>;
2279
-
2280
- /**
2281
- * Shared building blocks for Attaform's two devtools surfaces — the Vue
2282
- * DevTools (Chrome-extension) inspector wired up in `./devtools.ts`, and
2283
- * the Nuxt DevTools (overlay) panel wired up via `../../nuxt.ts` +
2284
- * `../pages/_attaform_devtools.vue`.
2285
- *
2286
- * Houses the window-bridge contract both surfaces consume so a new
2287
- * bridge field lands in one file. Both surfaces render RAW form values
2288
- * by design — DevTools is a dev-only surface, and redaction across every
2289
- * place a value surfaces is impractical security theater rather than a
2290
- * real safeguard.
2291
- */
2292
-
2293
- /**
2294
- * Property key on `window` that the Nuxt-side dev plugin attaches the
2295
- * bridge object to. The iframe-mounted overlay panel reads
2296
- * `window.parent[DEVTOOLS_WINDOW_KEY]` to reach the host app's registry.
2297
- *
2298
- * Underscored + namespaced to make accidental collision with consumer
2299
- * globals vanishingly unlikely. Stable across versions — bumping it
2300
- * would silently disconnect older library builds from newer overlay
2301
- * panels in the same browser tab during a library upgrade.
2302
- */
2303
- declare const DEVTOOLS_WINDOW_KEY = "__attaform_devtools__";
2304
- /**
2305
- * Shape of the object the host plugin attaches to `window` in dev mode.
2306
- * The iframe overlay panel reads this to discover the live registry and
2307
- * render its forms.
2308
- *
2309
- * Single-registry assumption: the latest `createAttaform()` install
2310
- * wins. Multi-app pages (rare; typically only seen in micro-frontend
2311
- * setups) will only see one app's forms in the panel. Documented but
2312
- * not actively supported — the alternative (a Set of registries with
2313
- * union-rendering) is a future call if a real consumer hits it.
2314
- */
2315
- interface AttaformDevtoolsBridge {
2316
- registry: AttaformRegistry;
2317
- /**
2318
- * The library version, surfaced in the panel's footer for support /
2319
- * bug-report context. Read from `package.json` at host-plugin init.
2320
- */
2321
- version: string;
2322
- }
2323
- declare global {
2324
- interface Window {
2325
- [DEVTOOLS_WINDOW_KEY]?: AttaformDevtoolsBridge;
2326
- }
2327
- }
2328
-
2329
- /**
2330
- * Typed error classes thrown by the form library. Each one signals a
2331
- * distinct misuse so calling code can branch on `instanceof` instead
2332
- * of pattern-matching error messages.
2333
- *
2334
- * Every class extends `AttaformError`, so consumers can write a single
2335
- * polymorphic catch (`catch (e) { if (e instanceof AttaformError) ... }`)
2336
- * instead of OR-chaining checks for each subclass. `AttaformError` itself
2337
- * extends the standard `Error`, so existing `instanceof Error` usage
2338
- * keeps working.
2339
- */
2340
-
2341
- /**
2342
- * Base for every error class thrown by `attaform`. Sets
2343
- * `this.name` from the constructor's `new.target.name`, so subclasses
2344
- * don't have to redeclare their own name override.
2345
- */
2346
- declare class AttaformError extends Error {
2347
- constructor(message: string, options?: ErrorOptions);
2348
- }
2349
- /**
2350
- * Thrown when a path string is malformed — typically a dotted path
2351
- * with empty segments (e.g. `'a..b'`, leading or trailing dots).
2352
- * Use array form (`['a', 'b']`) for keys that contain literal dots.
2353
- */
2354
- declare class InvalidPathError extends AttaformError {
2355
- }
2356
- /**
2357
- * Thrown when `useForm` receives an invalid configuration — most often
2358
- * a schema passed directly as the first argument, or no argument at
2359
- * all. The configuration is an options bag; the schema is one of
2360
- * several fields, even when it's the only one in use.
2361
- *
2362
- * ```ts
2363
- * // ✗ Crashes deep inside the validator with an opaque message:
2364
- * const form = useForm(z.object({ ... }))
2365
- * // ✗ Same:
2366
- * const form = useForm()
2367
- * // ✓ Pass the schema as the `schema` field:
2368
- * const form = useForm({ schema: z.object({ ... }) })
2369
- * ```
2370
- *
2371
- * The same shape applies to every entry point: `attaform/zod`,
2372
- * `attaform/zod-v3`, `attaform/zod-v4`, and the schema-agnostic
2373
- * `attaform` root.
2374
- */
2375
- declare class InvalidUseFormConfigError extends AttaformError {
2376
- constructor();
2377
- }
2378
- /**
2379
- * Thrown when a `handleSubmit`-supplied `onError` callback itself
2380
- * throws or rejects. Wraps the inner failure so both the original
2381
- * cause (via `error.cause`) and the propagation site are visible.
2382
- */
2383
- declare class SubmitErrorHandlerError extends AttaformError {
2384
- }
2385
- /**
2386
- * Thrown when an `attaform` API needs the registry attached to a Vue
2387
- * app but it isn't there yet. Component-level entry points (`useForm`,
2388
- * `injectForm`, `useRegister`) lazy-install the registry on first use,
2389
- * so this error is mostly reached by SSR helpers — `renderAttaformState`
2390
- * and `hydrateAttaformState` — which run outside a setup context and
2391
- * have no current instance to install against.
2392
- *
2393
- * Fix: add `app.use(createAttaform())` (or `app.use(createAttaform({
2394
- * ssr: true }))` on the server) to your SSR entry, before
2395
- * `renderToString` / hydration. Under Nuxt, `attaform/nuxt` already
2396
- * does this; the error usually points at a non-Nuxt SSR setup that
2397
- * hasn't installed explicitly.
2398
- */
2399
- declare class RegistryNotInstalledError extends AttaformError {
2400
- constructor();
2401
- }
2402
- /**
2403
- * Thrown when `useForm` / `injectForm` is called outside of a
2404
- * Vue `setup()` function — typically from an event handler, watcher,
2405
- * or async callback that runs after mount.
2406
- *
2407
- * Fix: move the call into `setup()`, or trigger it from a child
2408
- * component whose `setup()` runs the composable.
2409
- */
2410
- declare class OutsideSetupError extends AttaformError {
2411
- constructor();
2412
- }
2413
- /**
2414
- * Thrown when a `useForm({ key })` call uses a key starting with
2415
- * `__atta:`. That prefix is reserved for keys the library generates
2416
- * internally (e.g. for anonymous `useForm()` calls without an
2417
- * explicit key). Pick a different prefix for your form.
2418
- */
2419
- declare class ReservedFormKeyError extends AttaformError {
2420
- constructor(key: string);
2421
- }
2422
-
2423
- /**
2424
- * Anti-flash timing for the library-default display reducer.
2425
- *
2426
- * - `showDelay` — how long in-flight work (a validation run or an async
2427
- * register transform) may run before its spinner is allowed to show. Work
2428
- * that settles inside this window never reveals `'pending'` at all, so a
2429
- * fast (often synchronous) check does not flash a spinner on every keystroke.
2430
- * - `minVisible` — once shown, the minimum time the spinner stays up. Work
2431
- * that lands just past `showDelay` is held here so the spinner does not
2432
- * itself flash on and immediately off.
2433
- *
2434
- * Both are milliseconds.
2435
- */
2436
- type DisplayTimings = {
2437
- readonly showDelay: number;
2438
- readonly minVisible: number;
2439
- };
2440
- /**
2441
- * Library-default anti-flash timings. `showDelay: 120` cleanly swallows
2442
- * synchronous, microtask-resolved, and tiny-async work (validation runs and
2443
- * async register transforms alike) so none of them flash a spinner;
2444
- * `minVisible: 120` keeps a shown spinner snappy once one does land.
2445
- * Retune via {@link makeDefaultDisplayState} without touching the engine.
2446
- */
2447
- declare const DEFAULT_TIMINGS: DisplayTimings;
2448
- /**
2449
- * Build a default `getDisplayState` reducer with custom anti-flash timing.
2450
- * Power users who want a tighter or looser spinner than {@link DEFAULT_TIMINGS}
2451
- * pass their own `{ showDelay, minVisible }`:
2452
- *
2453
- * ```ts
2454
- * import { makeDefaultDisplayState } from 'attaform'
2455
- *
2456
- * useForm({
2457
- * schema,
2458
- * getDisplayState: makeDefaultDisplayState({ showDelay: 50, minVisible: 200 }),
2459
- * })
2460
- * ```
2461
- *
2462
- * The returned reducer is pure: the engine injects `now` and threads the
2463
- * previous machine, so the same `(prev, ctx)` always yields the same next
2464
- * machine. It shapes only the display projection — `errors`, `valid`,
2465
- * `validating`, and the underlying validation run exactly as before.
2466
- */
2467
- declare function makeDefaultDisplayState({ showDelay, minVisible, }: DisplayTimings): GetDisplayState;
2468
- /**
2469
- * Library-default `getDisplayState` reducer. Resolves every path's
2470
- * `field.displayState` — and thus `field.show*` and the `form.meta`
2471
- * rollups — whenever the consumer has not configured an override at the
2472
- * per-form or plugin level. Built from {@link DEFAULT_TIMINGS}; publicly
2473
- * re-exported so an override can compose with it (a layered reducer that
2474
- * special-cases a subtree but otherwise defers picks up future
2475
- * refinements for free):
2476
- *
2477
- * ```ts
2478
- * import { defaultDisplayState } from 'attaform'
2479
- *
2480
- * useForm({
2481
- * schema,
2482
- * getDisplayState: (prev, ctx) => {
2483
- * const next = defaultDisplayState(prev, ctx)
2484
- * return next.display === 'success' && ctx.field.path[0] === 'username'
2485
- * ? { display: 'idle' }
2486
- * : next
2487
- * },
2488
- * })
2489
- * ```
2490
- */
2491
- declare const defaultDisplayState: GetDisplayState;
2492
-
2493
- export { renderAttaformState as $, createAttaform as B, DEFAULT_TIMINGS as D, createRegistry as E, defaultCoercionRules as H, defaultDisplayState as J, defineCoercion as K, escapeForInlineScript as M, gate as N, OutsideSetupError as O, getRegistryFromApp as P, hydrateAttaformState as Q, RegistryNotInstalledError as R, injectForm as T, injectWizard as V, isRegisterValue as X, kAttaformRegistry as Y, lazy as Z, makeDefaultDisplayState as _, useRegister as a0, useRegistry as a1, useWizard as a2, vRegister as a3, AttaformError as c, AttaformErrorCode as d, DEVTOOLS_WINDOW_KEY as f, InvalidPathError as i, InvalidUseFormConfigError as j, ReservedFormKeyError as k, SubmitErrorHandlerError as n, assignKey as z };
2494
- export type { AttaformRegistry as A, CompiledStep as C, FormStatus as F, GateMarker as G, InjectWizardInput as I, LazyMarker as L, SerializedAttaformState as S, UseRegisterReturn as U, WizardAggregateError as W, AnyForm as a, AttaformDevtoolsBridge as b, AttaformPluginOptions as e, DisplayTimings as g, FormStatusSeed as h, SerializedFormData as l, StepSlot as m, UseWizardReturnType as o, WizardCtx as p, WizardCtxForm as q, WizardOnError as r, WizardOnSubmit as s, WizardOptions as t, WizardPersistFn as u, WizardRestoreFn as v, WizardRestoreState as w, WizardStatusesProxy as x, WizardSubmitContext as y };