attaform 0.16.3 → 0.16.4

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 (57) hide show
  1. package/dist/chunks/devtools.cjs +1 -1
  2. package/dist/chunks/devtools.mjs +1 -1
  3. package/dist/index.cjs +3 -2
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +33 -4
  6. package/dist/index.d.mts +33 -4
  7. package/dist/index.d.ts +33 -4
  8. package/dist/index.mjs +3 -3
  9. package/dist/nuxt.d.cts +1 -1
  10. package/dist/nuxt.d.mts +1 -1
  11. package/dist/nuxt.d.ts +1 -1
  12. package/dist/shared/{attaform.lFNwBcA3.d.ts → attaform.CCQkY4Ta.d.ts} +1 -1
  13. package/dist/shared/{attaform.c_NzdRyc.cjs → attaform.CIwZtbGV.cjs} +6 -2
  14. package/dist/shared/attaform.CIwZtbGV.cjs.map +1 -0
  15. package/dist/shared/{attaform.Bls_kFR6.d.mts → attaform.CMRmwGDt.d.cts} +1 -1
  16. package/dist/shared/{attaform._EqYNPYF.d.ts → attaform.CU3JperC.d.cts} +172 -14
  17. package/dist/shared/{attaform._EqYNPYF.d.cts → attaform.CU3JperC.d.mts} +172 -14
  18. package/dist/shared/{attaform._EqYNPYF.d.mts → attaform.CU3JperC.d.ts} +172 -14
  19. package/dist/shared/{attaform.DLnKT7wk.d.cts → attaform.CXMOheyZ.d.mts} +1 -1
  20. package/dist/shared/{attaform.jrxE_xZw.mjs → attaform.DZRj9s0s.mjs} +5 -3
  21. package/dist/shared/attaform.DZRj9s0s.mjs.map +1 -0
  22. package/dist/shared/{attaform.KrNw10aW.cjs → attaform.Dd_pWnmn.cjs} +12 -13
  23. package/dist/shared/attaform.Dd_pWnmn.cjs.map +1 -0
  24. package/dist/shared/{attaform.DILbdvfo.mjs → attaform.DyV1O4tI.mjs} +111 -22
  25. package/dist/shared/attaform.DyV1O4tI.mjs.map +1 -0
  26. package/dist/shared/{attaform.CFA6y0KF.mjs → attaform.UA19EF3J.mjs} +12 -13
  27. package/dist/shared/attaform.UA19EF3J.mjs.map +1 -0
  28. package/dist/shared/{attaform.C9Ph2SMx.cjs → attaform.fegmBJaq.cjs} +111 -21
  29. package/dist/shared/attaform.fegmBJaq.cjs.map +1 -0
  30. package/dist/shared/{attaform.XYOMTvuO.mjs → attaform.g7rfuXdz.mjs} +7 -3
  31. package/dist/shared/attaform.g7rfuXdz.mjs.map +1 -0
  32. package/dist/shared/{attaform.DGuGGNg9.cjs → attaform.keLBaHB6.cjs} +7 -3
  33. package/dist/shared/attaform.keLBaHB6.cjs.map +1 -0
  34. package/dist/zod-v3.cjs +2 -2
  35. package/dist/zod-v3.d.cts +3 -3
  36. package/dist/zod-v3.d.mts +3 -3
  37. package/dist/zod-v3.d.ts +3 -3
  38. package/dist/zod-v3.mjs +2 -2
  39. package/dist/zod-v4.cjs +2 -2
  40. package/dist/zod-v4.d.cts +3 -3
  41. package/dist/zod-v4.d.mts +3 -3
  42. package/dist/zod-v4.d.ts +3 -3
  43. package/dist/zod-v4.mjs +2 -2
  44. package/dist/zod.cjs +3 -3
  45. package/dist/zod.d.cts +3 -3
  46. package/dist/zod.d.mts +3 -3
  47. package/dist/zod.d.ts +3 -3
  48. package/dist/zod.mjs +3 -3
  49. package/package.json +1 -1
  50. package/dist/shared/attaform.C9Ph2SMx.cjs.map +0 -1
  51. package/dist/shared/attaform.CFA6y0KF.mjs.map +0 -1
  52. package/dist/shared/attaform.DGuGGNg9.cjs.map +0 -1
  53. package/dist/shared/attaform.DILbdvfo.mjs.map +0 -1
  54. package/dist/shared/attaform.KrNw10aW.cjs.map +0 -1
  55. package/dist/shared/attaform.XYOMTvuO.mjs.map +0 -1
  56. package/dist/shared/attaform.c_NzdRyc.cjs.map +0 -1
  57. package/dist/shared/attaform.jrxE_xZw.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"attaform.DILbdvfo.mjs","sources":["../../src/runtime/core/diff-apply.ts","../../src/runtime/core/field-meta.ts","../../src/runtime/core/humanize.ts","../../src/runtime/core/path-walker.ts","../../src/runtime/core/field-state-api.ts","../../src/runtime/core/surface-proxy.ts","../../src/runtime/core/errors-proxy.ts","../../src/runtime/core/field-arrays.ts","../../src/runtime/core/field-state-proxy.ts","../../src/runtime/core/defaults.ts","../../src/runtime/core/persistence/index.ts","../../src/runtime/core/error-codes.ts","../../src/runtime/core/process-form.ts","../../src/runtime/core/extract-schema-fields.ts","../../src/runtime/core/slim-primitive-gate.ts","../../src/runtime/core/schema-coerce.ts","../../src/runtime/core/register-api.ts","../../src/runtime/core/unset.ts","../../src/runtime/core/unset-walker.ts","../../src/runtime/core/values-proxy.ts","../../src/runtime/core/build-form-api.ts","../../src/runtime/core/create-form-store.ts","../../src/runtime/core/get-computed-schema.ts","../../src/runtime/core/history.ts","../../src/runtime/core/hash.ts","../../src/runtime/composables/use-abstract-form.ts","../../src/runtime/composables/use-form-context.ts"],"sourcesContent":["import type { Path, Segment } from './paths'\n\n/**\n * Structural diff/apply walker. Used by the state layer to emit per-leaf\n * patches when `setValue` replaces a subtree. Cost scales with the\n * size of the changed subtree, not the full form's leaf count.\n *\n * \"Leaves\" are anything that's not a plain object or array: strings, numbers,\n * booleans, null, undefined, Date, Map, Set, class instances, functions, etc.\n * For forms, this is the right boundary — we don't want to walk into a `Date`\n * or a `File` value.\n */\n\nexport type Patch =\n | { readonly kind: 'added'; readonly path: Path; readonly newValue: unknown }\n | { readonly kind: 'removed'; readonly path: Path; readonly oldValue: unknown }\n | {\n readonly kind: 'changed'\n readonly path: Path\n readonly oldValue: unknown\n readonly newValue: unknown\n }\n\n/**\n * True for plain objects (own prototype === Object.prototype or null) and\n * arrays. Deliberately rejects Map, Set, Date, class instances, functions —\n * those are treated as opaque leaf values.\n */\nfunction isDescendable(value: unknown): value is Record<string, unknown> | readonly unknown[] {\n if (value === null || typeof value !== 'object') return false\n if (Array.isArray(value)) return true\n const proto = Object.getPrototypeOf(value) as object | null\n return proto === null || proto === Object.prototype\n}\n\nfunction appendSegment(prefix: Path, segment: Segment): Path {\n const next: Segment[] = new Array<Segment>(prefix.length + 1)\n for (let i = 0; i < prefix.length; i++) {\n const s = prefix[i]\n // prefix indices are always in-range by construction; the nullish fallback\n // placates noUncheckedIndexedAccess without adding runtime overhead.\n next[i] = s as Segment\n }\n next[prefix.length] = segment\n return next\n}\n\n/**\n * Walk `oldValue` and `newValue` in lockstep, calling `visit(patch)` for every\n * leaf that differs. Identical values (by `Object.is`) produce no patches.\n *\n * Root replacement (when `prefix` is empty and both values are descendable\n * but of different shapes, e.g. object → array) emits a single `'changed'`\n * patch with `path: []`. Callers handling root patches should clear all\n * dependent state.\n */\nexport function diffAndApply(\n oldValue: unknown,\n newValue: unknown,\n prefix: Path,\n visit: (patch: Patch) => void\n): void {\n if (Object.is(oldValue, newValue)) return\n\n const oldIsDescendable = isDescendable(oldValue)\n const newIsDescendable = isDescendable(newValue)\n\n // Missing (undefined) <-> descendable: recurse into the descendable side so\n // every leaf emits an atomic 'added' / 'removed' patch. Populating\n // per-field metadata during form init / dynamic field additions relies on\n // this granularity. Other shape mismatches (primitive <-> object, array <->\n // object) are treated as atomic replacements.\n if (oldValue === undefined && newIsDescendable) {\n if (Array.isArray(newValue)) {\n for (let i = 0; i < newValue.length; i++) {\n diffAndApply(undefined, newValue[i], appendSegment(prefix, i), visit)\n }\n } else {\n const rec = newValue as Record<string, unknown>\n for (const k of Object.keys(rec)) {\n diffAndApply(undefined, rec[k], appendSegment(prefix, k), visit)\n }\n }\n return\n }\n\n if (oldIsDescendable && newValue === undefined) {\n if (Array.isArray(oldValue)) {\n for (let i = 0; i < oldValue.length; i++) {\n diffAndApply(oldValue[i], undefined, appendSegment(prefix, i), visit)\n }\n } else {\n const rec = oldValue as Record<string, unknown>\n for (const k of Object.keys(rec)) {\n diffAndApply(rec[k], undefined, appendSegment(prefix, k), visit)\n }\n }\n return\n }\n\n if (oldIsDescendable && newIsDescendable) {\n const oldIsArray = Array.isArray(oldValue)\n const newIsArray = Array.isArray(newValue)\n\n if (oldIsArray && newIsArray) {\n const oldArr = oldValue\n const newArr = newValue\n const max = Math.max(oldArr.length, newArr.length)\n for (let i = 0; i < max; i++) {\n diffAndApply(oldArr[i], newArr[i], appendSegment(prefix, i), visit)\n }\n return\n }\n\n if (!oldIsArray && !newIsArray) {\n const oldRec = oldValue as Record<string, unknown>\n const newRec = newValue as Record<string, unknown>\n const seen = new Set<string>()\n for (const k of Object.keys(oldRec)) {\n seen.add(k)\n diffAndApply(oldRec[k], newRec[k], appendSegment(prefix, k), visit)\n }\n for (const k of Object.keys(newRec)) {\n if (seen.has(k)) continue\n diffAndApply(oldRec[k], newRec[k], appendSegment(prefix, k), visit)\n }\n return\n }\n\n // object <-> array mismatch at this node. Treat as a full replacement.\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n if (oldIsDescendable && !newIsDescendable) {\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n if (!oldIsDescendable && newIsDescendable) {\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n return\n }\n\n // Both leaves; they differ (Object.is returned false above).\n if (oldValue === undefined) {\n visit({ kind: 'added', path: prefix, newValue })\n return\n }\n if (newValue === undefined) {\n visit({ kind: 'removed', path: prefix, oldValue })\n return\n }\n visit({ kind: 'changed', path: prefix, oldValue, newValue })\n}\n\n/**\n * Apply `source`'s changes to `target` by reassigning only the\n * top-level keys whose subtrees CONTENT-differ. Uses `diffAndApply`'s\n * structural walk (not `Object.is`) to decide which keys changed,\n * because reactive proxies and copy-on-write spreads routinely produce\n * reference-different but content-equal subtrees that we don't want\n * to reassign — reassigning fires Vue's property dep and re-triggers\n * deep watches on that subtree.\n *\n * Returns `true` on success. Returns `false` when `target` and\n * `source` have incompatible shapes (e.g. object ↔ array, or one\n * side isn't a descendable container) — the caller must fall back\n * to wholesale replacement.\n *\n * **Why** (subtle but load-bearing):\n *\n * Vue's reactive proxy for an object-typed Ref gets re-created every\n * time the Ref's value is reassigned wholesale (`form.value = next`).\n * That re-creation fires every deep watch transitively bound to the\n * Ref — even watches whose underlying sub-tree is identity-equal\n * across the swap. When one of those watches reacts by writing back\n * to the form (the canonical \"same as pickup address\" mirror\n * pattern), the watch re-fires synchronously on its own write and\n * the browser tab freezes.\n *\n * The cure is to keep `form.value`'s identity stable across writes\n * and update only the children whose CONTENT actually changed. Deep\n * watches on sibling subtrees see no dep change and stay quiet; the\n * touched child gets a new reference, so reactive consumers tracking\n * THAT path (computeds, directive bindings, etc.) re-evaluate\n * correctly.\n *\n * Old subtree references that get reassigned are orphaned but\n * unmutated — exactly what consumers (history snapshots, captured\n * `prev` callback args) need.\n */\nexport function applyChangedKeys(target: unknown, source: unknown): boolean {\n if (!isDescendable(target) || !isDescendable(source)) return false\n const targetIsArray = Array.isArray(target)\n const sourceIsArray = Array.isArray(source)\n if (targetIsArray !== sourceIsArray) return false\n\n // Find the unique first segments where target and source differ in\n // CONTENT. A root-level patch (path.length === 0) signals an\n // un-recoverable shape mismatch: tell the caller to wholesale-replace.\n // Tracking a sentinel inside `changedFirstSegments` itself rather\n // than a separate flag — keeps eslint's narrowing from declaring\n // the flag dead code (the visitor callback is opaque to its flow\n // analysis).\n const ROOT_SENTINEL = Symbol.for('attaform.applyChangedKeys.rootMismatch')\n const changedFirstSegments = new Set<string | number | symbol>()\n diffAndApply(target, source, [], (patch) => {\n if (patch.path.length === 0) {\n changedFirstSegments.add(ROOT_SENTINEL)\n return\n }\n changedFirstSegments.add(patch.path[0] as string | number)\n })\n if (changedFirstSegments.has(ROOT_SENTINEL)) return false\n\n if (targetIsArray) {\n const t = target as unknown[]\n const s = source as readonly unknown[]\n if (t.length > s.length) t.length = s.length\n for (const idx of changedFirstSegments) {\n if (typeof idx === 'symbol') continue\n const i = typeof idx === 'number' ? idx : Number(idx)\n t[i] = s[i]\n }\n } else {\n const t = target as Record<string, unknown>\n const s = source as Record<string, unknown>\n const sourceKeys = new Set(Object.keys(s))\n for (const k of Object.keys(t)) {\n if (!sourceKeys.has(k)) delete t[k]\n }\n for (const k of changedFirstSegments) {\n if (typeof k === 'symbol') continue\n t[String(k)] = s[String(k)]\n }\n }\n return true\n}\n\n/**\n * Stable structural snapshot of a value. Walks plain objects + arrays\n * recursively; non-recursable values (primitives, Date, RegExp, Map,\n * Set, functions, class instances) pass through unchanged.\n *\n * Used by setValue's callback path so the `prev` arg passed to a\n * consumer's `(prev) => next` lambda is a frozen-in-time snapshot —\n * not a live reference into `form.value` that would silently mutate\n * once the surrounding setValue commits its in-place merge. Consumers\n * routinely cache `prev` in a closure or a test variable; without this\n * clone, those caches would silently drift to the post-setValue state.\n */\nexport function structuralSnapshot<T>(value: T): T {\n if (!isDescendable(value)) return value\n if (Array.isArray(value)) {\n const out = new Array(value.length)\n for (let i = 0; i < value.length; i++) {\n out[i] = structuralSnapshot(value[i])\n }\n return out as unknown as T\n }\n const src = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const k of Object.keys(src)) {\n out[k] = structuralSnapshot(src[k])\n }\n return out as unknown as T\n}\n","/**\n * Schema-attached field metadata — the shared types used by both Zod\n * adapters and the unified `attaform/zod` entry so a consumer's data\n * flow reads the same shape regardless of which path runs at lookup.\n *\n * Storage lives in the cross-adapter `field-meta-store` core: a pair\n * of WeakMaps (single-payload for last-write-wins reads, list-of-\n * payloads for shared-schema disambiguation). Every entry's\n * `fieldMeta` re-exports the same registry-shaped object, so\n * `withMeta`/`fieldMeta.add` writes from one entry surface at lookup\n * through any other.\n *\n * `withMeta(schema, payload)` clones the schema before registering,\n * so each call gets fresh identity (the WeakMap keys on reference).\n * The cloning strategy depends on the major: Zod 4 schemas use the\n * native `.clone()`, Zod 3 schemas reconstruct via constructor +\n * `_def`. The unified entry's `withMeta` runtime-branches on which\n * one is in play.\n *\n * Reads are unified through `AbstractSchema.getFieldMetaAtPath(path)`,\n * which returns a fully-resolved `ResolvedFieldMeta` (label /\n * description / placeholder / meta) so the per-leaf and per-container\n * `FieldState` producers in core never see the version split.\n */\n\n/**\n * The metadata a consumer attaches to a schema node — short label\n * (presentational), longer description (helper text), placeholder\n * (input affordance). Declared as `interface` (not `type`) so\n * downstream apps can extend the shape via TypeScript declaration\n * merging when they want to register richer payloads (tooltips,\n * icons, badge counts, etc.):\n *\n * declare module 'attaform/zod' {\n * interface FieldMetaPayload {\n * tooltip?: string\n * }\n * }\n *\n * After augmentation, `withMeta(schema, { tooltip: '…' })` is typed\n * and `state.meta.tooltip` reads back as `string | undefined`.\n *\n * Every key is optional. Empty payloads (no keys registered) are\n * indistinguishable from \"not registered at all\" — both surface as\n * fallbacks (humanize for label, undefined for the rest).\n */\nexport interface FieldMetaPayload {\n label?: string\n description?: string\n placeholder?: string\n}\n\n/**\n * The fully-resolved metadata returned by\n * `AbstractSchema.getFieldMetaAtPath(path)`. Adapters apply the\n * precedence rules:\n *\n * - `label`: registry payload → `humanize(lastSegment)`\n * - `description`: registry payload → schema's `.describe()` value → `undefined`\n * - `placeholder`: registry payload → `undefined`\n * - `meta`: full registered payload, frozen — empty object if nothing registered\n *\n * `label` is always a non-empty string at leaves (humanize fallback\n * guarantees this for any non-numeric segment). For containers it\n * may collapse to the empty string when the path is empty (root) or\n * the segment is a numeric index — callers display \"\" or substitute\n * a context-appropriate fallback.\n */\nexport type ResolvedFieldMeta = {\n readonly label: string\n readonly description: string | undefined\n readonly placeholder: string | undefined\n readonly meta: Readonly<FieldMetaPayload>\n}\n\n/**\n * Empty resolved metadata for paths that don't exist in the schema\n * (or for adapters that don't yet implement `getFieldMetaAtPath`).\n * Callers can compare against this sentinel via referential equality\n * to detect \"no metadata available.\"\n */\nexport const EMPTY_RESOLVED_FIELD_META: ResolvedFieldMeta = Object.freeze({\n label: '',\n description: undefined,\n placeholder: undefined,\n meta: Object.freeze({}),\n})\n","/**\n * Convert a path segment into a presentable label. Used as the\n * fallback for `FieldState.label` when no explicit label is\n * registered with the schema. Splits camelCase, snake_case, and\n * kebab-case into separate words and title-cases each word.\n *\n * Numeric segments (array indices) collapse to an empty string —\n * `items[3]` should not present as `'3'`. Callers can substitute\n * their own fallback (e.g. `'Item 3'`) when this returns empty.\n *\n * Pure function, no I/O. Safe to call eagerly.\n */\nexport function humanize(segment: string | number): string {\n if (typeof segment === 'number') return ''\n const str = String(segment)\n if (str.length === 0) return ''\n // Numeric-string segments (array indices like '3'): treat as\n // empty so `items.3` doesn't surface as 'Item 3'.\n if (/^\\d+$/.test(str)) return ''\n // Split camelCase boundaries, snake_case, kebab-case, and\n // collapse runs of whitespace.\n const tokens = str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .split(' ')\n .filter((part) => part.length > 0)\n if (tokens.length === 0) return ''\n return tokens\n .map((part) => {\n const head = part[0]\n return head === undefined ? part : head.toUpperCase() + part.slice(1).toLowerCase()\n })\n .join(' ')\n}\n","import type { Path, Segment } from './paths'\n\n/**\n * The minimal slice of `AbstractSchema` the structural-completeness\n * helpers need. Declared inline (not imported from types-api) so this\n * file stays free of cyclic imports — types-api imports types-core,\n * types-core does not import types-api, and this file is consumed by\n * core/create-form-store.ts which sits between the two.\n */\nexport type SchemaForFill = {\n getDefaultAtPath(path: Path): unknown\n /**\n * Distinguish tuple (number — structural length) from unbounded\n * array (null) at `path`. `undefined` signals \"fall back to the\n * runtime's index-probe loop\" for adapters that can't introspect.\n * See `AbstractSchema.arrayShapeAtPath` for the full contract.\n */\n arrayShapeAtPath(path: Path): number | null | undefined\n}\n\n/**\n * Structured-path get/set primitives. Replace `lodash-es/get` and\n * `lodash-es/set` for internal callers that speak `Path` rather than\n * dotted strings.\n *\n * Semantics:\n * - `getAtPath` returns `undefined` for any path that traverses through\n * a non-descendable value (null, primitive, function). This preserves\n * distinctions: `null` at the exact target is returned as `null`, not\n * as `undefined`; only missing / non-descendable intermediates collapse.\n * - `setAtPath` is copy-on-write at every level from root to target. New\n * intermediate containers are created according to the segment type:\n * numeric segments produce arrays, string segments produce plain objects.\n * Sibling values at each level are preserved by reference (structural\n * sharing), so the non-touched subtrees stay reference-equal for\n * downstream `Object.is` checks in `diffAndApply`.\n */\n\nconst NOT_FOUND: unique symbol = Symbol('NOT_FOUND')\n\nfunction descendStep(value: unknown, segment: Segment): unknown | typeof NOT_FOUND {\n if (value === null || value === undefined) return NOT_FOUND\n if (typeof value !== 'object') return NOT_FOUND\n if (Array.isArray(value)) {\n if (typeof segment !== 'number') return NOT_FOUND\n if (segment < 0 || segment >= value.length) return NOT_FOUND\n return value[segment]\n }\n const record = value as Record<string, unknown>\n const key = typeof segment === 'number' ? String(segment) : segment\n if (!(key in record)) return NOT_FOUND\n return record[key]\n}\n\nexport function getAtPath(root: unknown, path: Path): unknown {\n if (path.length === 0) return root\n let current: unknown = root\n for (const segment of path) {\n const next = descendStep(current, segment)\n if (next === NOT_FOUND) return undefined\n current = next\n }\n return current\n}\n\n/**\n * Returns true iff `path` exists in `root` as a descendable chain to a leaf\n * or to a defined value. Distinguishes \"exists and is undefined\" (rare but\n * possible with explicit assignment) from \"missing\".\n */\nexport function hasAtPath(root: unknown, path: Path): boolean {\n if (path.length === 0) return true\n let current: unknown = root\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i] as Segment\n const next = descendStep(current, segment)\n if (next === NOT_FOUND) return false\n current = next\n }\n const last = path[path.length - 1] as Segment\n if (current === null || current === undefined) return false\n if (typeof current !== 'object') return false\n if (Array.isArray(current)) {\n return typeof last === 'number' && last >= 0 && last < current.length\n }\n const key = typeof last === 'number' ? String(last) : last\n return key in (current as Record<string, unknown>)\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false\n if (Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value) as object | null\n return proto === null || proto === Object.prototype\n}\n\nexport function setAtPath(root: unknown, path: Path, value: unknown): unknown {\n return setAtPathOffset(root, path, value, 0)\n}\n\nfunction setAtPathOffset(root: unknown, path: Path, value: unknown, offset: number): unknown {\n if (offset >= path.length) return value\n\n const head = path[offset] as Segment\n const nextOffset = offset + 1\n\n if (typeof head === 'number') {\n const arr = Array.isArray(root) ? [...root] : []\n // Extend sparse arrays with undefined slots up to the target index.\n while (arr.length <= head) arr.push(undefined)\n arr[head] = setAtPathOffset(arr[head], path, value, nextOffset)\n return arr\n }\n\n const rec: Record<string, unknown> = isPlainRecord(root) ? { ...root } : {}\n rec[head] = setAtPathOffset(rec[head], path, value, nextOffset)\n return rec\n}\n\n/**\n * Copy-on-write deletion of `path` from `root`. Returns a fresh root\n * with the targeted leaf (or container) removed; siblings stay\n * reference-equal. Missing intermediates short-circuit and return\n * `root` unchanged.\n *\n * Array semantics: deleting a numeric index splices the array (length\n * shrinks by one). Object semantics: deleting a string key removes the\n * own-property and shrinks the key set by one.\n *\n * Used by the persistence layer's `clearPersistedDraft(path)` to wipe\n * a single subpath from the persisted entry without disturbing other\n * paths the user might have opted in.\n */\nexport function deleteAtPath(root: unknown, path: Path): unknown {\n return deleteAtPathOffset(root, path, 0)\n}\n\nfunction deleteAtPathOffset(root: unknown, path: Path, offset: number): unknown {\n if (offset >= path.length) return undefined\n\n const head = path[offset] as Segment\n const isLeafStep = offset === path.length - 1\n const nextOffset = offset + 1\n\n if (typeof head === 'number') {\n if (!Array.isArray(root)) return root\n if (head < 0 || head >= root.length) return root\n if (isLeafStep) {\n const arr = [...root]\n arr.splice(head, 1)\n return arr\n }\n const arr = [...root]\n arr[head] = deleteAtPathOffset(arr[head], path, nextOffset)\n return arr\n }\n\n if (!isPlainRecord(root)) return root\n if (isLeafStep) {\n const rec: Record<string, unknown> = { ...root }\n delete rec[head]\n return rec\n }\n if (!(head in root)) return root\n const rec: Record<string, unknown> = { ...root }\n rec[head] = deleteAtPathOffset(rec[head], path, nextOffset)\n return rec\n}\n\n/**\n * Recursive merge that fills consumer-supplied gaps with the schema's\n * prescribed defaults. The runtime calls this on every `setValueAtPath`\n * write (and on whole-form callback returns) so the form remains\n * structurally complete after the write.\n *\n * Semantics:\n * - Plain object: every schema-default key not present in `consumer`\n * is filled with the schema default's value at that key. Schema-only\n * keys recurse into structural completeness; consumer-only keys (not\n * in the schema) survive untouched (validation flags them).\n * - Array: each consumer element is merged with the SCHEMA element\n * default (looked up via `schema.getDefaultAtPath([...path, i])`).\n * Length follows the consumer — padding past the consumer's length\n * is `setAtPathWithSchemaFill`'s job, not this function's.\n * - `null` consumer wins (a deliberate \"clear\" signal — validation\n * catches misuse against non-nullable shapes).\n * - `undefined` consumer falls back to the schema default (treats\n * undefined as \"missing\"). When the schema default is also\n * undefined the result is undefined — schema and consumer agree.\n * - Primitives, Date, RegExp, Map, Set, class instances: consumer\n * wins; no recursion (these are leaves under `isPlainRecord`).\n *\n * Idempotent short-circuit: when consumer is structurally complete\n * relative to defaults the function returns `consumer` by reference,\n * so common-case writes (consumer already complete) allocate nothing.\n */\n/**\n * Resolve the array shape at `scratch`. Returns the tuple's\n * structural length, `null` for unbounded arrays, or `undefined`\n * if the adapter doesn't support `arrayShapeAtPath` (signalling\n * the fallback probe loop).\n *\n * The fallback probes at index `1_000_000` (tuple → `undefined`;\n * array → element default), then probes sequentially up to the cap\n * to discover the tuple length. Built-in zod adapters return a\n * definitive shape so this never fires for them; the fallback\n * exists for third-party adapters that haven't implemented the\n * method.\n */\nfunction resolveArrayShape(schema: SchemaForFill, scratch: Segment[]): number | null | undefined {\n const shape = schema.arrayShapeAtPath(scratch)\n if (shape !== undefined) return shape\n // Legacy probe: high-index lookup distinguishes tuple from array.\n const TUPLE_PROBE_INDEX = 1_000_000\n scratch.push(TUPLE_PROBE_INDEX)\n const probe = schema.getDefaultAtPath(scratch)\n scratch.pop()\n if (probe !== undefined) return null // unbounded array\n // Tuple-like: walk forward to find the structural length. Cap at\n // 1024 to protect against pathological recursive lazies.\n let n = 0\n while (n < 1024) {\n scratch.push(n)\n const v = schema.getDefaultAtPath(scratch)\n scratch.pop()\n if (v === undefined) break\n n++\n }\n return n\n}\n\nexport function mergeStructural(\n schema: SchemaForFill,\n path: Path,\n consumer: unknown,\n defaultValue: unknown = schema.getDefaultAtPath(path)\n): unknown {\n // Internal recursion uses a single mutable scratch path: each level\n // pushes its segment before descending and pops on return. Eliminates\n // the per-recursion `[...path, key]` / `[...path, i]` allocation\n // that previously fired on every object key + every array element.\n // Schema adapters (zod / standard-schema) read `getDefaultAtPath`\n // synchronously and don't retain the path, so passing the live\n // scratch is safe; if a future adapter needed retention, snapshot\n // inside that adapter rather than allocating per-call here.\n const scratch: Segment[] = path.slice()\n return mergeStructuralImpl(schema, scratch, consumer, defaultValue)\n}\n\nfunction mergeStructuralImpl(\n schema: SchemaForFill,\n scratch: Segment[],\n consumer: unknown,\n defaultValue: unknown\n): unknown {\n // Consumer is missing — fall back to the schema default. When the\n // schema default itself is `undefined` (path doesn't exist in the\n // schema), the result is `undefined` and we don't fight it.\n if (consumer === undefined) return defaultValue\n\n // Null wins: deliberate consumer signal. Schema-validation catches\n // null-vs-non-nullable; runtime doesn't override consumer intent.\n if (consumer === null) return null\n\n // Array branch: distinguish tuple-like (fixed length) from array\n // (unbounded) via `arrayShapeAtPath`. Tuples pad consumer to the\n // structural length; unbounded arrays follow the consumer's length\n // and reuse one element default across positions.\n if (Array.isArray(consumer)) {\n const shape = resolveArrayShape(schema, scratch)\n const isTuple = typeof shape === 'number'\n const targetLen = isTuple ? shape : consumer.length\n // Unbounded array: every position resolves to the same element\n // default — query once and reuse. Tuples query per-position\n // since each slot carries its own default.\n let cachedElementDefault: unknown\n let cachedElementDefaultRead = false\n let mutated = targetLen > consumer.length\n const out = consumer.slice() as unknown[]\n while (out.length < targetLen) out.push(undefined)\n for (let i = 0; i < targetLen; i++) {\n scratch.push(i)\n let elemDefault: unknown\n if (isTuple) {\n elemDefault = schema.getDefaultAtPath(scratch)\n } else {\n if (!cachedElementDefaultRead) {\n cachedElementDefault = schema.getDefaultAtPath(scratch)\n cachedElementDefaultRead = true\n }\n elemDefault = cachedElementDefault\n }\n const consumerElem = i < consumer.length ? consumer[i] : undefined\n const merged = mergeStructuralImpl(schema, scratch, consumerElem, elemDefault)\n scratch.pop()\n if (merged !== consumerElem) {\n out[i] = merged\n mutated = true\n }\n }\n return mutated ? out : consumer\n }\n\n // Plain object: fill missing keys from default, recurse on present\n // keys. Consumer-only keys pass through.\n if (isPlainRecord(consumer)) {\n if (!isPlainRecord(defaultValue)) {\n // Default is non-record (or undefined / leaf) — nothing to fill;\n // consumer wins as-is. Recurse just in case consumer holds nested\n // keys that the schema knows about at deeper paths (rare).\n return consumer\n }\n let mutated = false\n const out: Record<string, unknown> = { ...consumer }\n // Fill schema-default keys missing from consumer.\n for (const key of Object.keys(defaultValue)) {\n if (!(key in consumer) || consumer[key] === undefined) {\n const defAtKey = defaultValue[key]\n // Recurse so that filling produces a structurally-complete\n // sub-tree (covers nested-object defaults that themselves\n // contain wrappers / unions).\n scratch.push(key)\n const filled = mergeStructuralImpl(schema, scratch, undefined, defAtKey)\n scratch.pop()\n if (filled !== undefined) {\n out[key] = filled\n mutated = true\n }\n }\n }\n // Recurse into consumer-supplied keys to catch nested gaps.\n for (const key of Object.keys(consumer)) {\n scratch.push(key)\n const merged = mergeStructuralImpl(schema, scratch, consumer[key], defaultValue[key])\n scratch.pop()\n if (merged !== consumer[key]) {\n out[key] = merged\n mutated = true\n }\n }\n return mutated ? out : consumer\n }\n\n // Leaf-ish (primitives, Date, RegExp, Map, Set, class instances) —\n // consumer wins, no recursion.\n return consumer\n}\n\n/**\n * Schema-aware variant of `setAtPath`. When extending past array\n * length, pads new positions with the schema's element default\n * instead of `undefined`. When descending into an object whose\n * intermediate property is missing, fills the intermediate with\n * the schema's default at that sub-path.\n *\n * `value` is the already-mergeStructural'd target value — this\n * function only handles INTERMEDIATE fill. The caller (typically\n * `setValueAtPath` on the form store) is responsible for completing\n * the leaf.\n *\n * Performance: schema lookups happen only at gap sites. The common\n * case (write to existing slot) does a copy-on-write spread without\n * touching the schema. Misuse (`setValue('posts.21', x)` against an\n * empty array) costs `getDefaultAtPath` once for the array element\n * default (cached via `lastArrayDefault`/`lastArrayPathPrefix` for\n * the duration of the call) and N pad inserts.\n */\nexport function setAtPathWithSchemaFill(\n root: unknown,\n schema: SchemaForFill,\n fullPath: Path,\n value: unknown\n): unknown {\n if (fullPath.length === 0) return value\n return setAtPathWithSchemaFillImpl(root, schema, fullPath, value, 0)\n}\n\nfunction setAtPathWithSchemaFillImpl(\n root: unknown,\n schema: SchemaForFill,\n fullPath: Path,\n value: unknown,\n startIdx: number\n): unknown {\n if (startIdx >= fullPath.length) return value\n\n const head = fullPath[startIdx] as Segment\n const isLeafStep = startIdx === fullPath.length - 1\n\n if (typeof head === 'number') {\n const arr = Array.isArray(root) ? [...root] : []\n const prefix = fullPath.slice(0, startIdx)\n // Pad with element defaults if extending past length. Tuple-vs-\n // array detection mirrors mergeStructural: probe at a high index\n // — tuples return `undefined` (out of range), unbounded arrays\n // return the element default. The previous heuristic (compare two\n // adjacent defaults via Object.is) gave wrong answers for arrays\n // of objects (each call yields a fresh object, identity differs)\n // AND for tuples of identical primitives (Object.is(0, 0) === true).\n if (arr.length < head) {\n const scratch: Segment[] = prefix.slice() as Segment[]\n const shape = resolveArrayShape(schema, scratch)\n const tupleLike = typeof shape === 'number'\n // For unbounded arrays, every position resolves to the same\n // element default — cache the lookup once. For tuples, query\n // per-position so each slot's default lands at its own index.\n let cachedArrayDefault: unknown\n if (!tupleLike) {\n scratch.push(0)\n cachedArrayDefault = schema.getDefaultAtPath(scratch)\n scratch.pop()\n }\n while (arr.length < head) {\n const idx = arr.length\n if (tupleLike) {\n scratch.push(idx)\n arr.push(schema.getDefaultAtPath(scratch))\n scratch.pop()\n } else {\n arr.push(cachedArrayDefault)\n }\n }\n }\n\n if (isLeafStep) {\n arr[head] = value\n return arr\n }\n\n // Intermediate step: ensure the slot at `head` is structurally\n // complete BEFORE recursing into the rest of the path. Without\n // this fill, recursion starts from `undefined` and the next level\n // builds a fresh `{}` populated only by the keys the path\n // actually touches — sibling fields (other Person keys, other\n // Address keys) get silently dropped. Same intermediate-fill\n // semantic the object branch applies a few lines below.\n let childRoot = arr[head]\n if (childRoot === undefined || (childRoot !== null && typeof childRoot !== 'object')) {\n childRoot = schema.getDefaultAtPath([...prefix, head])\n }\n arr[head] = setAtPathWithSchemaFillImpl(childRoot, schema, fullPath, value, startIdx + 1)\n return arr\n }\n\n // Object key.\n const rec: Record<string, unknown> = isPlainRecord(root) ? { ...root } : {}\n if (isLeafStep) {\n rec[head] = value\n return rec\n }\n\n // Intermediate: ensure the child exists, filling from the schema\n // default if missing or non-descendable.\n const existing = rec[head]\n let childRoot: unknown\n if (existing === undefined || (existing !== null && typeof existing !== 'object')) {\n const intermPath: Segment[] = [...fullPath.slice(0, startIdx + 1)]\n const intermDefault = schema.getDefaultAtPath(intermPath)\n childRoot = intermDefault\n } else {\n childRoot = existing\n }\n rec[head] = setAtPathWithSchemaFillImpl(childRoot, schema, fullPath, value, startIdx + 1)\n return rec\n}\n","import { computed, type ComputedRef } from 'vue'\nimport type { FieldState, ValidationError } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { EMPTY_RESOLVED_FIELD_META } from './field-meta'\nimport { humanize } from './humanize'\nimport { hasAtPath } from './path-walker'\nimport {\n canonicalizePath,\n isPathPrefix,\n segmentsForPathKey,\n type Path,\n type PathKey,\n} from './paths'\n\n/**\n * Reactive field-state accessor. Combines per-field records, DOM\n * focus/blur state, validation errors, and adapter-resolved metadata\n * into a single `FieldState` object suitable for templates:\n *\n * const emailState = getFieldState('email')\n * emailState.value.dirty, .errors, .focused, .label, ...\n *\n * All reads go through Vue computeds so consumers get fine-grained\n * reactivity — a change to one field's focus does not invalidate\n * computeds watching another field.\n *\n * The accessor returns one shape — `FieldState<unknown>` — at every\n * path. At leaf paths, fields read from per-leaf primitives. At\n * container paths, the same fields aggregate over descendant leaves\n * (disjunction for event-presence: dirty/focused/touched/validating;\n * conjunction for absence/uniformity: pristine/valid/blank). DU\n * containers traverse only the active variant via `hasAtPath` on\n * the live form value.\n *\n * Memoised per canonical path key — repeated calls with the same\n * path return the same `ComputedRef` so consumers don't accumulate\n * duplicate Vue subscriptions.\n */\nexport type { FieldState }\n\nexport function buildFieldStateAccessor<F extends GenericForm>(state: FormStore<F>) {\n // Per-path memoisation so `getFieldStateAt(p)` returns the same\n // `ComputedRef` reference on repeated reads with the same canonical\n // path. The Map's lifetime equals the form-store's; cleared\n // implicitly when the store is GC'd.\n const cache = new Map<PathKey, ComputedRef<FieldState<unknown>>>()\n\n return function getFieldState(pathInput: string | Path): ComputedRef<FieldState<unknown>> {\n const { segments, key } = canonicalizePath(pathInput)\n const cached = cache.get(key)\n if (cached !== undefined) return cached\n const c = computed<FieldState<unknown>>(() =>\n state.schema.isLeafAtPath(segments)\n ? buildLeafFieldState(state, segments, key)\n : buildContainerFieldState(state, segments, key)\n )\n cache.set(key, c)\n return c\n }\n}\n\n/**\n * Per-leaf computation: reads the leaf-specific reactive sources.\n */\nfunction buildLeafFieldState<F extends GenericForm>(\n state: FormStore<F>,\n segments: Path,\n key: PathKey\n): FieldState<unknown> {\n const record = state.fields.get(key)\n const value = state.getValueAtPath(segments)\n const original = state.originals.get(key)?.value\n const pristine = state.isPristineAtPath(segments)\n const schemaForKey = state.schemaErrors.get(key)\n const blankForKey = state.derivedBlankErrors.value.get(key)\n const userForKey = state.userErrors.get(key)\n const errors: ValidationError[] = []\n if (schemaForKey !== undefined) errors.push(...schemaForKey)\n if (blankForKey !== undefined) errors.push(...blankForKey)\n if (userForKey !== undefined) errors.push(...userForKey)\n const validating = (state.fieldValidationCounts.get(key) ?? 0) > 0\n // `valid` mirrors `meta.valid` per-path: when the sub-schema at\n // this path declares async work, gate the answer on the form-wide\n // `firstValidationDone` so the surface doesn't lie about a\n // yet-to-arrive verdict. Sync-only sub-schemas (e.g. a bare\n // `z.string()` leaf) skip the gate — there's nothing to wait on,\n // and clamping every such field to `false` at mount would defeat\n // the green-checkmark UX pattern that `field.valid` is built for.\n const gated = state.pathHasAsyncValidation(segments) && !state.firstValidationDone.value\n const valid = !gated && errors.length === 0 && !validating\n const elementRecord = state.elements.get(key)\n const elementsArr: readonly HTMLElement[] = elementRecord\n ? Object.freeze([...elementRecord.elements])\n : EMPTY_ELEMENTS\n const firstElement: HTMLElement | null = elementsArr[0] ?? null\n const resolved = state.schema.getFieldMetaAtPath\n ? state.schema.getFieldMetaAtPath(segments)\n : EMPTY_RESOLVED_FIELD_META\n const lastSegment = segments.length === 0 ? '' : (segments[segments.length - 1] ?? '')\n const label = resolved.label || humanize(lastSegment)\n return {\n value,\n original,\n pristine,\n dirty: !pristine,\n focused: record?.focused ?? null,\n blurred: record?.blurred ?? null,\n touched: record?.touched ?? null,\n connected: record?.connected ?? false,\n element: firstElement,\n elements: elementsArr,\n updatedAt: record?.updatedAt ?? null,\n errors,\n validating,\n valid,\n path: segments,\n blank: state.blankPaths.has(key),\n label,\n description: resolved.description,\n placeholder: resolved.placeholder,\n meta: resolved.meta,\n }\n}\n\n/**\n * Per-container aggregation: rolls up descendant-leaf state per the\n * rule sheet. Reads only ACTIVE-variant descendants — DU branches\n * not currently selected by the discriminator are filtered out via\n * `hasAtPath` on the live form value.\n *\n * Aggregation rules (matches `docs/api/use-form-return.md`):\n * - pristine / valid / blank: conjunction (all descendants)\n * - dirty: !pristine\n * - focused / blurred / touched / connected / validating: disjunction (any descendant)\n * - errors: concat + sort by `pathOrdinal` (schema-declaration order)\n * - updatedAt: max ISO timestamp (lex-compared) over descendants\n * - value / original: live subtree at the path\n * - element / elements: nothing bound at containers — null / empty\n * - label / description / placeholder / meta: from `getFieldMetaAtPath`\n */\nfunction buildContainerFieldState<F extends GenericForm>(\n state: FormStore<F>,\n segments: Path,\n _key: PathKey\n): FieldState<unknown> {\n // Read live form value first so the access participates in dep\n // tracking; the discriminator key write that switches a DU variant\n // shows up here and re-runs the computed.\n const formValue = state.form.value\n const value = state.getValueAtPath(segments)\n const original = state.originals.get(canonicalizePath(segments).key)?.value\n // Enumerate active descendant leaves under the container path.\n // The `originals` Map tracks every leaf the form has ever seen;\n // filter via `isPathPrefix` for descendant-membership and via\n // `hasAtPath(formValue, leafSeg)` to keep only the active-variant\n // leaves (DU switches reshape `formValue` wholesale, so this is\n // the live ground truth).\n let pristine = true\n let blank = true\n let dirty = false\n let focused = false\n let blurred = false\n let touched = false\n let connected = false\n let validating = false\n let updatedAt: string | null = null\n let asyncPending = false\n for (const [, entry] of state.originals) {\n if (!isPathPrefix(segments, entry.segments)) continue\n if (segments.length === entry.segments.length) continue // self isn't a descendant\n if (!hasAtPath(formValue, entry.segments)) continue\n const leafKey = canonicalizePath(entry.segments).key\n const leafRecord = state.fields.get(leafKey)\n if (!state.isPristineAtPath(entry.segments)) {\n pristine = false\n dirty = true\n }\n if (!state.blankPaths.has(leafKey)) blank = false\n if (leafRecord?.focused === true) focused = true\n if (leafRecord?.blurred === true) blurred = true\n if (leafRecord?.touched === true) touched = true\n if (leafRecord?.connected === true) connected = true\n if ((state.fieldValidationCounts.get(leafKey) ?? 0) > 0) validating = true\n if (state.pathHasAsyncValidation(entry.segments)) asyncPending = true\n const ts = leafRecord?.updatedAt\n if (ts !== undefined && ts !== null) {\n // ISO 8601 timestamps sort lexicographically; max-string is\n // the most-recent write.\n if (updatedAt === null || ts > updatedAt) updatedAt = ts\n }\n }\n // Aggregate errors at this prefix. Drives `form.fields(p).errors`,\n // `form.errors(p)`, and `form.meta.errors` through one helper so\n // the three surfaces read identically. Active-variant filter\n // applied via the same `hasAtPath` gate the descendant walk used.\n // `valid` derives from this single source so the two fields can\n // never disagree.\n const errors = aggregateErrorsAt(state, segments)\n // A container's own sub-schema can also declare async work — a\n // top-level `.refine(async ...)` on the root, or a cross-field\n // refine on a sub-object — and those don't show up in any per-\n // leaf `pathHasAsyncValidation` reading. Check the container's\n // OWN path too, so the firstValidationDone gate fires until that\n // pass lands.\n if (!asyncPending && state.pathHasAsyncValidation(segments)) asyncPending = true\n const gated = asyncPending && !state.firstValidationDone.value\n const valid = !gated && errors.length === 0 && !validating\n const resolved = state.schema.getFieldMetaAtPath\n ? state.schema.getFieldMetaAtPath(segments)\n : EMPTY_RESOLVED_FIELD_META\n const lastSegment = segments.length === 0 ? '' : (segments[segments.length - 1] ?? '')\n const label = resolved.label || humanize(lastSegment)\n return {\n value,\n original,\n pristine,\n dirty,\n focused,\n blurred,\n touched,\n connected,\n element: null,\n elements: EMPTY_ELEMENTS,\n updatedAt,\n errors,\n validating,\n valid,\n path: segments,\n blank,\n label,\n description: resolved.description,\n placeholder: resolved.placeholder,\n meta: resolved.meta,\n }\n}\n\n/**\n * Walk the merged error stores at every leaf descendant of `prefix`,\n * filter inactive variants via `hasAtPath`, and return the\n * concatenated errors sorted by schema-declaration order\n * (`pathOrdinals` — same ordering metaErrors uses today).\n *\n * Shared by container `errors` aggregation here and by the top-level\n * `metaErrors` / `form.errors(path)` aggregation in `build-form-api.ts`\n * — one helper, three call sites, no drift.\n */\nexport function aggregateErrorsAt<F extends GenericForm>(\n state: FormStore<F>,\n prefix: Path\n): ValidationError[] {\n const formValue = state.form.value\n const buckets = new Map<number, ValidationError[]>()\n const collect = (errs: ReadonlyMap<PathKey, ValidationError[]>): void => {\n for (const [pathKey, list] of errs) {\n if (list.length === 0) continue\n // Resolve the path's segments via the canonical PathKey ↔\n // Segment[] inverse cache (`segmentsForPathKey`). Covers\n // every shape the error stores can hold — leaf paths,\n // container paths (cross-field refines), and the form-level\n // `[]` key — without depending on `originals` (which only\n // tracks leaves).\n const segs = segmentsForPathKey(pathKey)\n if (segs === null) continue\n if (!isPathPrefix(prefix, segs)) continue\n // Skip inactive variants. Form-level errors (path === []) are\n // always retained — they're not variant-bound. Container-level\n // errors (cross-field refines on a container path) are\n // filtered when their CONTAINER path is reachable; the\n // refine pinned the error at the container, not at any\n // particular leaf.\n if (segs.length > 0 && !hasAtPath(formValue, segs)) continue\n const ordinal = state.ensurePathOrdinal(pathKey)\n const existing = buckets.get(ordinal)\n if (existing === undefined) buckets.set(ordinal, [...list])\n else existing.push(...list)\n }\n }\n collect(state.schemaErrors)\n collect(state.derivedBlankErrors.value)\n collect(state.userErrors)\n if (buckets.size === 0) return []\n return [...buckets.entries()].sort(([a], [b]) => a - b).flatMap(([, errs]) => errs)\n}\n\n// Frozen empty array shared across \"no elements bound\" reads so\n// consumers can `===`-compare against a stable reference and the\n// computed doesn't allocate a new array on every re-evaluation when\n// the path has no registered elements.\nconst EMPTY_ELEMENTS: readonly HTMLElement[] = Object.freeze([])\n","import type { AbstractSchema } from '../types/types-api'\nimport { canonicalizePath, type Path, type Segment } from './paths'\n\n/**\n * Leaf-aware callable Proxy machinery shared by `form.values`,\n * `form.errors`, and `form.fields`. One generic builder; per-surface\n * specialisation lives in the surface's own factory file (see\n * `field-state-proxy.ts` for fields).\n *\n * Two-level contract:\n *\n * - At a **container path** (`schema.isLeafAtPath(segments) === false`)\n * the `get` trap descends to a sub-proxy. No leaf-key injection — a\n * schema field literally named `dirty` at depth 2+ stays reachable.\n * - At a **leaf path** (`schema.isLeafAtPath(segments) === true`)\n * the `get` trap terminates. Two flavours:\n * - `leafKeys` undefined (errors/values): returns\n * `resolveLeaf(segments)` directly. The terminal IS the value.\n * - `leafKeys` provided (fields): returns a leaf-VIEW proxy that\n * exposes only `leafKeys` as terminal reads off `resolveLeaf`'s\n * return. FIELD_STATE_KEYS injection happens HERE only.\n *\n * Both proxies are callable (function-target with `apply` trap):\n * - `proxy()` → root proxy (same as no-paren)\n * - `proxy('a.b.c')` / `proxy(['a', 'b', 'c'])` → walks to that path,\n * returns whatever the dotted form would (leaf or container proxy).\n *\n * Symbol keys pass through to the function target so Vue's reactivity\n * sigils (`Symbol(__v_isRef)`, `Symbol(__v_isReadonly)`, etc.) and\n * iteration symbols don't accidentally route through the schema-aware\n * branch.\n *\n * Per-path proxy memoisation: each surface keeps its own\n * `Map<PathKey, CallableSurface>` so repeated reads of the same path\n * return the same Proxy object — referential equality matters for\n * downstream effect tracking and Vue's render diff.\n */\n\n/**\n * Tests an integer-like string without leading zeros. Mirrors the\n * `INTEGER_SEGMENT` regex in paths.ts. Inlined here to avoid exporting\n * an internal helper across the module boundary.\n */\nconst INTEGER_SEGMENT = /^(?:0|[1-9]\\d*)$/\n\n/**\n * Convert a string property key to the canonical Segment form. Integer-\n * looking strings (`'0'`, `'1'`, `'42'`) become numbers so that paths\n * accumulated through proxy descent match what `canonicalizePath`\n * produces from a dotted-string call (e.g. `proxy('users.0.name')`).\n */\nfunction keyToSegment(key: string): Segment {\n return INTEGER_SEGMENT.test(key) ? Number(key) : key\n}\n\nexport type SurfaceOptions<TLeaf> = {\n /** Schema instance; queried via `isLeafAtPath` at every descent. */\n readonly schema: AbstractSchema<unknown, unknown>\n /**\n * Resolve the surface's terminal value at a leaf path. Called at every\n * leaf-path read; consumers should memoise inside `resolveLeaf` if the\n * resolution is expensive (the field-state surface uses\n * `buildFieldStateAccessor` which returns a memoised `ComputedRef`).\n */\n readonly resolveLeaf: (path: Path) => TLeaf\n /**\n * If provided: at a leaf path, the surface proxy returns a leaf-VIEW\n * proxy exposing only these keys as terminal reads off the resolved\n * leaf. `readLeafKey` performs the extraction.\n *\n * If undefined: at a leaf path, the surface proxy returns\n * `resolveLeaf(path)` directly. No further proxy wrap.\n */\n readonly leafKeys?: ReadonlySet<string>\n /**\n * Extracts a leaf-key value from the resolved leaf. Required when\n * `leafKeys` is provided. The `key` arg is guaranteed to be in\n * `leafKeys`. Reads inside this function happen during a Vue effect's\n * run, so dependency tracking propagates from `resolveLeaf`'s return.\n */\n readonly readLeafKey?: (leaf: TLeaf, key: string) => unknown\n /**\n * Materialise the container at `segments` into a plain JSON-friendly\n * object. Called by the container proxy's `toJSON` / `toString` /\n * `Symbol.toPrimitive('default')` traps every time a consumer\n * stringifies the proxy. Reads inside this callback happen at call\n * time inside the consumer's active effect, so Vue's dependency\n * tracking captures every reactive read (error stores, the form\n * Ref, computed maps) — `JSON.stringify(form.errors)` in a render\n * function or `{{ form.errors }}` in a template re-runs whenever\n * the underlying state changes.\n *\n * If undefined: containers serialise to `{}`. Provided so each\n * surface controls its own materialisation strategy:\n * - `errors`: sparse — only paths that actually have errors,\n * active-path-filtered.\n * - `fields`: dense — every schema-leaf descendant snapshotted as\n * a `FieldState`.\n * - `values`: not built on this generic; its own proxy serialises\n * the inner readonly proxy directly.\n */\n readonly materializeContainer?: (segments: readonly Segment[]) => unknown\n /**\n * Terminal for the `apply` trap (call-form). `proxy('a.b.c')` and\n * `proxy()` route here, separate from the dot/bracket `get` trap\n * (which continues to descend at containers). This is what lets\n * `form.fields.pickup` navigate while `form.fields('pickup')`\n * returns the aggregated container `FieldState`; same dual-mode\n * applies to `form.errors(path)`.\n *\n * `proxy()` (no-arg) calls `resolveCallTarget([])` so consumers\n * grab the root state with one call (`form.fields()` aggregates\n * over the whole form).\n */\n readonly resolveCallTarget: (path: Path) => unknown\n}\n\n/**\n * The public shape of a built surface. Drill (dot/bracket) OR call\n * (apply trap with a path arg). The TypeScript shape stays loose at\n * the runtime layer; per-surface types in `types-api.ts` narrow the\n * descent.\n */\nexport type SurfaceProxy = ((path?: string | Path) => unknown) & Record<string, unknown>\n\nexport function buildSurfaceProxy<TLeaf>(opts: SurfaceOptions<TLeaf>): SurfaceProxy {\n // Per-path container Proxy cache. Key = canonical PathKey\n // (`JSON.stringify(segments)`). Lifetime = one buildSurfaceProxy call.\n const containerCache = new Map<string, SurfaceProxy>()\n // Per-path leaf-VIEW Proxy cache. Only populated when `leafKeys` is\n // configured. Same key shape, separate Map so a path with the same\n // canonical key but different leaf-ness (impossible in practice) wouldn't\n // collide.\n const leafViewCache = new Map<string, SurfaceProxy>()\n // Per-path \"schema has a field here\" cache. Used by the\n // schema-authority check that resolves collisions between built-in\n // method names (`toString`, `valueOf`) and schema fields literally\n // sharing those names. Same lifetime as the leaf/container caches.\n const existsCache = new Map<string, boolean>()\n\n /** True iff the schema has a field at `segs` (leaf OR container). */\n function schemaHasPath(segs: readonly Segment[]): boolean {\n const cacheKey = JSON.stringify(segs)\n const cached = existsCache.get(cacheKey)\n if (cached !== undefined) return cached\n const result = opts.schema.getSlimPrimitiveTypesAtPath(segs).size > 0\n existsCache.set(cacheKey, result)\n return result\n }\n\n /** Resolve a path to its leaf terminal or container sub-proxy. */\n function descendOrTerminate(segs: readonly Segment[]): unknown {\n const isLeaf = opts.schema.isLeafAtPath(segs)\n if (isLeaf) {\n if (opts.leafKeys !== undefined) return leafViewProxyAt(segs)\n return opts.resolveLeaf(segs)\n }\n return containerProxyAt(segs)\n }\n\n function containerProxyAt(segments: readonly Segment[]): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = containerCache.get(cacheKey)\n if (existing !== undefined) return existing\n\n // Container-shaped primitive coercion. The materialiser (when set)\n // is invoked on every call so reactive reads (error stores, the\n // form Ref) are tracked inside the consumer's active effect — the\n // proxy itself is cached per-path, but its serialised form is\n // computed fresh on every stringify, so there is no staleness.\n //\n // - `valueOf` follows `Object.prototype.valueOf` semantics: return\n // the receiver (the proxy itself, via dynamic `this`). Returning\n // a non-primitive keeps OrdinaryToPrimitive's `valueOf` →\n // `toString` fallback well-formed for any code path that\n // bypasses our `Symbol.toPrimitive` shortcut.\n // - `toString` returns `JSON.stringify(materialised)` so direct\n // method calls produce the same string as operator coercion.\n // - `Symbol.toPrimitive('number')` always returns `NaN` — a\n // container has no meaningful number coercion.\n const snapshotContainer = (): unknown =>\n opts.materializeContainer === undefined ? {} : opts.materializeContainer(segments)\n const containerToJSON = (): unknown => snapshotContainer()\n const containerToString = (): string => JSON.stringify(snapshotContainer())\n function containerValueOf(this: unknown): unknown {\n return this\n }\n const containerToPrimitive = (hint: string): string | number =>\n hint === 'number' ? NaN : containerToString()\n\n // Arrow-function target (so `typeof proxy === 'function'` and `apply`\n // fires). Arrow functions have no `prototype` property, which avoids\n // the \"ownKeys trap must include 'prototype'\" Proxy invariant — `length`\n // and `name` ARE present but configurable=true, so we can omit them\n // from ownKeys safely.\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n // proxy() returns the call-target at THIS path (so\n // `form.fields()` resolves the root aggregation). proxy(arg)\n // walks the absolutised arg path through the call-target.\n const arg = args[0] as string | Path | undefined\n if (arg === undefined) return opts.resolveCallTarget(segments as Path)\n const { segments: argSegs } = canonicalizePath(arg)\n return opts.resolveCallTarget(argSegs)\n },\n get(_, key: string | symbol): unknown {\n // Symbol passthrough: Vue's reactivity sigils + iteration symbols\n // resolve against the function target, not the schema-aware branch.\n if (typeof key === 'symbol') {\n // `Symbol.toPrimitive`: handles `String(proxy)` / `Number(proxy)`\n // / template-literal coercion in one shot, bypassing\n // OrdinaryToPrimitive's `toString` → `valueOf` walk (both of\n // which would otherwise route through schema descent below and\n // return sub-proxies — non-primitives — making the coercion\n // throw `TypeError(\"Cannot convert object to primitive value\")`).\n if (key === Symbol.toPrimitive) return containerToPrimitive\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n // `toJSON`: containers serialise to `{}`. The function-target\n // Proxy is `typeof === 'function'`, which JSON.stringify normally\n // omits — `toJSON` short-circuits that path. Consumers who want\n // structural data use `form.values.<container>` instead.\n if (key === 'toJSON') return containerToJSON\n const childSegs = [...segments, keyToSegment(key)]\n // Direct method-call coercion (`proxy.toString()` /\n // `proxy.valueOf()`): without intercepting these names, the\n // schema-aware descent below would return a sub-proxy and the\n // caller would get back another callable, not a primitive. We\n // resolve the collision with **schema authority**: if the\n // schema has a field literally named `toString` / `valueOf` at\n // this depth, that field wins (descent proceeds). Otherwise the\n // primitive-coercion handler wins. This keeps the Symbol.toPrimitive\n // shortcut consistent with direct method calls AND avoids the\n // FIELD_STATE_KEYS-style shadowing that 0.14 explicitly killed.\n if (key === 'toString' || key === 'valueOf') {\n if (!schemaHasPath(childSegs)) {\n return key === 'toString' ? containerToString : containerValueOf\n }\n // Schema has it — fall through to descent.\n }\n return descendOrTerminate(childSegs)\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n // Conservatively true — the proxy navigates any path; whether\n // the path resolves to a schema-defined slot is the consumer's\n // concern (read returns the deep proxy or terminal as usual).\n return true\n },\n // Containers are descend-only — `JSON.stringify(form.fields.address)`\n // returns `{}` (no leaf keys to enumerate). Consumers who want\n // structural data use `form.values.<container>` instead.\n ownKeys: () => [],\n getOwnPropertyDescriptor: () => undefined,\n // Block writes at the proxy boundary. Mutations go through\n // `setValue`, the directive, or the field-array helpers.\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n containerCache.set(cacheKey, proxy)\n return proxy\n }\n\n function leafViewProxyAt(segments: readonly Segment[]): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = leafViewCache.get(cacheKey)\n if (existing !== undefined) return existing\n\n const leafKeys = opts.leafKeys\n const readLeafKey = opts.readLeafKey\n if (leafKeys === undefined || readLeafKey === undefined) {\n // Defensive: leaf-VIEW proxy is only constructed via the `get`\n // trap's `descendOrTerminate` branch in `containerProxyAt`,\n // which guards on `opts.leafKeys`. Throw rather than silently\n // misroute if a future caller skips the guard.\n throw new Error('leafViewProxyAt called without leafKeys/readLeafKey configured')\n }\n\n // Snapshot builder shared by `toJSON` and the primitive-coercion\n // handlers. Reads through `resolveLeaf` and `readLeafKey` happen at\n // call time inside the consumer's active effect, so Vue's dependency\n // tracking captures the leaf's reactive deps (the\n // `ComputedRef<FieldState>` for fields).\n const snapshotLeaf = (): Record<string, unknown> => {\n const leaf = opts.resolveLeaf(segments)\n const snapshot: Record<string, unknown> = {}\n for (const leafKey of leafKeys) {\n snapshot[leafKey] = readLeafKey(leaf, leafKey)\n }\n return snapshot\n }\n const leafToString = (): string => JSON.stringify(snapshotLeaf())\n function leafValueOf(this: unknown): unknown {\n return this\n }\n const leafToPrimitive = (hint: string): string | number =>\n hint === 'number' ? NaN : leafToString()\n\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n // Same call-target dispatch as `containerProxyAt` so\n // `form.fields.email(somePath)` reads identically to\n // `form.fields(somePath)` — the call-form always lands on\n // the FieldState terminal.\n const arg = args[0] as string | Path | undefined\n if (arg === undefined) return opts.resolveCallTarget(segments as Path)\n const { segments: argSegs } = canonicalizePath(arg)\n return opts.resolveCallTarget(argSegs)\n },\n get(_, key: string | symbol): unknown {\n if (typeof key === 'symbol') {\n // See containerProxyAt for the rationale. Leaf-views return\n // the JSON-stringified snapshot so primitive coercion produces\n // a useful display (e.g. `String(form.fields.email)` shows the\n // FieldState shape rather than throwing).\n if (key === Symbol.toPrimitive) return leafToPrimitive\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n // Direct method-call path for primitive coercion. `toString`\n // returns the same JSON snapshot as `Symbol.toPrimitive`;\n // `valueOf` returns the receiver (non-primitive) so\n // OrdinaryToPrimitive's `valueOf` → `toString` walk falls through\n // for any code path that bypasses `Symbol.toPrimitive`. No schema\n // collision is possible at this depth: leaves are primitives, so\n // they have no schema children. Collisions at higher container\n // depths (a schema field literally named `toString`) are\n // resolved by `containerProxyAt`'s schema-authority check.\n if (key === 'toString') return leafToString\n if (key === 'valueOf') return leafValueOf\n // `toJSON`: leaf-views serialise to a snapshot object containing\n // every leaf-key value at the moment of the call. Lets SSR\n // templates stringify `form.fields.<leaf>` straight into the\n // hydration payload.\n if (key === 'toJSON') return snapshotLeaf\n // Reads inside the trap stay inside the consumer's active effect —\n // `resolveLeaf` returns a `ComputedRef` (for fields) and `.value`\n // is read inside `readLeafKey`, so Vue's dep tracking captures\n // the dependency at access time.\n if (leafKeys.has(key)) {\n const leaf = opts.resolveLeaf(segments)\n return readLeafKey(leaf, key)\n }\n // Schema field at a leaf-prop name: descend further. The leaf-prop\n // and the schema field name occupy DIFFERENT proxy depths because\n // the schema's leaf-aware structure puts them on different paths.\n // Example: schema `{ address: { valid: boolean } }`:\n // form.fields.address → container proxy\n // form.fields.address.valid → leaf-view (here)\n // form.fields.address.valid.valid → THIS read; 'valid'\n // IS in leafKeys → returns\n // the FieldState's\n // valid prop.\n // For non-leafKeys reads, descend by appending the key to segments\n // and re-checking leaf-ness. This handles container-shaped\n // schema fields hanging off a leaf-named ancestor (rare but\n // possible).\n return descendOrTerminate([...segments, keyToSegment(key)])\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n if (typeof key === 'string' && leafKeys.has(key)) return true\n return true\n },\n // Iteration: leaf-views expose the leaf-key set so\n // `JSON.stringify(form.fields.email)` produces a FieldState\n // snapshot rather than the function-target placeholder.\n ownKeys: () => Array.from(leafKeys),\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n if (typeof key !== 'string') return undefined\n if (!leafKeys.has(key)) return undefined\n const leaf = opts.resolveLeaf(segments)\n return {\n configurable: true,\n enumerable: true,\n value: readLeafKey(leaf, key),\n writable: false,\n }\n },\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n leafViewCache.set(cacheKey, proxy)\n return proxy\n }\n\n // Root proxy. Constructed via `containerProxyAt([])` — root is always\n // a container (every form has at least one field). The cache holds\n // a stable reference; `proxy()` returns the root for the no-arg case.\n const rootProxy = containerProxyAt([])\n return rootProxy\n}\n","import type { ValidationError } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { aggregateErrorsAt } from './field-state-api'\nimport { getAtPath, hasAtPath } from './path-walker'\nimport {\n canonicalizePath,\n segmentsForPathKey,\n type PathKey,\n type Path,\n type Segment,\n} from './paths'\nimport { buildSurfaceProxy, type SurfaceProxy } from './surface-proxy'\n\n/**\n * Build the leaf-aware `form.errors` callable Proxy. Drill via dot /\n * bracket OR call dynamically:\n *\n * form.errors.email // ValidationError[] | undefined (leaf)\n * form.errors.address.city // ValidationError[] | undefined (leaf)\n * form.errors.address // proxy for descent only (container)\n * form.errors('address.city') // function-call (dynamic / programmatic)\n * form.errors(['address', 'city']) // path-array form\n * form.errors() // root proxy\n *\n * Specialises `buildSurfaceProxy` (see surface-proxy.ts) with:\n * - `resolveLeaf`: merges schemaErrors + derivedBlankErrors + userErrors\n * at the canonical PathKey, FILTERED by `hasAtPath` (the active-path\n * filter from commit 1fbb8bb stays). Returns `undefined` when no\n * errors at the path OR the path isn't reachable through the live\n * form value (e.g. inactive variant of a discriminated union after\n * a switch). The store-side entries STAY — `form.meta.errors`\n * exposes the unfiltered aggregate.\n * - `leafKeys`: undefined. The leaf IS the terminal — an array or\n * undefined. No further proxy wrap.\n *\n * Path / value contract preserved: errors at unknown paths return a\n * sub-proxy (descend permissively). `form.errors.bogus` is a proxy,\n * not undefined — readers who want existence checks should use the\n * leaf form (`form.errors.bogus.somePath`) which terminates only at\n * schema-leaves.\n */\nexport function buildErrorsProxy<F extends GenericForm>(state: FormStore<F>): SurfaceProxy {\n return buildSurfaceProxy<ValidationError[] | undefined>({\n schema: state.schema as unknown as Parameters<typeof buildSurfaceProxy>[0]['schema'],\n resolveLeaf: (path) => {\n // Active-path filter: paths whose value is no longer reachable\n // through the live form value (inactive variant after a DU\n // switch) are hidden from `form.errors`. Per-field read APIs\n // (`form.fields.<path>.errors`, `state.getErrorsForPath`) and\n // the `form.meta.errors` aggregate still expose them.\n if (!hasAtPath(state.form.value, path as ReadonlyArray<Segment>)) return undefined\n const { key } = canonicalizePath(path as Path)\n const schemaForKey = state.schemaErrors.get(key)\n const blankForKey = state.derivedBlankErrors.value.get(key)\n const userForKey = state.userErrors.get(key)\n const merged: ValidationError[] = []\n if (schemaForKey !== undefined) merged.push(...schemaForKey)\n if (blankForKey !== undefined) merged.push(...blankForKey)\n if (userForKey !== undefined) merged.push(...userForKey)\n return merged.length === 0 ? undefined : merged\n },\n // No leafKeys — at a leaf, the resolved value (the merged array or\n // undefined) IS the terminal.\n materializeContainer: (segments) => materializeErrors(state, segments),\n // Call-form aggregates: `form.errors(path)` returns a single\n // `ValidationError[]` for any depth (leaf or container) — same\n // shared `aggregateErrorsAt` helper that `form.meta.errors` and\n // `form.fields(path).errors` use, so the three surfaces never\n // drift. Empty results return `undefined`, matching the leaf\n // proxy's pre-existing semantic (`form.errors.email === undefined`\n // when valid) so consumer code that branches on truthiness keeps\n // working — the call-form just extends that semantic to\n // containers and dynamic paths.\n resolveCallTarget: (path) => {\n const errs = aggregateErrorsAt(state, path)\n return errs.length === 0 ? undefined : errs\n },\n })\n}\n\n/**\n * Build a sparse, nested error tree under `containerSegments` for\n * `JSON.stringify(form.errors.<container>)`. Includes every leaf-keyed\n * descendant whose path is reachable in the live form value (the same\n * active-path filter `resolveLeaf` applies), excludes paths that\n * resolve to the container itself (cross-field refines and form-level\n * errors live in `form.meta.errors`, which is the unfiltered flat\n * aggregate). Sparse: containers with no error-bearing descendants\n * don't appear in the tree.\n *\n * Reactivity contract: every read in this function (the three error\n * stores, the form Ref) happens at call time. JSON.stringify invokes\n * `toJSON` once per stringify call inside the consumer's active\n * effect, so dependency tracking captures every store on every render\n * and re-runs on mutation. The per-path proxy memoisation in\n * `surface-proxy.ts` caches the proxy itself, NOT the materialised\n * object — there is no staleness.\n */\nfunction materializeErrors<F extends GenericForm>(\n state: FormStore<F>,\n containerSegments: readonly Segment[]\n): Record<string, unknown> | unknown[] {\n // Mirror the live-data shape at the container: array container →\n // array root (array indices place into integer slots, holes\n // serialise as `null`); object container → object root. Without\n // this the placement code would route numeric segments through a\n // string-keyed object, producing `{ \"0\": {…} }` for an array path\n // and breaking shape parity with `form.values`.\n const liveContainer = getAtPath(state.form.value, containerSegments)\n const tree: Record<string, unknown> | unknown[] = Array.isArray(liveContainer) ? [] : {}\n\n const collect = (store: ReadonlyMap<PathKey, ValidationError[]>): void => {\n entries: for (const [pathKey, errors] of store) {\n if (errors.length === 0) continue\n // Cache hit on every keystroke — the store's PathKeys are\n // produced through `canonicalizePath`, which warms the inverse\n // cache. Cold path (corrupt key) returns null and we skip.\n const fullPath = segmentsForPathKey(pathKey)\n if (fullPath === null) continue\n // Skip paths that aren't strict descendants of the container —\n // a path equal to or shorter than the container has no leaf-keyed\n // contribution at this view (errors at the exact container path\n // are surfaced via `form.meta.errors`).\n if (fullPath.length <= containerSegments.length) continue\n for (let i = 0; i < containerSegments.length; i++) {\n if (fullPath[i] !== containerSegments[i]) continue entries\n }\n // Active-path filter: skip paths that aren't reachable through\n // the live form value. Matches `resolveLeaf` semantics so a leaf\n // read and a container materialisation never disagree.\n if (!hasAtPath(state.form.value, fullPath)) continue\n placeAt(tree, fullPath.slice(containerSegments.length), errors)\n }\n }\n\n collect(state.schemaErrors)\n collect(state.derivedBlankErrors.value)\n collect(state.userErrors)\n return tree\n}\n\n/**\n * Place `errors` at the relative `path` inside `tree`, allocating\n * intermediate object/array containers as needed (numeric segments\n * produce arrays). When `tree` already has an array at `path`,\n * concatenate so multiple stores' contributions to the same path\n * merge into one array — matches `resolveLeaf`'s\n * `[...schemaErrors, ...blankErrors, ...userErrors]` ordering.\n */\nfunction placeAt(\n tree: Record<string, unknown> | unknown[],\n path: readonly Segment[],\n errors: ValidationError[]\n): void {\n if (path.length === 0) return\n let cursor: Record<string, unknown> | unknown[] = tree\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i] as Segment\n const nextSeg = path[i + 1] as Segment\n const key = typeof seg === 'number' ? String(seg) : seg\n const cursorRecord = cursor as Record<string, unknown>\n let child = cursorRecord[key]\n if (child === null || child === undefined || typeof child !== 'object') {\n child = typeof nextSeg === 'number' ? [] : {}\n cursorRecord[key] = child\n }\n cursor = child as Record<string, unknown> | unknown[]\n }\n const lastSeg = path[path.length - 1] as Segment\n const lastKey = typeof lastSeg === 'number' ? String(lastSeg) : lastSeg\n const cursorRecord = cursor as Record<string, unknown>\n const existing = cursorRecord[lastKey]\n cursorRecord[lastKey] = Array.isArray(existing) ? [...existing, ...errors] : errors\n}\n","import type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { canonicalizePath } from './paths'\n\n/**\n * Typed array helpers on top of FormStore. Each helper reads the current\n * array at the given path, produces a new copy (immutable, so that the\n * `form` ref's reactive notification goes out), and writes it back via\n * `setValueAtPath`. All downstream bookkeeping — diffAndApply patches,\n * field-record `updatedAt` stamps, error-store preservation — comes for\n * free through the normal setValueAtPath pipeline.\n *\n * Out-of-range index semantics:\n * - `remove` / `swap` / `replace`: no-op on invalid indices. Never grow\n * the array. Matches react-hook-form / VeeValidate precedent.\n * - `insert`: the target index is clamped via `Array.prototype.splice`\n * (values past `length` are treated as `length`).\n * - `move`: invalid `from` is a no-op; `to` is clamped to `[0, length]`.\n *\n * None of the helpers mutate the existing array — every write is a fresh\n * array literal, so Vue's identity-based change detection fires. Callers\n * that need to compose mutations should batch them at the schema level\n * (build the replacement shape, call `setValue(path, shape)` once).\n */\n\nexport type FieldArrayApi = {\n append(path: string, value: unknown): boolean\n prepend(path: string, value: unknown): boolean\n insert(path: string, index: number, value: unknown): boolean\n remove(path: string, index: number): boolean\n swap(path: string, a: number, b: number): boolean\n move(path: string, from: number, to: number): boolean\n replace(path: string, index: number, value: unknown): boolean\n}\n\nexport function buildFieldArrayApi<F extends GenericForm>(state: FormStore<F>): FieldArrayApi {\n function readArray(path: string): unknown[] {\n const segments = canonicalizePath(path).segments\n const current = state.getValueAtPath(segments)\n // If the path is missing or points at a non-array (e.g. the schema\n // default was undefined), treat as an empty array. This lets\n // `append` work for arrays that haven't been initialised by the\n // schema; the alternative of throwing surfaces programmer errors\n // earlier but blocks a common consumer pattern.\n return Array.isArray(current) ? current.slice() : []\n }\n\n function writeArray(path: string, next: unknown[]): boolean {\n const { segments, key } = canonicalizePath(path)\n // Persist iff some element has opted into this exact array path. If\n // the consumer opted into specific leaves (e.g. 'contacts.0.name')\n // an `append('contacts', row)` falls through — the array root has\n // no opt-in, so it doesn't persist. Coherent: \"you opted to persist\n // a leaf, not the array structure.\"\n return state.setValueAtPath(segments, next, {\n persist: state.persistOptIns.hasAnyOptInForPath(key),\n })\n }\n\n return {\n append(path, value) {\n const next = readArray(path)\n next.push(value)\n return writeArray(path, next)\n },\n prepend(path, value) {\n const next = readArray(path)\n next.unshift(value)\n return writeArray(path, next)\n },\n insert(path, index, value) {\n const next = readArray(path)\n // splice clamps `index` to `[0, length]`; negative values count from\n // the end. We pass through untouched — Array semantics are the\n // consumer's expected behaviour here.\n next.splice(index, 0, value)\n return writeArray(path, next)\n },\n remove(path, index) {\n const next = readArray(path)\n if (index < 0 || index >= next.length) return false\n next.splice(index, 1)\n return writeArray(path, next)\n },\n swap(path, a, b) {\n const next = readArray(path)\n if (a < 0 || a >= next.length) return false\n if (b < 0 || b >= next.length) return false\n if (a === b) return false\n const tmp = next[a]\n next[a] = next[b]\n next[b] = tmp\n return writeArray(path, next)\n },\n move(path, from, to) {\n const next = readArray(path)\n if (from < 0 || from >= next.length) return false\n const [item] = next.splice(from, 1)\n const clampedTo = Math.max(0, Math.min(to, next.length))\n next.splice(clampedTo, 0, item)\n return writeArray(path, next)\n },\n replace(path, index, value) {\n const next = readArray(path)\n if (index < 0 || index >= next.length) return false\n next[index] = value\n return writeArray(path, next)\n },\n }\n}\n","import type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { buildFieldStateAccessor, type FieldState } from './field-state-api'\nimport { getAtPath } from './path-walker'\nimport type { Path, Segment } from './paths'\nimport { buildSurfaceProxy, type SurfaceProxy } from './surface-proxy'\n\n/**\n * The leaf-prop set of a `FieldState`. At a leaf path, reads of\n * any of these keys terminate against the FieldState's reactive\n * prop. Reads of OTHER keys descend (e.g. a schema field literally\n * named `dirty` AT the leaf — which can happen when the shape is\n * `{ outer: { dirty: boolean } }`, making `outer.dirty` a leaf in\n * its own right; that case resolves via the leaf-aware proxy in\n * surface-proxy.ts where `outer.dirty` becomes a leaf-VIEW proxy and\n * `.dirty` on it reads the FieldState's `dirty` boolean).\n *\n * Container paths do NOT inject these keys via dot-access —\n * `form.fields.address.dirty` (where `address` is a container with\n * no `dirty` field) descends to a sub-proxy at `address.dirty` so\n * schema fields literally named `dirty` at depth 2+ stay\n * reachable. The container aggregation is reached via call-form:\n * `form.fields('address').dirty` returns the disjunction over\n * descendants.\n */\nconst FIELD_STATE_KEYS: ReadonlySet<string> = new Set<keyof FieldState<unknown>>([\n 'value',\n 'original',\n 'pristine',\n 'dirty',\n 'focused',\n 'blurred',\n 'touched',\n 'connected',\n 'element',\n 'elements',\n 'updatedAt',\n 'errors',\n 'validating',\n 'valid',\n 'path',\n 'blank',\n 'label',\n 'description',\n 'placeholder',\n 'meta',\n])\n\n/**\n * Build the leaf-aware `form.fields` callable Proxy. Drill via dot /\n * bracket access OR call dynamically:\n *\n * form.fields.email.errors // dot/bracket descent\n * form.fields('email').errors // function-call (dynamic / programmatic)\n * form.fields(['users', 0, 'name']) // path-array form\n * form.fields() // root proxy\n *\n * Specialises `buildSurfaceProxy` (see surface-proxy.ts) with:\n * - `resolveLeaf`: returns the per-path `ComputedRef<FieldState>`\n * produced by `buildFieldStateAccessor`. The accessor allocates one\n * computed per path; the per-path memoisation in `buildSurfaceProxy`\n * ensures repeated reads of the same path return the same proxy.\n * - `leafKeys`: `FIELD_STATE_KEYS`. At a leaf path, reads off these\n * keys return the FieldState's reactive prop. Reads inside the\n * trap stay inside the consumer's active effect, so Vue's dep\n * tracking captures the dependency at access time.\n * - `readLeafKey`: extracts `view.value[key]` — the `view.value` access\n * triggers the computed's evaluation; the bracket lookup is a plain\n * object read against the resulting `FieldState`.\n */\nexport function buildFieldStateProxy<F extends GenericForm>(state: FormStore<F>): SurfaceProxy {\n const getFieldStateAt = buildFieldStateAccessor(state)\n const snapshotFieldStateAt = (path: Path): Record<string, unknown> => {\n const view = getFieldStateAt(path as Parameters<typeof getFieldStateAt>[0]).value\n const snapshot: Record<string, unknown> = {}\n for (const k of FIELD_STATE_KEYS) snapshot[k] = (view as Record<string, unknown>)[k]\n return snapshot\n }\n // Per-path cache for the FieldState terminal proxy — stable\n // referential identity across repeated `form.fields(p)` reads with\n // the same canonical key.\n const terminalCache = new Map<string, SurfaceProxy>()\n /**\n * Build the third proxy shape (distinct from `containerProxyAt` and\n * `leafViewProxyAt` in surface-proxy.ts). Returned by `apply`-trap\n * call-form at any depth — leaf or container — so\n * `form.fields(path)` always lands on a `FieldState` surface.\n *\n * - `get`: `FIELD_STATE_KEYS` reads return the resolved leaf\n * prop (delegates to the per-path computed); other keys return\n * `undefined`. No descent.\n * - No `apply`. No further callable behavior.\n */\n function fieldStateTerminalAt(segments: Path): SurfaceProxy {\n const cacheKey = JSON.stringify(segments)\n const existing = terminalCache.get(cacheKey)\n if (existing !== undefined) return existing\n const target = (() => {}) as unknown as SurfaceProxy\n const proxy = new Proxy(target, {\n get(_, key: string | symbol): unknown {\n if (typeof key === 'symbol') {\n if (key === Symbol.toPrimitive) {\n return (hint: string): string | number =>\n hint === 'number' ? NaN : JSON.stringify(snapshotFieldStateAt(segments))\n }\n return Reflect.get(target, key)\n }\n if (typeof key !== 'string') return undefined\n if (key === 'toJSON') return () => snapshotFieldStateAt(segments)\n if (key === 'toString') return () => JSON.stringify(snapshotFieldStateAt(segments))\n if (key === 'valueOf')\n return function (this: unknown): unknown {\n return this\n }\n if (FIELD_STATE_KEYS.has(key)) {\n const computed = getFieldStateAt(segments as Parameters<typeof getFieldStateAt>[0])\n return (computed.value as Record<string, unknown>)[key]\n }\n return undefined\n },\n has: (_, key: string | symbol): boolean =>\n typeof key === 'string' && FIELD_STATE_KEYS.has(key),\n ownKeys: () => Array.from(FIELD_STATE_KEYS),\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n if (typeof key !== 'string') return undefined\n if (!FIELD_STATE_KEYS.has(key)) return undefined\n const computed = getFieldStateAt(segments as Parameters<typeof getFieldStateAt>[0])\n return {\n configurable: true,\n enumerable: true,\n value: (computed.value as Record<string, unknown>)[key],\n writable: false,\n }\n },\n set: () => false,\n deleteProperty: () => false,\n defineProperty: () => false,\n })\n terminalCache.set(cacheKey, proxy)\n return proxy\n }\n return buildSurfaceProxy<ReturnType<typeof getFieldStateAt>>({\n schema: state.schema as unknown as Parameters<typeof buildSurfaceProxy>[0]['schema'],\n resolveLeaf: (path) => getFieldStateAt(path as Parameters<typeof getFieldStateAt>[0]),\n leafKeys: FIELD_STATE_KEYS,\n readLeafKey: (computed, key) => (computed.value as Record<string, unknown>)[key],\n materializeContainer: (segments) => materializeFields(state, segments, snapshotFieldStateAt),\n resolveCallTarget: (path) => fieldStateTerminalAt(path),\n })\n}\n\n/**\n * Build a dense, nested `FieldState`-snapshot tree at\n * `containerSegments` for `JSON.stringify(form.fields.<container>)`.\n * Walks the live form value at the container path and snapshots the\n * `FieldState` for every schema-leaf descendant. Containers\n * recurse; leaves terminate with the snapshot. Arrays produce arrays;\n * records / objects produce objects whose key set matches the live\n * data (so a discriminated union exposes only the active variant's\n * keys, and a record exposes the keys actually present).\n *\n * Reactivity contract identical to `materializeErrors`: every read in\n * this function happens at call time inside the consumer's active\n * effect, so dependency tracking captures `state.form.value` and the\n * field-state computeds — `JSON.stringify(form.fields)` re-runs\n * whenever the form data or any per-leaf field state changes.\n */\nfunction materializeFields<F extends GenericForm>(\n state: FormStore<F>,\n containerSegments: readonly Segment[],\n snapshotFieldStateAt: (path: Path) => Record<string, unknown>\n): unknown {\n const liveValue = getAtPath(state.form.value, containerSegments)\n return walk(liveValue, containerSegments, state.schema, snapshotFieldStateAt)\n}\n\nfunction walk(\n value: unknown,\n basePath: readonly Segment[],\n schema: { isLeafAtPath(path: Path): boolean },\n snapshotFieldStateAt: (path: Path) => Record<string, unknown>\n): unknown {\n // Schema-leaf takes precedence over data shape: a leaf path with\n // `null` or a primitive in storage still surfaces the FieldState\n // (which is the field-state authority — `value` lives inside the view).\n if (schema.isLeafAtPath(basePath)) return snapshotFieldStateAt(basePath)\n // Container with no live value (e.g. an absent record key, or a\n // missing optional object): expose null so consumers can distinguish\n // \"schema container that hasn't been populated\" from \"container with\n // empty state\" (`{}` / `[]`).\n if (value === null || value === undefined) return value\n if (typeof value !== 'object') {\n // Defensive: schema reports container but data is a primitive. Surface\n // the primitive so the JSON shape reflects reality without throwing.\n return value\n }\n if (Array.isArray(value)) {\n return value.map((_, i) => walk(value[i], [...basePath, i], schema, snapshotFieldStateAt))\n }\n const result: Record<string, unknown> = {}\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = walk(\n (value as Record<string, unknown>)[key],\n [...basePath, key],\n schema,\n snapshotFieldStateAt\n )\n }\n return result\n}\n","/**\n * Library-level default constants. All consumer-facing fallbacks for\n * the bundled options (`debounceMs`, `persist.debounceMs`,\n * `history.max`, etc.) resolve to one of these — extracting them here\n * keeps the JSDoc on the public option type and the runtime fallback\n * in lockstep, and gives reviewers a single file to scan when tuning\n * timing/policy defaults.\n *\n * Per-form `useForm({ ... })` options always win over these. App-level\n * `createAttaform({ defaults: ... })` options sit between the\n * two: per-form > app-level > library default.\n */\n\n/**\n * Validation debounce (`useForm({ debounceMs })`) — ms to wait after\n * the LAST input event before running validation. Default `0`\n * (debounce disabled): every committed write fires a validation pass\n * synchronously, no `setTimeout`. Matches the obvious mental model\n * and avoids the \"why is my error 125 ms behind my keystroke?\"\n * footgun for new consumers.\n *\n * NOTE: this is purely the VALIDATION debounce. Form storage\n * (`form.values`) commits on every write the directive forwards;\n * `setValueWithInternalPath` writes immediately and triggers a\n * validation schedule. WHEN the directive actually forwards a write\n * is a separate concern controlled by input modifiers — `<input\n * v-register>` commits on every keystroke (`input` event), but\n * `<input v-register.lazy>` defers to the `change` event so storage\n * only commits on blur. The validation debounce is independent of\n * either path: it always counts ms since the last committed write.\n *\n * Devs who need validation coalescing — slow async adapters,\n * validation that runs heavy work — opt in with `debounceMs: 200`\n * (or any positive number). The off-by-default posture trades CPU\n * cycles for UX latency wins, and the cycles only matter for\n * adapters that are actually expensive.\n */\nexport const DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS = 0\n\n/**\n * Persistence write debounce (`persist.debounceMs`). 300 ms is\n * generous on purpose — the goal is \"draft survives accidental\n * navigation,\" not \"every keystroke hits storage.\" Lower if your\n * storage adapter is in-memory; raise for slow IndexedDB or remote\n * adapters.\n */\nexport const DEFAULT_PERSISTENCE_DEBOUNCE_MS = 300\n\n/**\n * Undo/redo stack ceiling (`history.max`). 50 covers a generous\n * editing session without unbounded memory growth from long-lived\n * forms. Snapshots are shallow, so the per-snapshot cost is small;\n * the cap exists more for predictability than memory pressure.\n */\nexport const DEFAULT_HISTORY_MAX_SNAPSHOTS = 50\n\n/**\n * Storage-key namespace for persistence. Resolved once at\n * `resolveStorageKey` to `${PERSISTENCE_KEY_PREFIX}${formKey}` unless\n * the consumer passes an explicit `persist.key`. Kept as a separate\n * constant so multi-tenant deployments can audit or reserve their\n * own prefix without grepping for the literal.\n */\nexport const PERSISTENCE_KEY_PREFIX = 'attaform:'\n\n/**\n * Reserved namespace for the library's internal synthetic keys\n * (anonymous forms today, plus any future internal-key uses).\n * `useAbstractForm` rejects any consumer-supplied key starting with\n * this prefix at construction time, throwing `ReservedFormKeyError` —\n * so collisions with the synthetic-key namespace are impossible by\n * construction. The double-underscore convention reads as \"internal\"\n * universally, lowering the chance a consumer would naturally pick\n * a key from this space anyway.\n */\nexport const RESERVED_KEY_PREFIX = '__atta:'\n\n/**\n * Synthetic-key prefix for `useForm()` calls without an explicit\n * `key`. Lives inside the reserved `__atta:` namespace so the entry-\n * level reject in `resolveFormKey` covers it automatically — see\n * `RESERVED_KEY_PREFIX` for the enforcement story.\n */\nexport const ANONYMOUS_FORM_KEY_PREFIX = `${RESERVED_KEY_PREFIX}anon:`\n","import type {\n AbstractSchema,\n FormStorage,\n FormStorageKind,\n PersistConfig,\n PersistConfigOptions,\n ValidationError,\n} from '../../types/types-api'\nimport { PERSISTENCE_KEY_PREFIX } from '../defaults'\nimport { __DEV__ } from '../dev'\nimport { isPlainRecord, setAtPath, getAtPath } from '../path-walker'\nimport { segmentsForPathKey, type Path, type PathKey, type Segment } from '../paths'\n\n/**\n * Public-ish handle returned by `wirePersistence`. Lives on\n * `state.modules.get('persistence')` so `buildFormApi` can plug\n * `form.persist(path)` and `form.clearPersistedDraft(path?)` into\n * the consumer-facing API. Internal — consumers go through the API.\n */\nexport type PersistenceModule = {\n /**\n * Read-merge-write a single path's current value. Flushes any pending\n * debounced write first so the imperative checkpoint can't be\n * overwritten by a stale-data write that fires immediately after.\n * No-op if the FormStore is disposed.\n */\n writePathImmediately(path: Path): Promise<void>\n /**\n * Wipe the persisted entry. With `path` provided, removes that\n * subpath only (and any matching error entries) and writes back; the\n * entry is removed entirely if the resulting form value is empty.\n * Without `path`, calls the adapter's `removeItem` directly.\n */\n clearPersistedDraft(path?: Path): Promise<void>\n /**\n * Drains any pending debounced or in-flight write. Resolves once\n * storage has the latest opted-in form value. Called by the registry\n * before evicting a FormStore so the last keystroke isn't lost when\n * a component unmounts mid-debounce.\n *\n * Safe to call after `dispose()` — resolves immediately as a no-op.\n */\n awaitPendingWrites(): Promise<void>\n /** Disposer — called from FormStore.dispose. */\n dispose(): void\n}\n\n/**\n * Cache key for `state.modules.get(...)`. Only the persistence layer\n * itself + buildFormApi read this — exporting keeps the literal in one\n * place rather than scattering 'persistence' across files.\n */\nexport const PERSISTENCE_MODULE_KEY = 'persistence'\n\n/**\n * Resolve a `FormStorage` adapter for the given storage kind. Built-in\n * kinds are dynamically imported so a consumer who picks `'local'`\n * never pulls the IndexedDB adapter code. Rollup's\n * side-effect-free graph tree-shakes the unused adapters cleanly.\n *\n * Passing a custom `FormStorage` object bypasses the dispatch and is\n * returned as-is — no dynamic import happens. This is the escape hatch\n * for encrypted stores, cookie-backed stores, native-mobile bridges.\n */\nexport async function getStorageAdapter(\n storage: FormStorageKind | FormStorage\n): Promise<FormStorage> {\n if (typeof storage === 'object') return storage\n switch (storage) {\n case 'local': {\n const { createLocalStorageAdapter } = await import('./local-storage')\n return createLocalStorageAdapter()\n }\n case 'session': {\n const { createSessionStorageAdapter } = await import('./session-storage')\n return createSessionStorageAdapter()\n }\n case 'indexeddb': {\n const { createIndexedDbAdapter } = await import('./indexeddb')\n return createIndexedDbAdapter()\n }\n }\n}\n\n/**\n * Persisted payload envelope.\n *\n * `v` is a attaform-INTERNAL storage-format version — bumped only when the\n * library's persisted payload schema itself changes (e.g. adding a new\n * field, restructuring `data`). It is NOT consumer-controlled.\n * Schema-driven invalidation uses the storage key's `:${fingerprint}`\n * suffix instead, so consumers don't need to manage versioning at all.\n *\n * `data` mirrors the SSR `SerializedFormData` shape so one deserialiser\n * handles both.\n *\n * Errors are stored source-segregated (matching FormStore's split):\n * - `schemaErrors` is validation-owned; cleared by reset / submit-success.\n * - `userErrors` is consumer-owned (written via setFieldErrors* APIs);\n * persists across schema revalidation and successful submits.\n */\nexport type PersistedPayload<Form> = {\n readonly v: number\n readonly data: {\n readonly form: Form\n readonly schemaErrors?: ReadonlyArray<readonly [string, ValidationError[]]>\n readonly userErrors?: ReadonlyArray<readonly [string, ValidationError[]]>\n /**\n * Path keys that were in the form's `blankPaths` set at\n * serialisation time. Optional — older v=2 envelopes don't carry it,\n * and forms with no blank paths skip the field too.\n * Replayed into the reactive Set on the next mount so an accidental\n * refresh preserves the user's \"displayed empty\" state across\n * sessions. Introduced in envelope v=3.\n */\n readonly blankPaths?: ReadonlyArray<string>\n }\n}\n\n/**\n * Current attaform-internal envelope version. Bumped only when the library\n * changes the persisted payload's structural shape — readers reject\n * envelopes with a different `v`. Schema-content invalidation is\n * handled at the storage key level (the `:${fingerprint}` suffix), so\n * consumers shouldn't see this number.\n *\n * v=3: adds `data.blankPaths` for round-tripping the\n * blank UI state across persistence + SSR. v=2 envelopes\n * are dropped with a one-time dev-warn (commit 6 of the unset feature).\n *\n * v=4: `ValidationError` gained a required `code` field. Persisted\n * `schemaErrors` / `userErrors` now include `code`; v=3 payloads are\n * dropped with a one-time dev-warn.\n */\nexport const PERSISTED_ENVELOPE_VERSION = 4\n\n/**\n * `value` is expected to be a raw `PersistedPayload` (parsed JSON or\n * structured-cloned object). Returns `null` if the shape doesn't match\n * — the caller falls back to schema defaults.\n *\n * The attaform-internal envelope `v` must match `PERSISTED_ENVELOPE_VERSION`;\n * mismatches (older library versions' payloads) are dropped. Schema\n * change detection lives at the storage-key level via the fingerprint\n * suffix.\n */\nexport function readPersistedPayload<Form>(value: unknown): PersistedPayload<Form> | null {\n if (value === null || value === undefined || typeof value !== 'object') return null\n const envelope = value as Partial<PersistedPayload<Form>>\n if (typeof envelope.v !== 'number') return null\n if (envelope.v !== PERSISTED_ENVELOPE_VERSION) {\n warnVersionMismatch(envelope.v)\n return null\n }\n if (envelope.data === undefined || typeof envelope.data !== 'object') return null\n return envelope as PersistedPayload<Form>\n}\n\n/**\n * Tracks envelope versions we've already warned about during this\n * session. The reader hits this for every form mount that finds\n * stale persisted state, so a page with N saved drafts at an old\n * version would otherwise produce N warnings of the same content.\n * Module-scoped Set survives the test-suite hot-reload cycle but\n * resets on each fresh page load — exactly the dedup window we want.\n *\n * `null` in production so the Set allocation tree-shakes out.\n */\nconst warnedVersions: Set<number> | null = __DEV__ ? new Set<number>() : null\n\nfunction warnVersionMismatch(observedVersion: number): void {\n if (warnedVersions === null) return\n if (warnedVersions.has(observedVersion)) return\n warnedVersions.add(observedVersion)\n console.warn(\n `[attaform] Dropping persisted draft — envelope v=${observedVersion}, ` +\n `but this version of the library expects v=${PERSISTED_ENVELOPE_VERSION}. ` +\n `The persisted shape changed across releases; older drafts can't be restored. ` +\n `New drafts saved this session will use the current envelope.`\n )\n}\n\nexport function buildPersistedPayload<Form>(\n form: Form,\n include: 'form' | 'form+errors',\n schemaErrors: ReadonlyMap<string, ValidationError[]>,\n userErrors: ReadonlyMap<string, ValidationError[]>,\n blankPaths?: ReadonlySet<string>\n): PersistedPayload<Form> {\n // The blank list is part of the form's restorable UI\n // state — its visibility doesn't depend on the `include` mode\n // (which only governs whether errors come along for the ride).\n // Skip the field when the set is empty so v=3 round-trips with\n // unchanged minimal payload size for forms that never go empty.\n const transientList: ReadonlyArray<string> | undefined =\n blankPaths !== undefined && blankPaths.size > 0 ? [...blankPaths] : undefined\n\n if (include === 'form') {\n if (transientList === undefined) return { v: PERSISTED_ENVELOPE_VERSION, data: { form } }\n return {\n v: PERSISTED_ENVELOPE_VERSION,\n data: { form, blankPaths: transientList },\n }\n }\n return {\n v: PERSISTED_ENVELOPE_VERSION,\n data: {\n form,\n schemaErrors: [...schemaErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n userErrors: [...userErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n ...(transientList !== undefined ? { blankPaths: transientList } : {}),\n },\n }\n}\n\n/**\n * Tiny debounce utility. Returns a `{ schedule, flush, cancel }`\n * triple — `schedule` delays a single pending write, `flush` runs it\n * immediately, `cancel` drops it. Unlike a library `debounce`, this\n * one awaits the underlying async write inside `flush` so callers\n * can await full completion on consumer teardown.\n *\n * `debounceMs: 0` is the off switch — `schedule()` fires the write\n * synchronously rather than queueing through `setTimeout(fn, 0)`\n * (which is a macrotask the browser clamps to ~4 ms anyway).\n */\nexport function createDebouncedWriter(\n write: () => Promise<void>,\n debounceMs: number\n): {\n schedule(): void\n flush(): Promise<void>\n cancel(): void\n} {\n let timer: ReturnType<typeof setTimeout> | null = null\n let pending: Promise<void> | null = null\n\n function schedule(): void {\n if (timer !== null) clearTimeout(timer)\n // `debounceMs: 0` is the off switch — fire the write synchronously\n // rather than punting through `setTimeout(fn, 0)` (which queues a\n // macrotask and the browser clamps to ~4 ms anyway).\n if (debounceMs === 0) {\n pending = write().finally(() => {\n pending = null\n })\n return\n }\n timer = setTimeout(() => {\n timer = null\n pending = write().finally(() => {\n pending = null\n })\n }, debounceMs)\n }\n\n async function flush(): Promise<void> {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n pending = write().finally(() => {\n pending = null\n })\n }\n if (pending !== null) await pending\n }\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n return { schedule, flush, cancel }\n}\n\n/**\n * Resolve the per-form storage KEY BASE. Default is\n * `attaform:${formKey}` — consumers who want a different\n * namespace (multi-tenant app, per-user prefix) pass `persist.key`.\n *\n * The full storage key is `${base}:${fingerprint}` (see\n * `resolveStorageKey`). The base is exposed separately so the\n * orphan-cleanup pass can `listKeys(base)` and prune any entry under\n * an old fingerprint.\n */\nexport function resolveStorageKeyBase(config: PersistConfigOptions, formKey: string): string {\n return config.key ?? `${PERSISTENCE_KEY_PREFIX}${formKey}`\n}\n\n/**\n * Resolve the full per-form storage key, composed of the base and the\n * schema's structural fingerprint. The fingerprint suffix gives free\n * automatic invalidation: any structural schema change produces a new\n * fingerprint, so the new mount looks up a fresh key and the old\n * draft becomes an orphan (cleaned up on the same mount via\n * `cleanupOrphanKeys`).\n */\nexport function resolveStorageKey(\n config: PersistConfigOptions,\n formKey: string,\n fingerprint: string\n): string {\n return `${resolveStorageKeyBase(config, formKey)}:${fingerprint}`\n}\n\n/**\n * Delete every attaform-managed key under `base` that's not the current\n * fingerprint key. Sweeps two shapes:\n * - Unfingerprinted keys (no `:` suffix at all) — defensive cover\n * for hand-written or migration-written entries that skipped the\n * fingerprint suffix.\n * - Fingerprint-suffixed keys whose suffix doesn't match the\n * current schema.\n *\n * Exact-or-`:`-prefix match prevents collision with sibling forms\n * whose `config.key` shares a string prefix (e.g. `'my-form'` vs\n * `'my-form-2'`).\n *\n * Fire-and-forget; never throws. SSR-guarded by the caller (cleanup\n * runs inside `wirePersistence`, which is itself client-only).\n */\nexport async function cleanupOrphanKeys(\n adapter: FormStorage,\n base: string,\n currentKey: string\n): Promise<void> {\n let keys: string[]\n try {\n keys = await adapter.listKeys(base)\n } catch {\n return\n }\n for (const key of keys) {\n if (key === currentKey) continue\n // Match either the exact base (unfingerprinted key) or an\n // explicit `:` continuation (stale-fingerprint key).\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n}\n\n/**\n * The canonical list of built-in backends. Used by the cross-store\n * cleanup sweep — any standard backend not matching the configured\n * one gets a `removeItem(key)` at mount.\n */\nexport const STANDARD_STORAGE_KINDS = ['local', 'session', 'indexeddb'] as const\n\n/**\n * Coerce the consumer-facing `PersistConfig` (which accepts shorthand\n * forms — a string backend name, or a custom `FormStorage` adapter) into\n * the resolved options bag the rest of the persistence layer expects.\n *\n * Discrimination rules (in order):\n *\n * 1. `typeof input === 'string'` — `FormStorageKind` shorthand.\n * 2. `'storage' in input` — already the full options bag.\n * 3. otherwise — custom `FormStorage` adapter.\n *\n * Step 3 trusts the caller's type: a `FormStorage` is a duck-typed\n * `{ getItem, setItem, removeItem }` object, and we don't validate\n * the shape — TypeScript already covers that path on the call site.\n *\n * Returning `PersistConfigOptions` (not `PersistConfig`) means the\n * normalized form is referentially distinct from the input — callers\n * can be confident `result.storage` is always present.\n */\nexport function normalizePersistConfig(input: PersistConfig): PersistConfigOptions {\n if (typeof input === 'string') return { storage: input }\n if ('storage' in input) return input\n return { storage: input }\n}\n\n/**\n * Wipe every attaform-managed key under `base` from every standard backend.\n * Fire-and-forget. Used when no `persist:` is configured on the form:\n * a previous deployment may have written entries under this base\n * (any fingerprint), and the dev removing persistence should mean the\n * on-disk artifact is gone too — for every fingerprint that ever ran.\n *\n * Sweeps unfingerprinted keys (no `:` suffix) and fingerprint-\n * suffixed keys equally. Errors per backend are swallowed.\n */\nexport async function sweepAllOrphansAcrossStandardStores(base: string): Promise<void> {\n for (const kind of STANDARD_STORAGE_KINDS) {\n try {\n const adapter = await getStorageAdapter(kind)\n const keys = await adapter.listKeys(base)\n for (const key of keys) {\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n } catch {\n // Backend unavailable (Node, Safari private mode, IDB blocked).\n }\n }\n}\n\n/**\n * Cross-store cleanup. Calls `removeItem(key)` on every standard\n * backend that's NOT the configured one — fire-and-forget. Runs once\n * at form mount.\n *\n * Why this matters: if a form was persisting to `'local'` and the dev\n * later switches to `'session'` (or a custom encrypted adapter), the\n * stale entry in `'local'` would otherwise sit there indefinitely,\n * potentially holding sensitive data the dev thought they had moved\n * to a safer store. The configured `storage` option is the source of\n * truth for \"where the draft lives now\"; everything else is hysteresis\n * from past app states and should be wiped.\n *\n * Implementation note: deletion is inlined per-backend rather than going\n * through `getStorageAdapter`. Inlining avoids dynamic-importing the\n * adapter chunks the consumer specifically chose NOT to use — a form\n * configured for `'local'` shouldn't pull the IndexedDB chunk just to\n * sweep it.\n *\n * If `configured` is a custom `FormStorage` adapter, all three standard\n * backends are swept (we don't know which built-in the dev migrated\n * away from, and we can't reach custom adapters by enumeration).\n *\n * Errors are swallowed — cleanup is best-effort. Backend unavailable\n * (Node, Safari private mode, IDB blocked) is also a silent skip.\n */\n/**\n * Cross-store orphan cleanup: wipe every attaform-managed key under `base`\n * from each standard backend that's NOT the configured one. Symmetric\n * with `cleanupOrphanKeys` on the configured store: ensures stale\n * drafts don't survive in stores the dev migrated AWAY from. Sweeps\n * unfingerprinted and stale-fingerprint keys equally.\n *\n * If `configured` is a custom `FormStorage` adapter, all three\n * standard backends are swept (we don't know which built-in the dev\n * migrated away from, and we can't reach custom adapters by\n * enumeration).\n *\n * Fire-and-forget. Per-backend errors swallowed.\n */\nexport async function sweepNonConfiguredStandardStoresForOrphans(\n configured: FormStorageKind | FormStorage,\n base: string\n): Promise<void> {\n const configuredKind = typeof configured === 'string' ? configured : null\n for (const kind of STANDARD_STORAGE_KINDS) {\n if (kind === configuredKind) continue\n try {\n const adapter = await getStorageAdapter(kind)\n const keys = await adapter.listKeys(base)\n for (const key of keys) {\n if (key === base || key.startsWith(`${base}:`)) {\n void adapter.removeItem(key).catch(() => undefined)\n }\n }\n } catch {\n // Backend unavailable.\n }\n }\n}\n\n/**\n * Build a sparse object containing only the values at `pathKeys` from\n * `form`. Each PathKey is the canonical JSON-array form\n * (`'[\"profile\",\"name\"]'`) emitted by `canonicalizePath`. Paths whose\n * value is `undefined` in the source (e.g. an optional schema field\n * the user never touched) are skipped — the caller's\n * `mergeSparseHydration` re-fills from schema defaults on read.\n *\n * The returned object structurally-shares with the source: a path that\n * names a container (e.g. `'contacts'` resolving to a whole array) is\n * copied by reference into the sparse output. Per-leaf opt-ins\n * (`'contacts.0.name'`) construct intermediate containers via\n * `setAtPath`.\n */\nexport function pluckPaths(form: unknown, pathKeys: Iterable<PathKey>): unknown {\n let sparse: unknown = undefined\n for (const pathKey of pathKeys) {\n // PathKeys arrive from the opt-in registry (canonical) — cache hit\n // every iteration. The null branch covers persistence payloads\n // round-tripped from disk that were corrupted before reaching the\n // restoration code.\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n const value = getAtPath(form, segments)\n if (value === undefined) continue\n sparse = setAtPath(sparse ?? {}, segments, value)\n }\n return sparse ?? {}\n}\n\n/**\n * Restrict a `(PathKey → ValidationError[])` map to entries whose key\n * appears in `pathKeys`. Used by the persistence writer to drop errors\n * on non-opted-in paths from the persisted envelope — a persisted\n * error without a persisted value would dangle on rehydration (the\n * form would resurrect with no value but a complaint about it).\n */\nexport function filterErrorsByPaths(\n errors: ReadonlyMap<string, ValidationError[]>,\n pathKeys: ReadonlySet<PathKey>\n): Map<string, ValidationError[]> {\n const out = new Map<string, ValidationError[]>()\n for (const [key, value] of errors) {\n if (pathKeys.has(key as PathKey)) out.set(key, value)\n }\n return out\n}\n\n/**\n * Merge a sparse persisted form over schema defaults. Returns a new\n * object — neither input is mutated. Used by hydration replay when\n * the persisted payload only contains opted-in paths.\n *\n * Object keys are merged recursively (sparse keys override defaults).\n * Arrays are REPLACED wholesale: if a path resolves to an array in the\n * sparse persisted form, it overrides the schema's array entirely. This\n * is the simpler rule for the common cases (whole-array opt-in via\n * `'contacts'` works; per-leaf opt-in implicitly accepts that schema\n * defaults for sibling leaves at the same array index won't be filled).\n *\n * Primitives in the sparse form override defaults. `null` and explicit\n * primitive values pass through (a persisted `null` is meaningful).\n *\n * **Discriminated unions:** when a path resolves to a DU in the\n * schema AND the sparse value's discriminator differs from the\n * defaults' discriminator (i.e. the persisted draft was written\n * against a different active variant than the schema's first-variant\n * default), the merge REBASES on the matching variant's slim default\n * rather than deep-merging across variants. Without this, deep merge\n * would produce an inconsistent shape carrying BOTH variants' keys\n * (e.g. `{channel: 'sms', number: '...', address: ''}`) — violates\n * the DU's per-variant shape contract and surfaces ghost fields in\n * `form.values`.\n */\nexport function mergeSparseHydration<F>(\n schemaDefaults: F,\n sparse: unknown,\n schema?: AbstractSchema<unknown, unknown>\n): F {\n return mergeDeep(schemaDefaults, sparse, [], schema) as F\n}\n\nfunction mergeDeep(\n target: unknown,\n source: unknown,\n path: readonly Segment[],\n schema: AbstractSchema<unknown, unknown> | undefined\n): unknown {\n if (source === undefined) return target\n if (source === null || typeof source !== 'object') return source\n if (Array.isArray(source)) return source\n if (!isPlainRecord(source)) return source\n // DU rebase: if this path is a discriminated union AND target/\n // source describe different variants, rebase target onto the\n // matching variant's slim default before merging. Skips when no\n // schema is provided (callers without an adapter handle, including\n // tests) or when the DU info isn't available at this path.\n let mergeTarget = target\n if (schema !== undefined) {\n const du = schema.getUnionDiscriminatorAtPath(path as Segment[])\n if (du !== undefined) {\n const sourceDisc = (source as Record<string, unknown>)[du.discriminatorKey]\n const targetDisc = isPlainRecord(target)\n ? (target as Record<string, unknown>)[du.discriminatorKey]\n : undefined\n if (sourceDisc !== undefined && !Object.is(sourceDisc, targetDisc)) {\n const variantDefault = du.getVariantDefault(sourceDisc)\n if (isPlainRecord(variantDefault)) {\n mergeTarget = variantDefault\n }\n }\n }\n }\n const out: Record<string, unknown> = isPlainRecord(mergeTarget) ? { ...mergeTarget } : {}\n for (const key of Object.keys(source)) {\n out[key] = mergeDeep(out[key], (source as Record<string, unknown>)[key], [...path, key], schema)\n }\n return out\n}\n","/**\n * Stable identifiers for library-emitted `ValidationError` codes.\n *\n * Convention: `<scope>:<kebab-case-identifier>`. Three scopes are\n * recognised by the library:\n *\n * - `atta:` — emitted by the framework-agnostic core (this map).\n * - `zod:` — emitted by the Zod adapter; computed inline from\n * `issue.code` (e.g. `zod:too_small`). No enum here because\n * Zod's code list evolves.\n * - consumer-defined — anything the consumer's backend / app stamps\n * onto a `ValidationError` (via the `parseApiErrors` wire payload\n * or `setFieldErrors` directly). Pick a scope (`api:`, `auth:`,\n * etc.) and stay consistent.\n *\n * Use these constants in tests and error-routing UI:\n *\n * ```ts\n * if (error.code === AttaformErrorCode.NoValueSupplied) {\n * // user hasn't filled this field\n * }\n * ```\n */\nexport const AttaformErrorCode = {\n /** A required field is in the blank set — user hasn't supplied a value. */\n NoValueSupplied: 'atta:no-value-supplied',\n /** The schema adapter's `validateAtPath` threw synchronously. */\n AdapterThrew: 'atta:adapter-threw',\n /** The supplied path didn't resolve to any node in the schema. */\n PathNotFound: 'atta:path-not-found',\n} as const\n\nexport type AttaformErrorCode = (typeof AttaformErrorCode)[keyof typeof AttaformErrorCode]\n","import { getCurrentScope, onScopeDispose, ref, watchEffect, type Ref } from 'vue'\nimport type {\n HandleSubmit,\n OnError,\n OnInvalidSubmitPolicy,\n OnSubmit,\n ReactiveValidationStatus,\n SubmitHandler,\n ValidationError,\n ValidationResponse,\n ValidationResponseWithoutValue,\n} from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { __DEV__ } from './dev'\nimport { AttaformErrorCode } from './error-codes'\nimport { SubmitErrorHandlerError } from './errors'\nimport { canonicalizePath, segmentsForPathKey, type Path } from './paths'\n\n/**\n * Tracks FormStores for which we've already emitted the\n * \"validate() called outside an effect scope\" warning. One warn per\n * store keeps the diagnostic loud the first time and silent for the\n * rest of the run — important for hot-loop callers that would\n * otherwise spam the console (a tight test loop calling validate()\n * 1000 times shouldn't produce 1000 warnings).\n */\nconst warnedNoScopeStores: WeakSet<FormStore<GenericForm>> | null = __DEV__\n ? new WeakSet<FormStore<GenericForm>>()\n : null\n\n/**\n * validate + handleSubmit, both built against a FormStore<F>. Replaces\n * use-form-store's validation factory + the submit wrapper in\n * use-abstract-form.ts.\n *\n * Phase 5.6: validation is async end-to-end. `AbstractSchema.validateAtPath`\n * returns `Promise<ValidationResponse<F>>`, so every caller here awaits.\n * The reactive `validate()` ref carries a `pending` flag to distinguish\n * \"in-flight\" from \"settled\"; stale results are dropped via a per-call\n * generation counter.\n */\n\nexport type BuildProcessFormOptions = {\n /**\n * Policy applied inside handleSubmit when validation fails. Invoked\n * after the error store is populated and before the user's `onError`\n * callback. Default `'none'`.\n */\n onInvalidSubmit?: OnInvalidSubmitPolicy\n}\n\nexport function buildProcessForm<F extends GenericForm>(\n state: FormStore<F>,\n formInstanceId: string,\n options: BuildProcessFormOptions = {}\n) {\n const invalidPolicy: OnInvalidSubmitPolicy = options.onInvalidSubmit ?? 'none'\n\n function validate(pathInput?: string | Path): Readonly<Ref<ReactiveValidationStatus<F>>> {\n // Start in a pending state — the first async run has not settled yet.\n // When validation fires, this ref writes `{ pending: false, ... }`\n // with the resolved status; stale writes (older generation) are\n // dropped so a slow earlier run can't overwrite a newer result.\n const result = ref<ReactiveValidationStatus<F>>({\n pending: true,\n errors: undefined,\n success: false,\n formKey: state.formKey,\n }) as Ref<ReactiveValidationStatus<F>>\n\n let gen = 0\n\n async function kickoff(data: unknown, path: Path | undefined, captured: number): Promise<void> {\n // Runs on a microtask outside the watchEffect's sync frame. Reads\n // and writes to reactive state inside this function DO NOT track\n // against the effect — the activeEffect stack is empty here —\n // so writing to `activeValidations` / `result` can't re-trigger\n // the watchEffect below.\n state.activeValidations.value += 1\n result.value = {\n pending: true,\n errors: undefined,\n success: false,\n formKey: state.formKey,\n }\n try {\n const refinement = await runRefinementValidation(data, path)\n if (captured !== gen) return\n result.value = settled(composeWithDerivedBlank(refinement, path))\n } catch (err) {\n if (captured !== gen) return\n // Adapters are contractually \"return errors, don't throw\"; if\n // one does throw we don't want the validate() ref to hang in\n // `pending: true` forever. Wrap the throw as a single\n // adapter-level error so the form surfaces something.\n result.value = {\n pending: false,\n errors: [\n {\n message: adapterThrowMessage(err),\n path: [],\n formKey: state.formKey,\n code: AttaformErrorCode.AdapterThrew,\n },\n ],\n success: false,\n formKey: state.formKey,\n }\n } finally {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n }\n\n const stop = watchEffect(() => {\n // Read form.value (or the subtree at path) so the effect re-runs\n // on any mutation. We must NOT touch any other reactive state\n // here — the writes in `kickoff` would otherwise re-trigger the\n // effect in a hot loop. Deferring via `queueMicrotask` puts the\n // writes on a clean task where `activeEffect` is null.\n const segments = pathInput === undefined ? undefined : toSegments(pathInput)\n const dataAtPath = segments === undefined ? state.form.value : state.getValueAtPath(segments)\n const localGen = ++gen\n queueMicrotask(() => {\n void kickoff(dataAtPath, segments, localGen)\n })\n })\n // Tie the watcher's lifetime to the caller's effect scope so\n // components that call validate() in setup release the watcher on\n // unmount. Tests calling validate() in a raw context simply leak\n // the watcher for the test's duration — acceptable given tests\n // tear down the module context per run.\n if (getCurrentScope() !== undefined) {\n onScopeDispose(stop)\n } else if (\n __DEV__ &&\n warnedNoScopeStores !== null &&\n !warnedNoScopeStores.has(state as FormStore<GenericForm>)\n ) {\n warnedNoScopeStores.add(state as FormStore<GenericForm>)\n console.warn(\n '[attaform] validate() called outside a Vue effect scope; ' +\n 'its reactive watcher will leak until the form is garbage-collected. ' +\n 'Fix: call validate() inside setup() / a child component, ' +\n 'or wrap the call in `effectScope().run(...)`.'\n )\n }\n return result as Readonly<Ref<ReactiveValidationStatus<F>>>\n }\n\n /**\n * Imperative one-shot validation. Doesn't subscribe to form reactivity;\n * each call runs validation once against the current form snapshot.\n * Used by consumers who want to `await` a single validation run — the\n * debounced field-level path in 5.7, server-side round-trips, tests.\n */\n async function validateAsync(\n pathInput?: string | Path\n ): Promise<ValidationResponseWithoutValue<F>> {\n const segments = pathInput === undefined ? undefined : toSegments(pathInput)\n const dataAtPath = segments === undefined ? state.form.value : state.getValueAtPath(segments)\n state.activeValidations.value += 1\n try {\n const refinement = await runRefinementValidation(dataAtPath, segments)\n return stripData(composeWithDerivedBlank(refinement, segments))\n } finally {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n }\n\n /**\n * Refinement-only adapter pass-through. Returns the schema's\n * refinement-class result without touching the blank-required class\n * — that lives reactively on `state.derivedBlankErrors`. Callers\n * compose the consumer-facing response via `composeWithDerivedBlank`\n * so `setAllSchemaErrors` only ever sees refinement errors and the\n * blank class never gets double-counted (once in `schemaErrors`, once\n * in `derivedBlankErrors`).\n */\n async function runRefinementValidation(\n data: unknown,\n path: Path | undefined\n ): Promise<ValidationResponse<F>> {\n return (await state.schema.validateAtPath(data, path)) as ValidationResponse<F>\n }\n\n /**\n * Fold the reactively-derived blank-required errors into a refinement\n * response. The derived class always reflects current state, so this\n * snapshot at call time matches what `form.errors` shows in the same\n * tick.\n */\n function composeWithDerivedBlank(\n refinement: ValidationResponse<F>,\n scope: Path | undefined\n ): ValidationResponse<F> {\n const blankErrors = collectScopedBlankErrors(state, scope)\n if (blankErrors.length === 0) return refinement\n if (refinement.success) {\n return {\n data: undefined,\n errors: blankErrors,\n success: false,\n formKey: state.formKey,\n }\n }\n return { ...refinement, errors: [...refinement.errors, ...blankErrors] }\n }\n\n /**\n * handleSubmit(onSubmit, onError?) builds a submit handler. On success:\n * clear errors, call onSubmit. On failure: populate errors via\n * setAllErrors, then call onError if provided.\n *\n * If the user's onError throws/rejects, the thrown value is re-thrown\n * wrapped in SubmitErrorHandlerError — prior versions swallowed this\n * into a console.error, which masked real bugs.\n *\n * Drives the submission-lifecycle refs on FormStore:\n * - `submitting` flips true at entry, false in `finally`.\n * - `submitCount` increments once per call, regardless of outcome —\n * \"how many times did the user click submit\" is the consumer-facing\n * question, independent of whether anything awaited.\n * - `submitError` clears at entry and captures anything thrown from\n * the user callback (or the wrapped error-handler error). Re-throws\n * after capturing so imperative callers (`await handler(event)`)\n * still see the rejection; template `@submit=\"...\"` callers read\n * `submitError` instead.\n *\n * Phase 5.6: the pre-dispatch validation is now async, so the handler\n * awaits `runValidation` before branching on success/failure. The\n * `validating` ref (backed by `state.activeValidations`) is true\n * for the validation window.\n */\n const handleSubmit: HandleSubmit<F> = (onSubmit: OnSubmit<F>, onError?: OnError) => {\n const submitHandler: SubmitHandler = async (event?: Event): Promise<void> => {\n if (\n event !== undefined &&\n 'preventDefault' in event &&\n typeof event.preventDefault === 'function'\n ) {\n event.preventDefault()\n }\n // Use the in-flight counter on FormStore so two overlapping submit\n // handlers don't clobber each other: the first completion only\n // flips submitting to false when the counter reaches zero, not\n // unconditionally. submitError is shared across runs by design — a\n // later run's success / failure replaces the earlier capture,\n // UNLESS a `reset()` fired between entry and throw (see below).\n const genAtEntry = state.submissionGeneration.value\n state.activeSubmissions.value += 1\n state.submitting.value = true\n state.submitError.value = null\n // Abort any in-flight per-field validation runs so their late\n // writes can't clobber the authoritative submit result. Also\n // clears debounce timers that never fired.\n state.cancelFieldValidation()\n state.activeValidations.value += 1\n let validationSettled = false\n try {\n const refinement = await runRefinementValidation(state.form.value, undefined)\n const merged = composeWithDerivedBlank(refinement, undefined)\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n validationSettled = true\n // Generation guard: if `reset()` fired while we were awaiting\n // validation, the consumer just zeroed the submission surface\n // — the validation result is for state that's been replaced.\n // Skip the schema-error write so reset's empty store stays\n // empty; still run the user's onError so they get the result\n // (it's their data, not ours, to discard).\n const generationStillValid = state.submissionGeneration.value === genAtEntry\n if (!merged.success) {\n // Source-segregated writer: only refinement-class errors land\n // in `schemaErrors`. The blank-required class is already in\n // `derivedBlankErrors` (reactively derived from `blankPaths`),\n // so writing it here would double-count. User-injected errors\n // live in their own store and are NOT clobbered by validation.\n if (generationStillValid) {\n if (refinement.success) {\n state.clearSchemaErrors()\n } else {\n state.setAllSchemaErrors(refinement.errors)\n }\n }\n // Apply the invalid-submit focus/scroll policy AFTER populating\n // the error store (so getFirstErrorElement walks the fresh\n // entries) and BEFORE the user's onError callback (so consumer\n // logic can override by calling .focus on something else).\n // Skip the policy too on a stale generation — the post-reset\n // form has no errors to focus.\n if (generationStillValid) {\n applyInvalidSubmitPolicy(state, formInstanceId, invalidPolicy)\n }\n if (onError !== undefined) {\n try {\n await onError(merged.errors)\n } catch (cause) {\n throw new SubmitErrorHandlerError('User-provided onError threw', { cause })\n }\n }\n return\n }\n // Schema-only clear: a successful submit means refinement\n // validation passed AND no required-blank errors exist, so the\n // schema-error store goes empty. User-injected errors persist —\n // consumers managing their own warning/info state via\n // setFieldErrors keep ownership of that lifecycle. Skip the\n // clear when reset already cleared (and bumped gen) — any\n // errors injected by post-reset user mutations would be wrongly\n // wiped otherwise.\n if (generationStillValid) {\n state.clearSchemaErrors()\n }\n await onSubmit(merged.data)\n // Notify subscribers (persistence's clear-on-success handler,\n // future hooks). Fires only when the user callback resolved —\n // validation-failure and callback-throw skip it.\n state.emitSubmitSuccess()\n } catch (err) {\n // Only publish the error if `reset()` hasn't fired since this\n // submission began. Otherwise the consumer just zeroed the\n // submission surface and we'd undo their intent by re-raising\n // into `submitError`. We still re-throw so imperative callers\n // (`await handler(event)`) observe the rejection.\n if (state.submissionGeneration.value === genAtEntry) {\n state.submitError.value = err\n }\n throw err\n } finally {\n // If validation threw before we decremented, drop the counter now\n // so `validating` doesn't hang true after a failed submit.\n if (!validationSettled) {\n state.activeValidations.value = Math.max(0, state.activeValidations.value - 1)\n }\n state.activeSubmissions.value = Math.max(0, state.activeSubmissions.value - 1)\n // `activeSubmissions` always decrements (the submission is done),\n // but the *visible* lifecycle counters — `submitting` and\n // `submitCount` — only update when the submission's generation\n // still matches. A post-reset completion is a no-op from the\n // consumer's point of view: reset already flipped `submitting`\n // to false and zeroed `submitCount`, and the finished submission\n // belongs to the prior generation.\n if (state.submissionGeneration.value === genAtEntry) {\n state.submitting.value = state.activeSubmissions.value > 0\n state.submitCount.value += 1\n }\n }\n }\n return submitHandler\n }\n\n return { validate, validateAsync, handleSubmit }\n}\n\nfunction toSegments(pathInput: string | Path): Path {\n return canonicalizePath(pathInput).segments\n}\n\nfunction settled<F extends GenericForm>(\n response: ValidationResponse<F>\n): ReactiveValidationStatus<F> {\n if (response.success) {\n return { pending: false, errors: undefined, success: true, formKey: response.formKey }\n }\n return { pending: false, errors: response.errors, success: false, formKey: response.formKey }\n}\n\nfunction stripData<F extends GenericForm>(\n response: ValidationResponse<F>\n): ValidationResponseWithoutValue<F> {\n if (response.success) {\n return { errors: undefined, success: true, formKey: response.formKey }\n }\n return { errors: response.errors, success: false, formKey: response.formKey }\n}\n\nfunction adapterThrowMessage(err: unknown): string {\n if (err instanceof Error) return `Adapter validateAtPath threw: ${err.message}`\n return 'Adapter validateAtPath threw a non-Error value'\n}\n\n/**\n * Read the reactively-derived blank-required errors out of the store,\n * filtered to paths inside `scope` (or all paths when `scope` is\n * `undefined`). The errors themselves are computed on the FormStore via\n * `derivedBlankErrors` — this helper just snapshots a scoped slice for\n * the validation/submit response. Mutating the returned array is safe;\n * the store's computed builds a fresh map per recompute.\n */\nfunction collectScopedBlankErrors<F extends GenericForm>(\n state: FormStore<F>,\n scope: Path | undefined\n): ValidationError[] {\n const derived = state.derivedBlankErrors.value\n if (derived.size === 0) return []\n const errors: ValidationError[] = []\n for (const [pathKey, entries] of derived) {\n if (scope !== undefined) {\n // Cache hit on canonical PathKeys; cold (corrupt) keys return\n // null and we skip. Don't round-trip through\n // `canonicalizePath(pathKey)` — that would treat the JSON-encoded\n // string as a NEW dotted path and produce a single segment\n // containing the literal JSON.\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n if (!pathStartsWith(segments, scope)) continue\n }\n errors.push(...entries)\n }\n return errors\n}\n\n/**\n * `true` if `target`'s segments start with `prefix`. Used to honour the\n * per-path scope of `validate(path)` / `validateAsync(path)` — only\n * blank paths inside the validated subtree contribute. An empty prefix\n * matches every path.\n */\nfunction pathStartsWith(target: Path, prefix: Path): boolean {\n if (prefix.length > target.length) return false\n for (let i = 0; i < prefix.length; i++) {\n if (!Object.is(target[i], prefix[i])) return false\n }\n return true\n}\n\nfunction applyInvalidSubmitPolicy<F extends GenericForm>(\n state: FormStore<F>,\n formInstanceId: string,\n policy: OnInvalidSubmitPolicy\n): void {\n if (policy === 'none') return\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return\n if (policy === 'scroll-to-first-error') {\n target.element.scrollIntoView()\n return\n }\n if (policy === 'focus-first-error') {\n target.element.focus()\n return\n }\n // 'both' — scroll first, then focus with preventScroll so the\n // browser doesn't undo the explicit scroll.\n target.element.scrollIntoView()\n target.element.focus({ preventScroll: true })\n}\n","import type { AbstractSchema } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Best-effort top-level field hint for diagnostic error messages.\n * Walks the schema's slim default at the root and returns its keys\n * — sufficient for object-rooted schemas (the overwhelming majority).\n * Non-object roots return `[]`; the message degrades by omitting the\n * fields clause rather than throwing.\n *\n * No adapter contract change: every adapter already implements\n * `getDefaultAtPath([])` for the structural-fill pipeline, so this\n * helper is free.\n */\nexport function extractSchemaFields(\n schema: AbstractSchema<GenericForm, GenericForm>\n): readonly string[] {\n try {\n const root = schema.getDefaultAtPath([])\n if (root !== null && typeof root === 'object' && !Array.isArray(root)) {\n return Object.keys(root as object)\n }\n } catch {\n // Adapter threw — degrade gracefully so the diagnostic still fires.\n }\n return []\n}\n","/**\n * Slim-primitive write gate.\n *\n * Walks a value tree from a write path, validating that each leaf's\n * primitive type matches the schema's slim primitive set at the\n * corresponding sub-path. Used by `setValueAtPath` to reject writes\n * whose primitive shape can't possibly satisfy the slim schema —\n * regardless of refinement-level conformance.\n *\n * Refinement-level constraints (format checks, length / range bounds,\n * enum membership, literal equality) are NOT enforced here; they're\n * a validation-time concern. This gate exists purely to keep the\n * runtime store's primitive shape honest.\n */\nimport type { AbstractSchema, SlimPrimitiveKind } from '../types/types-api'\nimport type { Path, Segment } from './paths'\nimport { isPlainRecord } from './path-walker'\nimport { __DEV__ } from './dev'\n\n/**\n * Per-store one-shot dev-warn dedupe. Keyed by (FormStore identity,\n * dotted path + offending kind) so the same misuse during a v-for\n * re-render doesn't flood the console.\n *\n * In production, `__DEV__` is `false` and the WeakMap allocation\n * tree-shakes out — `recordRejection` returns `false` (don't warn).\n */\nconst warnedRejections: WeakMap<object, Set<string>> | null = __DEV__\n ? new WeakMap<object, Set<string>>()\n : null\n\nfunction shouldWarnOnce(store: object, key: string): boolean {\n if (warnedRejections === null) return false\n let set = warnedRejections.get(store)\n if (set === undefined) {\n set = new Set()\n warnedRejections.set(store, set)\n }\n if (set.has(key)) return false\n set.add(key)\n return true\n}\n\n/**\n * Map a value to its slim primitive kind. Mirrors the adapter walker's\n * leaf-level mapping so the same kind names compare across the\n * accept-set boundary.\n *\n * Exported so the default-values pipelines can reuse the same\n * primitive-vs-refinement classification logic the runtime gate uses.\n */\nexport function slimKindOf(value: unknown): SlimPrimitiveKind {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (Array.isArray(value)) return 'array'\n if (value instanceof Date) return 'date'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n const t = typeof value\n switch (t) {\n case 'string':\n return 'string'\n case 'number':\n return 'number'\n case 'boolean':\n return 'boolean'\n case 'bigint':\n return 'bigint'\n case 'symbol':\n return 'symbol'\n case 'function':\n return 'function'\n case 'undefined':\n return 'undefined'\n case 'object':\n return 'object'\n }\n}\n\nfunction isLeafValue(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (Array.isArray(value)) return false\n if (isPlainRecord(value)) return false\n return true\n}\n\n/**\n * Validate `value` against the schema's slim shape, descending into\n * plain records and arrays so every leaf is checked at its sub-path.\n *\n * Returns `true` if every leaf's primitive matches the schema's\n * accept set at its path; `false` otherwise (and emits a one-shot\n * dev-warn naming the bad path + offending kind + accepted kinds).\n *\n * Conventions:\n * - Empty accept set → REJECT every kind. This covers a `never`-typed\n * path (intentionally accepts nothing) AND unresolvable paths (typo\n * in `register('addr.zipp')` against a schema that doesn't have\n * that field — silently accepting the write would create a phantom\n * slot in storage). The \"permissive\" cases (`any` / `unknown` /\n * `void` and the lazy-peel-failure case) return the FULL accept set\n * instead, so they accept anything via the membership check below\n * — they don't go through this branch.\n * - The value AT the write path is also checked: writing `'oops'`\n * to a path expecting `'object'` is rejected at the top-level.\n * - For wrappers like `.optional()` / `.nullable()`, the adapter's\n * accept set already includes `'undefined'` / `'null'` — no\n * special-casing here.\n */\nexport function isSlimPrimitiveValid(\n schema: AbstractSchema<unknown, unknown>,\n store: object,\n path: Path,\n value: unknown\n): boolean {\n return walk(schema, store, path, value)\n}\n\nfunction walk(\n schema: AbstractSchema<unknown, unknown>,\n store: object,\n path: Path,\n value: unknown\n): boolean {\n // Top-of-tree check: does the value at THIS path satisfy the\n // schema's slim kinds at this path? Recurse into containers\n // afterwards — the recursion checks the elements' kinds at\n // the sub-paths.\n //\n // An empty accept set means the schema rejects every kind at this\n // path: either the path doesn't resolve (typo / unknown leaf) or\n // the path resolves to a `never`-typed schema. Either way, the\n // membership check below rejects, blocking the write. `any` /\n // `unknown` / `void` and the lazy-peel-failure case return the\n // full permissive set — those still accept any kind.\n const accepted = schema.getSlimPrimitiveTypesAtPath(path)\n const kind = isLeafValue(value) ? slimKindOf(value) : Array.isArray(value) ? 'array' : 'object'\n if (!accepted.has(kind)) {\n reportRejection(store, path, kind, accepted)\n return false\n }\n\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (!walk(schema, store, [...path, i], value[i])) return false\n }\n return true\n }\n\n if (isPlainRecord(value)) {\n for (const key of Object.keys(value)) {\n if (!walk(schema, store, [...path, key], (value as Record<string, unknown>)[key])) {\n return false\n }\n }\n return true\n }\n\n return true\n}\n\nfunction reportRejection(\n store: object,\n path: Path,\n kind: SlimPrimitiveKind,\n accepted: Set<SlimPrimitiveKind>\n): void {\n if (!__DEV__) return\n const dotted = path.map((s: Segment) => String(s)).join('.') || '(root)'\n const key = `${dotted}::${kind}`\n if (!shouldWarnOnce(store, key)) return\n\n // KISS rule: state the problem in one sentence, then list the fix.\n // Devs scan the first line; everything after is the recipe.\n\n // Path doesn't resolve (or resolves to a `never`-typed schema). The\n // headline names the actual cause; `never`-typed paths are rare\n // enough that they don't deserve top billing.\n if (accepted.size === 0) {\n console.warn(\n `[attaform] Cannot write to '${dotted}' — this path is not in your schema.\\n` +\n ` Fix: check for a typo in register('${dotted}'); it should match a leaf key in your schema.\\n` +\n ` (If the path resolves to a never-typed schema, it explicitly admits no values — relax the schema if intentional.)\\n` +\n ` The write was a no-op.`\n )\n return\n }\n\n const expected = formatExpectedKinds(accepted)\n\n // String-to-number is the most common gate rejection in real apps:\n // a plain `<input v-register>` against a numeric leaf reads\n // `el.value` as a string. Show both v-register fix paths verbatim\n // so the dev can copy-paste rather than parse \"slim primitive set\".\n if (kind === 'string' && accepted.has('number')) {\n console.warn(\n `[attaform] Cannot write a string to '${dotted}' — the schema expects ${expected}.\\n` +\n ` Fix: add type=\"number\" to the input, OR use the .number modifier on v-register:\\n` +\n ` <input type=\"number\" v-register=\"register('${dotted}')\" />\\n` +\n ` <input v-register.number=\"register('${dotted}')\" />\\n` +\n ` The write was a no-op.`\n )\n return\n }\n\n // Generic kind mismatch — no built-in DOM coercion path to suggest.\n console.warn(\n `[attaform] Cannot write a ${kind} to '${dotted}' — the schema expects ${expected}.\\n` +\n ` The write was a no-op.`\n )\n}\n\nfunction formatExpectedKinds(accepted: Set<SlimPrimitiveKind>): string {\n const list = [...accepted].sort()\n if (list.length === 1) return list[0] as string\n if (list.length === 2) return `${list[0]} or ${list[1]}`\n return `one of: ${list.join(', ')}`\n}\n","/**\n * Schema-driven coercion of user-typed DOM values at the v-register\n * directive layer. When the slim schema declares a numeric or\n * boolean type at a path, the directive coerces incoming string\n * values (`'25'` → `25`, `'true'` → `true`) before the slim-primitive\n * gate sees the write — making the schema authoritative for storage\n * shape and freeing consumers from sprinkling `.number` modifiers\n * across templates.\n *\n * Coercion is consumer-extensible: a `CoercionRegistry` is just an\n * `Array<CoercionEntry>` keyed at config time by `(input, output)`\n * `SlimPrimitiveKind` literals. The library ships\n * `defaultCoercionRules` (string→number, string→boolean) and\n * `defineCoercion` for type-narrowed authoring; consumers spread the\n * defaults to extend or supply their own array to replace.\n *\n * Coercion applies ONLY to user-typed DOM values flowing through\n * the directive's assigner. Programmatic writes (`form.setValue`,\n * `setValueWithInternalPath`) bypass coercion — they're authoritative\n * writes whose strict typing is on the caller. This mirrors the\n * `transforms` pipeline's user-input-only contract.\n */\nimport type {\n AbstractSchema,\n CoercionEntry,\n CoercionRegistry,\n CoercionResult,\n SlimPrimitiveKind,\n} from '../types/types-api'\nimport type { Path } from './paths'\nimport { slimKindOf } from './slim-primitive-gate'\nimport { __DEV__ } from './dev'\n\n/**\n * Type-narrowing helper for authoring entries. At runtime it's\n * identity; at compile time it preserves the `input` / `output`\n * literal types so `transform`'s parameter is narrowed to the\n * runtime type instead of widening to `SlimRuntimeOf<SlimPrimitiveKind>`.\n *\n * Without this helper, authoring `{ input: 'string', output:\n * 'number', transform: (s) => ... }` against the broader\n * `CoercionEntry` widens `s` to `string | number | boolean | ...`,\n * forcing a cast in every transform body. `defineCoercion` is the\n * opaque-free idiom.\n */\nexport function defineCoercion<I extends SlimPrimitiveKind, O extends SlimPrimitiveKind>(\n entry: CoercionEntry<I, O>\n): CoercionEntry<I, O> {\n return entry\n}\n\n/**\n * Internal index built from a `CoercionRegistry` at config-resolve\n * time. Keyed by `${input}->${output}` for O(1) per-keystroke\n * dispatch. The authoring shape (array, ergonomic, type-narrowing-\n * friendly) and the dispatch shape (Map, fast) decouple cleanly.\n */\nexport type CoercionIndex = ReadonlyMap<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>\n\n/** Identity function reused by `buildCoerceFn` when coercion is\n * disabled or the path admits no coercion target. */\nexport const IDENTITY: (v: unknown) => unknown = (v) => v\n\n/** Frozen empty index — reference-equal sentinel that lets\n * `buildCoerceFn` short-circuit to `IDENTITY` without allocation. */\nconst EMPTY_INDEX: CoercionIndex = new Map()\n\n/**\n * The library's built-in registry. Two cells: string→number and\n * string→boolean. Re-exported so consumers can spread it when\n * supplying a custom registry that extends defaults.\n */\nexport const defaultCoercionRules: CoercionRegistry = [\n defineCoercion({\n input: 'string',\n output: 'number',\n transform: (s) => {\n // Trim first so whitespace-only inputs don't slip past the\n // empty-string guard via `Number(' ') === 0`. The blank-paths\n // machinery owns the empty-input shape; coerce only fires when\n // there's a non-blank token to consider.\n const trimmed = s.trim()\n if (trimmed === '') return { coerced: false }\n const n = Number(trimmed)\n if (!Number.isFinite(n)) return { coerced: false }\n return { coerced: true, value: n }\n },\n }),\n defineCoercion({\n input: 'string',\n output: 'boolean',\n transform: (s) => {\n // Case-insensitive + whitespace-tolerant. Aligns with the\n // aria-style boolean-token convention (`aria-checked` accepts\n // \"true\"/\"True\"/\"TRUE\"). DOM `value=` attributes preserve\n // whatever case the dev wrote, and `value=\"True\"` is common\n // enough that strict-lowercase-only would be a footgun.\n const normalized = s.trim().toLowerCase()\n if (normalized === 'true') return { coerced: true, value: true }\n if (normalized === 'false') return { coerced: true, value: false }\n return { coerced: false }\n },\n }),\n]\n\n/**\n * Resolve the consumer's `coerce` config slot to a concrete index.\n * `true` / `undefined` → indexed defaults; `false` → empty index;\n * custom registry → indexed (with duplicate-pair dev-warn).\n *\n * Called once per FormStore in `createFormStore`.\n */\nexport function resolveCoercionIndex(\n config: boolean | CoercionRegistry | undefined\n): CoercionIndex {\n if (config === false) return EMPTY_INDEX\n const rules = config === undefined || config === true ? defaultCoercionRules : config\n return indexRules(rules)\n}\n\nfunction indexRules(rules: CoercionRegistry): CoercionIndex {\n const idx = new Map<`${SlimPrimitiveKind}->${SlimPrimitiveKind}`, CoercionEntry>()\n for (const entry of rules) {\n // The static type says `entry: CoercionEntry`, but consumers can\n // pass in registries assembled at runtime (parsed JSON, plugin\n // config) where individual entries may be malformed. Cast through\n // `unknown` to inspect runtime shape without lint complaining about\n // an \"always true\" type-narrowing branch.\n const candidate = entry as unknown\n if (\n candidate === null ||\n typeof candidate !== 'object' ||\n typeof (candidate as { transform?: unknown }).transform !== 'function'\n ) {\n if (__DEV__) {\n console.warn('[attaform] coercion entry missing or invalid `transform` — skipped.')\n }\n continue\n }\n const key = `${entry.input}->${entry.output}` as const\n if (idx.has(key) && __DEV__) {\n console.warn(`[attaform] duplicate coercion rule for '${key}' — last entry wins.`)\n }\n idx.set(key, entry)\n }\n return idx\n}\n\n/**\n * Build the per-register coerce closure. The closure captures the\n * resolved `accepted` set + the index, so the per-event hot path\n * doesn't re-walk the schema on every keystroke. Returns `IDENTITY`\n * when coerce is disabled — zero allocation for the common case.\n */\nexport function buildCoerceFn(\n schema: AbstractSchema<unknown, unknown>,\n segments: Path,\n index: CoercionIndex\n): (value: unknown) => unknown {\n if (index === EMPTY_INDEX) return IDENTITY\n if (index.size === 0) return IDENTITY\n const accepted = schema.getSlimPrimitiveTypesAtPath(segments)\n const elementAccepted =\n accepted.has('array') || accepted.has('set')\n ? schema.getSlimPrimitiveTypesAtPath([...segments, 0])\n : undefined\n return (value) => coerceValue(value, accepted, elementAccepted, index)\n}\n\n/**\n * Element-level coerce closure. Returns `undefined` when the path\n * isn't a container (scalar paths use `buildCoerceFn` exclusively).\n *\n * Why this is separate from `buildCoerceFn`: the path-level closure\n * handles the WRITE path correctly — given a container value, it\n * iterates and coerces each element internally. But the directive's\n * READ-side comparisons (`setChecked` array/Set branches,\n * `setSelected` multi-select) compare a SCALAR DOM-side value (the\n * option's `value` attribute) against the post-coerce container\n * elements. The path-level closure can't help here because it would\n * see a scalar and look up the path's accept set (`{ array }`),\n * which has no scalar coercion target. The element-level closure\n * skips ahead to the element-type accept set.\n */\nexport function buildElementCoerceFn(\n schema: AbstractSchema<unknown, unknown>,\n segments: Path,\n index: CoercionIndex\n): ((value: unknown) => unknown) | undefined {\n if (index === EMPTY_INDEX) return undefined\n if (index.size === 0) return undefined\n const accepted = schema.getSlimPrimitiveTypesAtPath(segments)\n if (!accepted.has('array') && !accepted.has('set')) return undefined\n const elementAccepted = schema.getSlimPrimitiveTypesAtPath([...segments, 0])\n return (value) => coerceScalar(value, elementAccepted, index)\n}\n\n/**\n * Pick the unambiguous coercion target for an accept set. Returns\n * the target kind only when it's the SOLE coercible kind — if the\n * path admits both `string` and `number`, the schema explicitly\n * accepts either, so silent retyping is wrong (passthrough).\n */\nfunction pickScalarTarget(accepted: ReadonlySet<SlimPrimitiveKind>): SlimPrimitiveKind | null {\n if (accepted.has('string')) return null\n if (accepted.has('number')) return 'number'\n if (accepted.has('boolean')) return 'boolean'\n if (accepted.has('bigint')) return 'bigint'\n return null\n}\n\n/**\n * Per-store WeakMap dedupe of dev-warns from coercion. Mirrors the\n * slim-gate's pattern (`slim-primitive-gate.ts:28-42`) so the same\n * (rule, error) pair doesn't flood the console during a v-for re-\n * render. Key shape: `<input>-><output>::<reason>`.\n */\nconst warnedCoerce: WeakMap<object, Set<string>> | null = __DEV__\n ? new WeakMap<object, Set<string>>()\n : null\nconst sharedWarnStore: object = {}\n\nfunction shouldWarnOnce(key: string): boolean {\n if (warnedCoerce === null) return false\n let set = warnedCoerce.get(sharedWarnStore)\n if (set === undefined) {\n set = new Set()\n warnedCoerce.set(sharedWarnStore, set)\n }\n if (set.has(key)) return false\n set.add(key)\n return true\n}\n\nfunction coerceScalar(\n value: unknown,\n accepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): unknown {\n if (accepted.size === 0) return value\n const sourceKind = slimKindOf(value)\n if (accepted.has(sourceKind)) return value\n const target = pickScalarTarget(accepted)\n if (target === null) return value\n const entry = index.get(`${sourceKind}->${target}`)\n if (entry === undefined) return value\n let result: CoercionResult<unknown>\n try {\n result = entry.transform(value as never) as CoercionResult<unknown>\n } catch (err) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::throw`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' threw — write passes through.`,\n err\n )\n }\n return value\n }\n if (!result.coerced) return value\n // Post-validate: the rule claimed it coerced, but did it actually\n // produce a value matching the declared `output`? Defends against\n // buggy consumer rules without forcing them to validate themselves.\n const returnedKind = slimKindOf(result.value)\n if (returnedKind !== entry.output) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::wrong-kind:${returnedKind}`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' produced a ${returnedKind} — write passes through.`\n )\n }\n return value\n }\n if (entry.output === 'number' && !Number.isFinite(result.value as number)) {\n if (__DEV__ && shouldWarnOnce(`${entry.input}->${entry.output}::nan`)) {\n console.warn(\n `[attaform] coercion '${entry.input}->${entry.output}' produced a non-finite number — write passes through.`\n )\n }\n return value\n }\n return result.value\n}\n\nfunction coerceArrayMembers(\n arr: readonly unknown[],\n elementAccepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): readonly unknown[] {\n let changed = false\n const out: unknown[] = []\n for (const el of arr) {\n const next = coerceScalar(el, elementAccepted, index)\n if (next !== el) changed = true\n out.push(next)\n }\n return changed ? out : arr\n}\n\nfunction coerceSetMembers(\n set: ReadonlySet<unknown>,\n elementAccepted: ReadonlySet<SlimPrimitiveKind>,\n index: CoercionIndex\n): ReadonlySet<unknown> {\n let changed = false\n const out: unknown[] = []\n for (const el of set) {\n const next = coerceScalar(el, elementAccepted, index)\n if (next !== el) changed = true\n out.push(next)\n }\n return changed ? new Set(out) : set\n}\n\nfunction coerceValue(\n value: unknown,\n accepted: ReadonlySet<SlimPrimitiveKind>,\n elementAccepted: ReadonlySet<SlimPrimitiveKind> | undefined,\n index: CoercionIndex\n): unknown {\n if (Array.isArray(value)) {\n if (!accepted.has('array') || elementAccepted === undefined) return value\n return coerceArrayMembers(value, elementAccepted, index)\n }\n if (value instanceof Set) {\n if (!accepted.has('set') || elementAccepted === undefined) return value\n return coerceSetMembers(value, elementAccepted, index)\n }\n return coerceScalar(value, accepted, index)\n}\n","import { computed, ref, shallowReadonly, type Ref } from 'vue'\nimport type {\n InternalRegisterValue,\n RegisterOptions,\n RegisterTransform,\n RegisterValue,\n WriteMeta,\n} from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { captureUserCallSite } from './dev-stack-trace'\nimport { AnonPersistError } from './errors'\nimport { extractSchemaFields } from './extract-schema-fields'\nimport { canonicalizePath, type Path, type PathKey } from './paths'\nimport { PERSISTENCE_MODULE_KEY } from './persistence'\nimport { buildCoerceFn, buildElementCoerceFn } from './schema-coerce'\n\n// Module-level frozen empty array — re-used as the transforms default\n// across every register() call that doesn't opt in. Avoids a per-call\n// allocation on the 99% of fields that don't declare normalization,\n// while keeping the directive's `for (const t of rv.transforms)`\n// iteration uniform (no null-check needed).\nconst EMPTY_TRANSFORMS: ReadonlyArray<RegisterTransform> = Object.freeze([])\n\n/**\n * Register API factory. Given a FormStore, returns a `register(path)` that\n * produces a RegisterValue suitable for the v-register directive.\n *\n * Design points:\n *\n * - Focus/blur listeners are attached per-element-registration and stored\n * on the element itself via a symbol, then removed on deregistration.\n * No registration-time helper cache.\n * - `innerRef` reads `form.value` directly via `getValueAtPath`; there's\n * no separate raw-vs-form tracking. The synchronous diff-apply writer\n * keeps the two values in lock-step.\n * - Cross-form isolation is by construction: every call to `buildRegister`\n * closes over a FormStore<F> unique to one form.\n */\n\nconst INTERACTIVE_TAG_NAMES = new Set(['INPUT', 'SELECT', 'TEXTAREA'])\n\n// `Symbol.for(...)` so duplicate copies of attaform agree on the\n// element-property key for stashed focus/blur handlers — see\n// `assignKey` in core/directive.ts for the same reasoning.\nconst attaformListenersSymbol: unique symbol = Symbol.for('attaform:focus-listeners')\n\ntype ElementWithListeners = HTMLElement & {\n [attaformListenersSymbol]?: {\n handleFocus: (event: FocusEvent) => void\n handleBlur: (event: FocusEvent) => void\n }\n}\n\nfunction attachFocusListeners<F extends GenericForm>(\n state: FormStore<F>,\n segments: Path,\n element: HTMLElement\n): void {\n const target = element as ElementWithListeners\n if (target[attaformListenersSymbol] !== undefined) return\n const handleFocus = (): void => state.markFocused(segments, true)\n const handleBlur = (): void => state.markFocused(segments, false)\n element.addEventListener('focus', handleFocus)\n element.addEventListener('blur', handleBlur)\n target[attaformListenersSymbol] = { handleFocus, handleBlur }\n}\n\nfunction detachFocusListeners(element: HTMLElement): void {\n const target = element as ElementWithListeners\n const listeners = target[attaformListenersSymbol]\n if (listeners === undefined) return\n element.removeEventListener('focus', listeners.handleFocus)\n element.removeEventListener('blur', listeners.handleBlur)\n delete target[attaformListenersSymbol]\n}\n\nexport function buildRegister<F extends GenericForm>(state: FormStore<F>, formInstanceId: string) {\n // Path-keyed cache of typed-form refs. Lifted out of the per-call\n // closure so multiple `register(path)` invocations for the same\n // path — e.g. two `<input v-register>` bindings to `'numberText'`,\n // or repeated calls inside a render function — share the same ref.\n // Without sharing, the directive's keystroke listener writes to\n // RegisterValue A's `lastTypedForm` while RegisterValue B's\n // `displayValue` reads its own (always-null) ref, and Vue patches\n // B's DOM to the canonical `String(storage)` mid-typing — yanking\n // the user's caret on a sibling input.\n const lastTypedFormByPath = new Map<PathKey, Ref<string | null>>()\n\n return function register(\n pathInput: string | Path,\n options?: RegisterOptions\n ): RegisterValue<unknown> {\n const { segments, key: pathKey } = canonicalizePath(pathInput)\n\n const innerRef = computed(() => state.getValueAtPath(segments)) as Readonly<Ref<unknown>>\n\n // The user's currently-typed string form for numeric fields,\n // populated by the directive on every keystroke and cleared on\n // blur. Lets `displayValue` surface the typed form (e.g. `'1e2'`)\n // mid-typing instead of the canonical `String(storage)` (`'100'`),\n // which Vue would otherwise patch into the DOM and yank the\n // cursor away from the user's caret. After blur the typed form\n // is cleared so `displayValue` falls back to the honest canonical\n // form — what the user sees matches what's in storage. Shared\n // across all RegisterValues for the same path so paired inputs\n // stay in sync mid-typing.\n let lastTypedForm = lastTypedFormByPath.get(pathKey)\n if (lastTypedForm === undefined) {\n lastTypedForm = ref<string | null>(null)\n lastTypedFormByPath.set(pathKey, lastTypedForm)\n }\n\n // String-form view of the path's storage value, with `''` returned\n // for blank membership and for null/undefined storage.\n // The blank branch is what lets a user clear a numeric\n // field: even though storage holds 0, the `:value` binding reads\n // displayValue and writes `''` to el.value, so Vue's next render\n // doesn't undo the user's clear.\n //\n // Typed-form preference (numeric only): when `lastTypedForm` is\n // set AND `parseFloat(lastTypedForm)` equals the current numeric\n // storage, return the typed form. Storage commits live (typing\n // `1e2` writes 100 to storage immediately), but the DOM keeps\n // showing `1e2` until blur — at which point the directive clears\n // `lastTypedForm` and Vue patches the DOM to `String(100)` =\n // `'100'`. The check naturally invalidates on programmatic\n // setValue / hydration / reset (different storage value → fall\n // back to `String(...)`).\n const displayValue = computed(() => {\n if (state.blankPaths.has(pathKey)) return ''\n const raw = state.getValueAtPath(segments)\n if (raw === null || raw === undefined) return ''\n const typed = lastTypedForm.value\n if (typed !== null && typeof raw === 'number' && parseFloat(typed) === raw) {\n return typed\n }\n return String(raw)\n }) as Readonly<Ref<string>>\n\n // Slim default precomputed at register-time. The schema is fixed\n // for the form's lifetime, so this is safe to cache; downstream\n // `markBlank` calls reuse it without re-walking the\n // schema tree.\n const slimDefault = state.schema.getDefaultAtPath(segments)\n\n const persist = options?.persist === true\n const acknowledgeSensitive = options?.acknowledgeSensitive === true\n const transforms = options?.transforms ?? EMPTY_TRANSFORMS\n\n // Schema-driven coerce closure. Captures the path's slim accept set\n // and the form's resolved coercion index so the per-event hot path\n // is a single function call. Identity when the form has coercion\n // disabled (`useForm({ coerce: false })`) or the path admits no\n // coercion target. Cached on RegisterValue so the directive doesn't\n // re-walk the schema per keystroke.\n const coerce = buildCoerceFn(\n state.schema as Parameters<typeof buildCoerceFn>[0],\n segments,\n state.coerceIndex\n )\n const coerceElement = buildElementCoerceFn(\n state.schema as Parameters<typeof buildElementCoerceFn>[0],\n segments,\n state.coerceIndex\n )\n\n // Eager throw: opt-in declared but the form has no persistence wired.\n // Without the throw the directive silently records the opt-in, no\n // writes ever land, and the dev concludes \"persistence is broken\"\n // when the actual issue is a missing `persist:` option on useForm().\n // Throws in dev and prod — contradictions are bugs, not rate-limited\n // drift. The error body carries the schema's top-level fields and a\n // captured call-site frame so the offending form is identifiable\n // from the message alone (script-setup stacks collapse misleadingly).\n //\n // Skipped during SSR: `wirePersistence` is intentionally not run on\n // the server (persistence is a client-only concern), so\n // `state.modules.has(PERSISTENCE_MODULE_KEY)` is always false during\n // SSR — even for forms that DID configure `persist:`. Without this\n // gate the throw would falsely fire on every server-rendered\n // `register({ persist: true })`. The client-side hydration pass\n // re-checks against a freshly-wired module and throws correctly if\n // the misuse is real.\n if (persist && !state.ssr && !state.modules.has(PERSISTENCE_MODULE_KEY)) {\n throw new AnonPersistError({\n cause: 'register-without-config',\n schemaFields: extractSchemaFields(state.schema),\n callSite: captureUserCallSite(),\n })\n }\n\n // `shallowReadonly` is what makes `rv.path`, `rv.formKey`, and the\n // other top-level string fields feel like reactive state in\n // wrapper components: property reads track in computeds /\n // watchEffects, mutations are blocked at runtime + type level, and\n // inner refs (`innerRef`, `displayValue`, `lastTypedForm`) keep\n // their `Ref` shape so the directive's `.value` reads/writes\n // continue to work unchanged.\n const internalRv: InternalRegisterValue = {\n innerRef,\n displayValue,\n lastTypedForm,\n\n markBlank: (): boolean => {\n // Mirror the binding's persist meta so the blank\n // mark rides the same persistence channel as user-typed\n // writes — without this, refresh after a clear silently loses\n // the empty state. The slim default keeps storage well-typed\n // (the schema's getDefaultAtPath returns 0 for z.number(), ''\n // for z.string(), false for z.boolean(), etc.).\n return state.setValueAtPath(segments, slimDefault, {\n blank: true,\n persist,\n })\n },\n\n registerElement: (element: HTMLElement): void => {\n // Skip non-form elements. Prevents accidental registration of\n // component wrapper divs when fallthrough attributes carry the\n // directive past the intended `<input>` / `<select>` / `<textarea>`.\n if (!INTERACTIVE_TAG_NAMES.has(element.tagName)) return\n const added = state.registerElement(segments, element, formInstanceId)\n if (added) attachFocusListeners(state, segments, element)\n },\n\n deregisterElement: (element: HTMLElement): void => {\n detachFocusListeners(element)\n state.deregisterElement(segments, element)\n },\n\n setValueWithInternalPath: (value: unknown, meta?: WriteMeta): boolean => {\n return state.setValueAtPath(segments, value, meta)\n },\n\n // Called by the `vRegisterHint` compile-time transform's wrapping\n // IIFE on every server-side render of `<element v-register=\"…\">`.\n // Without it, every SSR'd FieldState serialises `connected: false`\n // (because Vue skips directive lifecycle during SSR) and the client\n // briefly shows that stale flag until hydration runs the directive's\n // `created` hook. The mark only takes effect when `state.ssr` is\n // true; on the client this is a no-op so the directive lifecycle\n // remains the source of truth.\n markConnectedOptimistically: (): void => {\n state.markConnectedOptimistically(segments)\n },\n\n path: pathKey,\n // Frozen so a wrapper component can pass `rv.segments` directly\n // to `form.fields(...)` without defensive copying — and so test\n // fixtures or downstream code can't mutate the canonical\n // segment list out from under the directive.\n segments: Object.freeze(segments.slice()),\n formKey: state.formKey,\n formInstanceId,\n\n // --- Persistence opt-in (internal; the directive is the only\n // legitimate consumer) ---\n persist,\n acknowledgeSensitive,\n persistOptIns: state.persistOptIns,\n transforms,\n coerce,\n ...(coerceElement !== undefined ? { coerceElement } : {}),\n }\n return shallowReadonly(internalRv) as RegisterValue\n }\n}\n","/** Internal brand for the `Unset` type. Never exposed at runtime. */\ndeclare const _unsetBrand: unique symbol\n\n/**\n * Brand-typed sentinel admitted at every primitive leaf of\n * `DefaultValuesShape<T>`, `setValue`, and `reset`. The runtime value\n * is exported as {@link unset} under the same name.\n */\nexport type Unset = typeof _unsetBrand\n\n/**\n * The `unset` sentinel — pass it as a primitive leaf's value to mark\n * the field **displayed-empty** while storage holds the schema's slim\n * default (`0` / `''` / `false` / `0n`).\n *\n * Use it wherever a primitive leaf value is expected:\n *\n * ```ts\n * const form = useForm({\n * schema: z.object({ income: z.number() }),\n * defaultValues: { income: unset }, // UI starts blank, storage holds 0\n * key: 'housing',\n * })\n *\n * form.setValue('income', unset) // re-blank a field after a write\n * form.reset({ income: unset }) // reset to the blank state\n * ```\n *\n * Accepted at any `string` / `number` / `boolean` / `bigint` leaf in\n * `defaultValues`, `setValue(path, unset)`, and `form.reset({ … })`.\n *\n * The path joins the form's `blankPaths` set as long as it stays\n * unset. Required schemas (no `.optional()` / `.nullable()` /\n * `.default(N)`) raise `\"No value supplied\"` on submit while a leaf\n * is in `blankPaths`; optional / nullable / has-default schemas\n * accept the empty case as their wrapper allows.\n *\n * Storage never holds the symbol — the runtime translates it at the\n * API boundary, so reads through `form.values` always see the slim\n * default. Cross-bundle / SSR-safe: backed by `Symbol.for(...)` so\n * every realm gets the same sentinel.\n *\n * @see {@link isUnset} — type guard that narrows a value back to {@link Unset}.\n * @see `docs/recipes/blank-inputs.md` — the conceptual model behind blank-aware fields.\n */\nexport const unset: Unset = Symbol.for('attaform/unset') as Unset\n\n/**\n * Type guard — `true` when `value` is the `unset` sentinel.\n *\n * ```ts\n * if (isUnset(payload.income)) {\n * // payload.income is the sentinel; the field will display empty\n * }\n * ```\n */\nexport function isUnset(value: unknown): value is Unset {\n return value === unset\n}\n","import type { AbstractSchema } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport { __DEV__ } from './dev'\nimport { canonicalizePath, type Path, type PathKey, type Segment } from './paths'\nimport { isUnset } from './unset'\n\n/**\n * Walk a defaults / setValue / reset payload depth-first and produce\n * the cleaned-up storage tree plus the set of paths to mark as blank.\n * Used at three boundaries:\n *\n * - `useAbstractForm` construction (defaultValues pre-pass)\n * - `setValue(path, unset)` translation\n * - `reset(nextDefaultValues)` translation\n *\n * `blank` is the runtime's bookkeeping for **storage / display\n * divergence** — see `docs/recipes/blank-inputs.md` for the concept. Two sources of\n * marks, gated by that purpose:\n *\n * 1. **Explicit `unset` (any primitive leaf)** — the consumer wrote\n * `unset` at a primitive leaf (`defaultValues: { count: unset }` /\n * `setValue('count', unset)` / `reset({ count: unset })`). The\n * sentinel is replaced with the schema's slim default and the\n * path is added to the result. Explicit user intent applies\n * across every primitive type (string / number / boolean /\n * bigint), so the mark records \"the consumer asked for blank\n * here\" regardless of whether storage and display would otherwise\n * diverge.\n *\n * 2. **Unspecified numeric leaf (auto-mark)** — the consumer's\n * payload is partial (or omitted entirely) and the schema has a\n * `number` / `bigint` leaf the consumer did not cover. The slim\n * default (`0` / `0n`) lands in storage and the path is\n * auto-marked. Rationale: numeric storage forces a value (`0`,\n * `0n`) that the DOM input represents as `''` — the runtime\n * can't tell \"user typed 0\" from \"user supplied nothing\" without\n * this side-channel. Strings and booleans are NOT auto-marked:\n * their slim defaults (`''` / `false`) match what the DOM shows\n * natively, so there's no divergence to record. Adding an\n * auto-mark for those types would be the library second-\n * guessing the schema's accepted-empty verdict, which is the\n * schema author's call to express via `.min(1)` /\n * `z.literal(true)` / refinements.\n *\n * Recurses into plain objects, arrays, and tuples; non-recursable\n * containers (`Date`, `RegExp`, `Map`, `Set`, functions) pass through\n * unchanged. Arrays are NOT auto-mark-recursed (their elements are\n * runtime-added; per-element opt-in via explicit `unset`).\n *\n * Runtime guard: if `unset` lands at a path whose slim default isn't\n * a primitive, emit a one-time dev-warn and recurse into the slim\n * subtree for auto-mark — the path itself is NOT marked.\n * `DefaultValuesShape<T>` blocks this at compile time; the runtime\n * check is a guardrail for plain-JS consumers and dynamic plumbing.\n */\nexport function walkUnsetSentinels<T>(\n values: T,\n schema: AbstractSchema<GenericForm, GenericForm>\n): { cleanedValues: T; paths: PathKey[] } {\n const paths: PathKey[] = []\n // No defaults supplied — auto-mark every primitive leaf reachable\n // from the schema's slim root default. cleanedValues stays `undefined`\n // to preserve createFormStore's existing \"no user defaults\" code path.\n if (values === undefined) {\n const rootSlim = schema.getDefaultAtPath([])\n walkUnspecified(rootSlim, [], paths)\n return { cleanedValues: undefined as unknown as T, paths }\n }\n const cleaned = walk(values as unknown, [], schema, paths)\n return { cleanedValues: cleaned as T, paths }\n}\n\nfunction walk(\n input: unknown,\n segments: Segment[],\n schema: AbstractSchema<GenericForm, GenericForm>,\n paths: PathKey[]\n): unknown {\n if (isUnset(input)) {\n const slim = schema.getDefaultAtPath(segments)\n if (!isPrimitiveOrEmpty(slim)) {\n warnNonPrimitiveLeaf(segments, slim)\n // Recurse into slim subtree so unspecified primitive leaves\n // below this misused `unset` still get auto-marked.\n return walkUnspecified(slim, segments, paths)\n }\n paths.push(canonicalizePath(segments).key)\n return slim\n }\n // User omitted this key — fall through to walkUnspecified on the\n // schema's slim default at this path so primitive leaves get marked.\n if (input === undefined) {\n const slim = schema.getDefaultAtPath(segments)\n return walkUnspecified(slim, segments, paths)\n }\n // Explicit null is the user's choice, not absence — pass through.\n if (input === null) return null\n if (\n input instanceof Date ||\n input instanceof RegExp ||\n input instanceof Map ||\n input instanceof Set ||\n typeof input === 'function'\n ) {\n return input\n }\n // Reference stability: when an array's elements all walk to themselves\n // (no unset substitutions, no schema-only keys synthesized), return the\n // ORIGINAL `input` reference. Without this, a whole-form setValue with\n // a structurally-unchanged subtree (e.g., the `pickup` half of\n // `({ ...prev, delivery: prev.pickup })`) still produces a new clone of\n // pickup, which then re-fires any deep watch on `form.values.pickup` —\n // and a watcher that reacts by writing back to the form loops forever.\n // Returning the original reference for unchanged subtrees keeps Vue's\n // reactivity quiet on identity-equal slots.\n if (Array.isArray(input)) {\n const out = new Array(input.length)\n let mutated = false\n for (let i = 0; i < input.length; i++) {\n const walked = walk(input[i], [...segments, i], schema, paths)\n out[i] = walked\n if (walked !== input[i]) mutated = true\n }\n return mutated ? out : input\n }\n if (typeof input === 'object') {\n // Walk both user-supplied keys AND schema-only keys so unspecified\n // primitive leaves get auto-marked even inside a partially-supplied\n // object (e.g., `defaultValues: { user: { name: 'a' } }` against a\n // schema with `user.{name, age}` marks `user.age`).\n const slim = schema.getDefaultAtPath(segments)\n const inputKeys = Object.keys(input as object)\n const allKeys = new Set<string>(inputKeys)\n if (\n slim !== null &&\n slim !== undefined &&\n typeof slim === 'object' &&\n !Array.isArray(slim) &&\n !(slim instanceof Date) &&\n !(slim instanceof RegExp) &&\n !(slim instanceof Map) &&\n !(slim instanceof Set)\n ) {\n for (const k of Object.keys(slim as object)) allKeys.add(k)\n }\n const out: Record<string, unknown> = {}\n let mutated = allKeys.size !== inputKeys.length\n for (const key of allKeys) {\n const orig = (input as Record<string, unknown>)[key]\n const walked = walk(orig, [...segments, key], schema, paths)\n out[key] = walked\n if (walked !== orig) mutated = true\n }\n return mutated ? out : input\n }\n return input\n}\n\n/**\n * Recurse into a schema slim-default subtree, auto-marking every\n * **numeric** primitive leaf encountered. Called from `walk` whenever\n * the user's payload is missing at a path, and from the top-level\n * walker entry point when no defaults are supplied at all. Strings,\n * booleans, and other non-numeric leaves are left unmarked — the\n * library only auto-marks where storage and display diverge, which\n * for slim primitives is exclusively `number` and `bigint`. See the\n * docblock on `walkUnsetSentinels` for the full rationale.\n *\n * Exported so the discriminated-union variant-switch reshape in\n * `create-form-store.ts` can re-mark numeric leaves of the newly\n * activated variant after replacing the union's parent storage.\n */\nexport function walkUnspecified(slim: unknown, segments: Segment[], paths: PathKey[]): unknown {\n if (isPrimitiveOrEmpty(slim)) {\n if (isNumericPrimitive(slim)) {\n paths.push(canonicalizePath(segments).key)\n }\n return slim\n }\n if (\n slim instanceof Date ||\n slim instanceof RegExp ||\n slim instanceof Map ||\n slim instanceof Set ||\n typeof slim === 'function'\n ) {\n return slim\n }\n // Arrays: pass through without recursion. Elements are runtime-added;\n // tuple-shaped fixed arrays opt-in via explicit per-element `unset`.\n if (Array.isArray(slim)) return slim\n if (slim !== null && typeof slim === 'object') {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(slim as object)) {\n out[key] = walkUnspecified((slim as Record<string, unknown>)[key], [...segments, key], paths)\n }\n return out\n }\n return slim\n}\n\n/**\n * Substitute every `unset` sentinel inside `value` with the schema's\n * slim default at its absolute path (rooted at `prefix`), returning\n * the cleaned value plus the absolute paths where substitutions\n * happened.\n *\n * Trust-the-caller cousin of `walkUnsetSentinels`. Differs in two\n * ways tuned for the `setValue(path, value)` runtime boundary:\n *\n * 1. No auto-marking of unspecified primitive leaves. The caller's\n * shape is authoritative — we don't synthesize blanks for keys\n * they didn't supply. (The discriminated-union variant reshape\n * in `create-form-store.ts` handles numeric auto-marks for the\n * activated variant separately.)\n * 2. No schema-only key synthesis at object paths. For Case B\n * whole-union writes (`setValue('cargo', { type: 'oversized', … })`),\n * `schema.getDefaultAtPath(['cargo'])` returns the FIRST union\n * variant's default — synthesizing those keys would smuggle the\n * FIRST variant's leaves into the activated variant. The variant\n * reshape clears them via the matched `getVariantDefault`; we\n * must not put them back.\n *\n * Reference-stable: subtrees with no substitutions return their\n * original input reference, so a watcher on `form.values.<peer>`\n * stays quiet when the consumer's write didn't touch that peer.\n */\nexport function substituteUnsetSentinels<T>(\n value: T,\n prefix: Path,\n schema: AbstractSchema<GenericForm, GenericForm>\n): { cleanedValues: T; paths: PathKey[] } {\n const paths: PathKey[] = []\n const cleaned = substitute(value as unknown, [...prefix], schema, paths)\n return { cleanedValues: cleaned as T, paths }\n}\n\nfunction substitute(\n input: unknown,\n segments: Segment[],\n schema: AbstractSchema<GenericForm, GenericForm>,\n paths: PathKey[]\n): unknown {\n if (isUnset(input)) {\n const slim = schema.getDefaultAtPath(segments)\n if (!isPrimitiveOrEmpty(slim)) {\n // unset misuse at non-primitive leaf — match the existing\n // walker's guardrail: warn once, write the slim default, do\n // NOT mark the offending path.\n warnNonPrimitiveLeaf(segments, slim)\n return slim\n }\n paths.push(canonicalizePath(segments).key)\n return slim\n }\n if (input === undefined || input === null) return input\n if (\n input instanceof Date ||\n input instanceof RegExp ||\n input instanceof Map ||\n input instanceof Set ||\n typeof input === 'function'\n ) {\n return input\n }\n if (Array.isArray(input)) {\n let mutated = false\n const out = new Array(input.length)\n for (let i = 0; i < input.length; i++) {\n const walked = substitute(input[i], [...segments, i], schema, paths)\n out[i] = walked\n if (walked !== input[i]) mutated = true\n }\n return mutated ? out : input\n }\n if (typeof input === 'object') {\n let mutated = false\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(input as object)) {\n const orig = (input as Record<string, unknown>)[key]\n const walked = substitute(orig, [...segments, key], schema, paths)\n out[key] = walked\n if (walked !== orig) mutated = true\n }\n return mutated ? out : input\n }\n return input\n}\n\nfunction isPrimitiveOrEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n const t = typeof value\n return t === 'string' || t === 'number' || t === 'boolean' || t === 'bigint'\n}\n\n/**\n * `true` when `value` is a numeric primitive — the only types where\n * storage and display diverge enough that the runtime needs the\n * `blank` side-channel to tell \"user typed 0\" from \"user supplied\n * nothing.\" Strings (`''` storage = `''` display), booleans (`false`\n * storage = unchecked display), null, and undefined never auto-mark.\n */\nfunction isNumericPrimitive(value: unknown): boolean {\n const t = typeof value\n return t === 'number' || t === 'bigint'\n}\n\nconst warnedNonPrimitivePaths: Set<string> | null = __DEV__ ? new Set<string>() : null\n\nfunction warnNonPrimitiveLeaf(segments: Segment[], slim: unknown): void {\n if (warnedNonPrimitivePaths === null) return\n const dotted = segments.map(String).join('.')\n if (warnedNonPrimitivePaths.has(dotted)) return\n warnedNonPrimitivePaths.add(dotted)\n const slimType = slim === null ? 'null' : slim instanceof Date ? 'Date' : typeof slim\n console.warn(\n `[attaform] \\`unset\\` at \"${dotted || '<root>'}\" is a no-op — ` +\n `unset only works at primitive leaves (string / number / boolean / bigint, ` +\n `plus their optional / nullable variants), got \"${slimType}\". ` +\n `The slim default was written but the path is NOT marked blank. ` +\n `(TypeScript catches this at compile time; this warn covers plain-JS callers.)`\n )\n}\n","import { computed, readonly, type Ref } from 'vue'\nimport { __DEV__ } from './dev'\nimport { canonicalizePath, type Path } from './paths'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Public shape of `form.values` — a callable proxy that drills via\n * dot/bracket OR call dynamically:\n *\n * form.values.email // string (the value)\n * form.values.address.city // string (chained descent)\n * form.values.address // { city, … } — object, drillable further\n * form.values('address.city') // function-call (dynamic / programmatic)\n * form.values(['address', 'city']) // path-array form\n * form.values() // the whole form value (root)\n *\n * Asymmetry against `form.errors` / `form.fields`: containers in\n * `values` ARE useful (they are the structural objects), so they\n * terminate as well as descend. Errors and fields containers are\n * descend-only because their content at a container level is a\n * derivation (e.g. \"any descendant dirty\") rather than a real datum.\n */\nexport type ValuesProxy<F> = ((path?: string | Path) => unknown) & Readonly<F>\n\n/**\n * Build the callable readonly Proxy that powers `form.values`.\n *\n * Reactivity contract:\n *\n * - **Reads track dependencies normally.** The inner\n * `computed(() => readonly(form.value))` recomputes on every\n * whole-form swap (Ref reassignment via `reset()` / whole-form\n * `setValue`) and on every per-key write through Vue's reactive\n * tracking. Each read on the callable proxy delegates to\n * `inner.value.<key>`, which lands inside the consumer's active\n * effect — Vue tracks the dependency at access time.\n *\n * - **Writes are blocked.** Vue's `readonly()` traps `set` / `delete` /\n * `defineProperty` on the inner proxy. The callable wrapper\n * additionally rejects writes at its own boundary. The slim-\n * primitive write gate stays the only path into storage.\n *\n * - **Identity-stable on swap.** Vue's `readonly()` maps targets\n * to proxies by identity. A whole-form swap produces a fresh\n * readonly proxy; the wrapping computed invalidates and\n * re-evaluates. Consumers reading `form.values.<x>` always see\n * the current target's data.\n *\n * - **JSON.stringify works.** The callable proxy is `typeof ===\n * 'function'`, which JSON.stringify normally omits — `toJSON`\n * short-circuits that path and returns the inner readonly proxy\n * so consumers serialise the actual form data, not `undefined`.\n *\n * - **Symbol passthrough.** Vue's reactivity sigils\n * (`Symbol(__v_isRef)`, `Symbol(__v_isReadonly)`, etc.) and\n * iteration symbols resolve against the function target, not\n * the schema-aware branch.\n */\nexport function buildValuesProxy<F extends GenericForm>(form: Ref<F>): ValuesProxy<F> {\n const inner = computed(() => readonly(form.value))\n\n // Arrow-function target: callable (typeof === 'function', `apply`\n // trap fires) but no non-configurable `prototype` to satisfy the\n // ownKeys Proxy invariant.\n const target = (() => {}) as unknown as ValuesProxy<F>\n\n return new Proxy(target, {\n apply(_, __, args: unknown[]): unknown {\n const arg = args[0] as string | Path | undefined\n // No-arg: return the whole form value (the readonly root proxy).\n if (arg === undefined) return inner.value\n // Dynamic path: walk segments through the readonly proxy. Each\n // step reads through the proxy's own get traps so dependency\n // tracking propagates at every level.\n const { segments } = canonicalizePath(arg)\n let cursor: unknown = inner.value\n for (const seg of segments) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string | number, unknown>)[seg]\n }\n return cursor\n },\n get(_, key: string | symbol): unknown {\n // Symbol passthrough — Vue's reactivity sigils resolve here.\n if (typeof key === 'symbol') return Reflect.get(target, key)\n // toJSON: serialise the inner readonly proxy. JSON.stringify\n // checks for toJSON before checking typeof, so the callable\n // proxy serialises to the actual form data.\n if (key === 'toJSON') return () => inner.value\n // Property access: delegate to the readonly proxy. Vue's\n // dependency tracking captures the read inside the consumer's\n // active effect.\n return (inner.value as Record<string, unknown>)[key]\n },\n has(_, key: string | symbol): boolean {\n if (typeof key === 'symbol') return Reflect.has(target, key)\n return Reflect.has(inner.value as object, key)\n },\n ownKeys(): ArrayLike<string | symbol> {\n return Reflect.ownKeys(inner.value as object)\n },\n getOwnPropertyDescriptor(_, key: string | symbol): PropertyDescriptor | undefined {\n const desc = Reflect.getOwnPropertyDescriptor(inner.value as object, key)\n if (desc !== undefined) desc.configurable = true\n return desc\n },\n // Match Vue's `readonly()` semantics: writes warn (in dev) and\n // silently noop (return true). Returning false would throw\n // TypeError in strict-mode consumers, surprising users who\n // assigned through the proxy and expected it to be ignored.\n set(_, key) {\n if (__DEV__) {\n console.warn(\n `[attaform] form.values is read-only — write to \"${String(key)}\" was ignored. Use form.setValue / the directive / field-array helpers instead.`\n )\n }\n return true\n },\n deleteProperty(_, key) {\n if (__DEV__) {\n console.warn(\n `[attaform] form.values is read-only — delete of \"${String(key)}\" was ignored.`\n )\n }\n return true\n },\n defineProperty: () => true,\n })\n}\n","import { computed, reactive, readonly, type Ref } from 'vue'\nimport type {\n FormErrorsSurface,\n FormMeta,\n OnInvalidSubmitPolicy,\n ReactiveValidationStatus,\n RegisterValue,\n UseFormReturnType,\n ValidationError,\n ValidationResponseWithoutValue,\n} from '../types/types-api'\nimport type { DeepPartial, DefaultValuesShape, GenericForm } from '../types/types-core'\nimport { __DEV__ } from './dev'\nimport type { FormStore } from './create-form-store'\nimport { structuralSnapshot } from './diff-apply'\nimport { buildErrorsProxy } from './errors-proxy'\nimport { buildFieldArrayApi } from './field-arrays'\nimport { aggregateErrorsAt, buildFieldStateAccessor } from './field-state-api'\nimport { buildFieldStateProxy } from './field-state-proxy'\nimport type { HistoryModule } from './history'\nimport { getAtPath } from './path-walker'\nimport {\n canonicalizePath,\n ROOT_PATH_KEY,\n segmentsForPathKey,\n type Path,\n type PathKey,\n} from './paths'\nimport { PERSISTENCE_MODULE_KEY, type PersistenceModule } from './persistence'\nimport { enforceSensitiveCheck } from './persistence/sensitive-names'\nimport { buildProcessForm } from './process-form'\nimport { buildRegister } from './register-api'\nimport { isUnset } from './unset'\nimport { substituteUnsetSentinels, walkUnsetSentinels } from './unset-walker'\nimport { buildValuesProxy } from './values-proxy'\n\nexport type BuildFormApiOptions = {\n /** Forwarded to buildProcessForm. See `UseFormConfiguration.onInvalidSubmit`. */\n onInvalidSubmit?: OnInvalidSubmitPolicy\n /**\n * Pre-wired history module for undo/redo. When omitted, the public\n * `undo` / `redo` / `canUndo` / `canRedo` / `historySize` fields\n * are inert no-op stubs — consumers get a consistent API shape\n * without opting into the feature.\n */\n history?: HistoryModule\n}\n\n/**\n * Wrap a Set in a read-only facade. `Object.freeze(new Set(...))` does\n * NOT prevent `add` / `delete` / `clear` mutations on the underlying\n * Set — those methods bypass the frozen state. The Proxy traps the\n * mutating methods and rebinds method/getter access to the underlying\n * Set so internal-slot accesses (e.g. `size`, `has`) keep working.\n */\nfunction readonlySetSnapshot<T>(source: Iterable<T>): ReadonlySet<T> {\n const snapshot = new Set(source)\n return new Proxy(snapshot, {\n get(target, prop) {\n if (prop === 'add' || prop === 'delete' || prop === 'clear') {\n return () => {\n throw new TypeError(`Cannot mutate readonly Set: '${String(prop)}' is not allowed.`)\n }\n }\n // Bind the result to `target` so Set's internal-slot accessors\n // (`size`, `has`, `forEach`, the iterator protocol) receive the\n // underlying Set as `this` instead of the Proxy.\n const value = Reflect.get(target, prop, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n }) as ReadonlySet<T>\n}\n\n/**\n * Build the public form API from a FormStore. Extracted from\n * `useAbstractForm` so that both the top-level form entry (which creates\n * a fresh state) and `injectForm` (which resolves state from an\n * ambient provide/inject) produce identical API shapes without\n * duplicating the wiring.\n *\n * `buildFormApi` does not interact with the registry, consumer ref-counts,\n * or the current Vue instance — those concerns belong to the caller. This\n * function is pure over (FormStore, options) → api.\n */\nexport function buildFormApi<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(\n state: FormStore<Form>,\n formInstanceId: string,\n options: BuildFormApiOptions = {}\n): UseFormReturnType<Form, GetValueFormType> {\n const register = buildRegister(state, formInstanceId) as (\n path: string | Path\n ) => RegisterValue<unknown>\n // Don't set `onInvalidSubmit: undefined` — exactOptionalPropertyTypes\n // treats an explicit-undefined value differently from an omitted\n // property. Only pass the key when the consumer opted in.\n const processOptions =\n options.onInvalidSubmit !== undefined ? { onInvalidSubmit: options.onInvalidSubmit } : {}\n const {\n validate: validateBuilt,\n validateAsync: validateAsyncBuilt,\n handleSubmit,\n } = buildProcessForm(state, formInstanceId, processOptions)\n\n const validate = (pathInput?: string) =>\n validateBuilt(pathInput) as Ref<ReactiveValidationStatus<Form>>\n\n const validateAsync = (pathInput?: string) =>\n validateAsyncBuilt(pathInput) as Promise<ValidationResponseWithoutValue<Form>>\n\n // --- toRef escape hatch — Readonly<Ref<...>> for the rare case\n // a consumer needs ref-shaped interop (external composables that\n // expect a Vue ref, watchers reading a single path). Writes still\n // funnel through `setValue`, never via the ref.\n function pathToRef(pathInput: string): Readonly<Ref<unknown>> {\n const segments = canonicalizePath(pathInput).segments\n return computed(() => getAtPath(state.form.value, segments)) as Readonly<Ref<unknown>>\n }\n\n function setValueImpl(pathOrValue: unknown, maybeValue?: unknown): boolean {\n if (arguments.length === 1) {\n // Whole-form: hand the consumer's callback a STABLE structural\n // snapshot of the form, not the live reactive value. The form\n // store mutates `form.value` in place on commit (so deep-watch\n // dependencies fire only for paths that actually changed), so\n // a callback that closes over `prev` would otherwise see its\n // `prev` reference silently follow the post-commit state. The\n // consumer's RETURN value passes through mergeStructural so any\n // gaps the consumer introduced (partial replacement) are filled\n // from defaults.\n const next =\n typeof pathOrValue === 'function'\n ? (pathOrValue as (prev: unknown) => unknown)(structuralSnapshot(state.form.value))\n : pathOrValue\n // Whole-form `unset` sentinels (consumer wrote `setValue(unset)`\n // or returned `unset` for some leaf in a function form) flow\n // through the walker — every leaf gets translated, the cleaned\n // value lands in storage, and the discovered paths are added to\n // `blankPaths` via direct setValueAtPath calls (the\n // gate hook handles the bookkeeping).\n const walked = walkUnsetSentinels(\n next,\n state.schema as unknown as Parameters<typeof walkUnsetSentinels>[1]\n )\n const ok = state.setValueAtPath([], walked.cleanedValues)\n if (!ok) return false\n // Mark each blank path. `setValueAtPath` was just called\n // with cleaned values, so the gate hook's implicit-unmark would\n // have removed any prior blank entries for the paths\n // we just touched — re-add them now.\n for (const pathKey of walked.paths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n state.setValueAtPath(segments, state.schema.getDefaultAtPath(segments), {\n blank: true,\n })\n }\n return true\n }\n const segments = canonicalizePath(pathOrValue as string | Path).segments\n // `unset` at a specific path: resolve the slim default and route\n // through `setValueAtPath` with `blank: true`. Storage\n // gets the well-typed default; the path is marked for the\n // displayValue / required-empty machinery.\n if (isUnset(maybeValue)) {\n return state.setValueAtPath(segments, state.schema.getDefaultAtPath(segments), {\n blank: true,\n })\n }\n // Path-form callback: when the slot at `segments` is unpopulated,\n // hand the consumer the schema's default at that path instead of\n // `undefined` so `(prev) => prev.first.toUpperCase()` is safe.\n // For populated slots, prev is the live value — and stable: the\n // form store reassigns the changed first-segment of `form.value`\n // on commit (so the OLD subtree, which `prev` may close over, is\n // orphaned but unmutated). Consumers caching `prev` see frozen\n // pre-commit state.\n let resolvedValue: unknown\n if (typeof maybeValue === 'function') {\n const current = state.getValueAtPath(segments)\n const prev = current === undefined ? state.schema.getDefaultAtPath(segments) : current\n resolvedValue = (maybeValue as (prev: unknown) => unknown)(prev)\n // Callback returned `unset` — translate the same way as the\n // direct case above.\n if (isUnset(resolvedValue)) {\n return state.setValueAtPath(segments, state.schema.getDefaultAtPath(segments), {\n blank: true,\n })\n }\n } else {\n resolvedValue = maybeValue\n }\n // Nested-unset pass. The leaf-level cases above (`maybeValue ===\n // unset`, callback returned `unset`) are already done; what\n // remains is values like `{ type: 'oversized', lengthCm: unset, … }`\n // — the homepage REPL's discriminated-union Case B write. Without\n // this scrub, the symbols flow into the slim-primitive gate, fail\n // the kind check at the numeric leaf, and the whole write is\n // rejected — leaving the form on the prior variant.\n //\n // The walker is reference-stable on subtrees with no substitutions,\n // so the common case (no nested unsets) returns the same `resolvedValue`\n // identity and produces an empty `paths` list — no extra writes.\n const walked = substituteUnsetSentinels(\n resolvedValue,\n segments,\n state.schema as unknown as Parameters<typeof substituteUnsetSentinels>[2]\n )\n const ok = state.setValueAtPath(segments, walked.cleanedValues)\n if (!ok) return false\n // Mark each substituted leaf blank. Re-write the slim default\n // explicitly with `blank: true` so the gate hook adds the path\n // to `blankPaths` (the variant reshape's `walkUnspecified` only\n // auto-marks numeric leaves; this loop catches the\n // string / boolean / bigint cases the consumer flagged blank).\n for (const pathKey of walked.paths) {\n const blankSegments = segmentsForPathKey(pathKey)\n if (blankSegments === null) continue\n state.setValueAtPath(blankSegments, state.schema.getDefaultAtPath(blankSegments), {\n blank: true,\n })\n }\n return true\n }\n\n // --- Error store API — leaf-aware drillable callable Proxy ---\n // `form.errors` merges three reactive sources at every leaf path:\n // 1. `schemaErrors` — refinement-class errors written by the\n // validation pipeline (`scheduleFieldValidation`, `handleSubmit`,\n // construction-time seed, hydration).\n // 2. `derivedBlankErrors` — the reactively-derived \"No value supplied\"\n // class. Pure function of `(blankPaths, schema.isRequiredAtPath)`,\n // no writers.\n // 3. `userErrors` — API-injected errors written by `setFieldErrors*`\n // / `parseApiErrors`-fed entries.\n //\n // Iteration order at each leaf is schema → derived-blank → user, so\n // consumers reading `errors.email` see the structural / synthesised\n // errors first and any user-injected entries appended after. Mirrored\n // in `state.getErrorsForPath` and the per-field accessor.\n //\n // Active-path filter: errors whose `err.path` is no longer reachable\n // through the live form value (e.g. the inactive variant of a\n // discriminated union after a switch) are hidden from `form.errors`.\n // The store-side entries STAY — per-field accessors and the\n // `form.meta.errors` aggregate still expose them, so a programmatic\n // consumer reading errors at a specific path can see what's known\n // about it even when the path isn't currently in the active schema.\n //\n // Container paths are descend-only (no terminal). The \"give me every\n // error\" need is served by `form.meta.errors` (flat ValidationError[]).\n const errorsProxy = buildErrorsProxy(state)\n\n function setFieldErrors(errors: ValidationError[]): void {\n state.setAllUserErrors(errors)\n }\n\n function addFieldErrors(errors: ValidationError[]): void {\n state.addUserErrors(errors)\n }\n\n function clearFieldErrors(path?: string | (string | number)[]): void {\n // Pragmatic semantic: \"make the errors at this path go away\" —\n // clears both the schema-owned and user-owned stores. With always-on\n // validation the schema half re-populates on the next mutation if\n // the value is still invalid, so the inconsistency is short-lived\n // and confined to \"before the next keystroke / submit.\" See\n // docs/migration/0.11-to-0.12.md for the rationale.\n if (path === undefined) {\n state.clearSchemaErrors()\n state.clearUserErrors()\n return\n }\n const segments = canonicalizePath(path as string | Path).segments\n state.clearSchemaErrors(segments)\n state.clearUserErrors(segments)\n }\n\n function setFormErrors(\n errors: ReadonlyArray<Partial<ValidationError> & { message: string }>\n ): void {\n // Surgically replace just the form-level (path: []) entry. Going\n // through `setAllUserErrors` / `setFieldErrors` would clobber every\n // field error too — wrong for \"set this top-of-form message\n // without disturbing field validation.\"\n //\n // Caller-provided `path` and `formKey` are intentionally ignored:\n // this API is form-level-only by definition (path is always [])\n // and the form knows its own key. The lenient input shape lets\n // callers pipe `ValidationError[]` (e.g. from `parseApiErrors`)\n // straight in without having to map first.\n if (errors.length === 0) {\n state.userErrors.delete(ROOT_PATH_KEY)\n return\n }\n state.userErrors.set(\n ROOT_PATH_KEY,\n errors.map((e) => ({\n path: [],\n message: e.message,\n formKey: state.formKey,\n code: e.code ?? 'atta:form-error',\n }))\n )\n }\n\n function clearFormErrors(): void {\n state.userErrors.delete(ROOT_PATH_KEY)\n }\n\n // --- Submission lifecycle ---\n const submitting = computed<boolean>(() => state.submitting.value)\n const submitCount = computed<number>(() => state.submitCount.value)\n const submitError = computed<unknown>(() => state.submitError.value)\n\n // --- Validation lifecycle ---\n const validating = computed<boolean>(() => state.activeValidations.value > 0)\n // `valid` is \"we've validated at least once AND no errors AND not\n // currently validating.\" The `firstValidationDone` gate closes the\n // brief flash window at mount time when the slim default-derivation\n // parse strips refinements (`.refine`, `.superRefine`, async\n // validators) and the queued construction-time microtask hasn't\n // run yet. Without it, frame 1 paints the form as \"valid\" before\n // the real verdict arrives. The `!validating.value` guard\n // distinguishes a genuinely-clean form from one in the window\n // between an async refinement starting and resolving (where errors\n // haven't been written yet, but the verdict is pending).\n // Submit-button gates and per-form clean indicators use this.\n const valid = computed<boolean>(\n () =>\n state.firstValidationDone.value &&\n state.schemaErrors.size === 0 &&\n state.userErrors.size === 0 &&\n state.derivedBlankErrors.value.size === 0 &&\n !validating.value\n )\n\n // --- History (undo/redo) ---\n // When the consumer doesn't configure history, fall back to inert\n // stubs so the public API shape stays consistent whether or not\n // the feature is enabled.\n const history = options.history\n const undo = history?.undo ?? (() => false)\n const redo = history?.redo ?? (() => false)\n const canUndo = history?.canUndo ?? computed(() => false)\n const canRedo = history?.canRedo ?? computed(() => false)\n const historySize = history?.historySize ?? computed(() => 0)\n\n // --- Form-level meta aggregate ---\n // `metaErrors` flattens the three reactive error stores into a single\n // ValidationError[]. Unlike `form.errors.<path>` (per-leaf, active-\n // path filtered), this aggregate is UNFILTERED — inactive-variant\n // errors stay in. Consumers who want only addressable errors filter\n // the array themselves.\n //\n // Order is determined by the SET of errors currently present, not by\n // the temporal sequence of validations. Each path is bucketed at its\n // schema-declaration ordinal (`state.ensurePathOrdinal`); buckets sort\n // by ordinal and flatten in order. Within one ordinal slot the\n // per-store iteration order survives — schema → blank → user — so a\n // path with both a schema error and a userErrors entry surfaces both\n // at the same slot in their existing relative order. Resurrected\n // errors return to the slot they originally occupied: clearing\n // `email` then re-breaking it puts `email` back ahead of `password`,\n // not at the end of the aggregate.\n // The form-level error aggregate. Reads through the same shared\n // `aggregateErrorsAt` helper that `form.fields(path).errors` and\n // `form.errors(path)` use (with the empty-prefix path, which\n // collects every active-variant leaf). One source of truth — the\n // three surfaces never drift, and inactive-variant errors stay\n // hidden everywhere by default.\n const metaErrors = computed<readonly ValidationError[]>(() =>\n aggregateErrorsAt(state, [] as Path)\n )\n\n // --- Form-level meta bundle ---\n // Vue auto-unwraps refs that are top-level on a setup return, but not\n // refs nested in a return *object* — those render as their wrapper\n // (always truthy) and silently break bindings like `:disabled`. We\n // work around it by placing the scalars + computed array inside\n // `reactive()`, which unwraps ref values on property access at any\n // depth; `readonly()` layers a runtime write-guard on top.\n //\n // Named `formMeta` locally to avoid shadowing the `state: FormStore<F>`\n // param this function receives; exposed as `meta` on the public return.\n //\n // FormMeta = FieldState<F> at the root + lifecycle (submit / undo /\n // redo / instance identity). The FieldState fields are derived\n // through the shared `getFieldStateAt([])` accessor (memoised, same\n // reference returned by `form.fields()`) so `form.meta.dirty`,\n // `form.fields().dirty`, and `form.fields([]).dirty` all read\n // identical aggregated state.\n const getRootFieldStateAt = buildFieldStateAccessor(state)\n const rootFieldState = getRootFieldStateAt([] as Path)\n const formMeta = readonly(\n reactive({\n // FieldState fields — read through one shared root computed. Each\n // property accesses `rootFieldState.value[X]`, so any descendant\n // change re-evaluates the root computed once (Vue's reactive\n // graph dedupes the dependent re-renders).\n value: computed(() => rootFieldState.value.value),\n original: computed(() => rootFieldState.value.original),\n pristine: computed(() => rootFieldState.value.pristine),\n dirty: computed(() => rootFieldState.value.dirty),\n focused: computed(() => rootFieldState.value.focused),\n blurred: computed(() => rootFieldState.value.blurred),\n touched: computed(() => rootFieldState.value.touched),\n connected: computed(() => rootFieldState.value.connected),\n element: computed(() => rootFieldState.value.element),\n elements: computed(() => rootFieldState.value.elements),\n updatedAt: computed(() => rootFieldState.value.updatedAt),\n // Whole-form validating mirrors the LIFECYCLE counter\n // (`state.activeValidations`) ORed with any per-leaf validation\n // in flight (via `rootFieldState.validating`). A submit-time\n // validate run shows up as activeValidations; per-field\n // debounced validators show up as fieldValidationCounts. Either\n // flips the flag.\n validating: computed(\n () => state.activeValidations.value > 0 || rootFieldState.value.validating\n ),\n // Whole-form valid keeps the original `firstValidationDone`\n // mount gate so the surface doesn't lie about a yet-to-arrive\n // verdict at construction time. The shared `aggregateErrorsAt`\n // ensures `form.meta.errors` and `rootFieldState.errors` match,\n // so `errors.length === 0` here would agree with `valid` —\n // keep the explicit form-level computation for the gate.\n valid,\n errors: metaErrors,\n path: computed(() => rootFieldState.value.path),\n blank: computed(() => rootFieldState.value.blank),\n label: computed(() => rootFieldState.value.label),\n description: computed(() => rootFieldState.value.description),\n placeholder: computed(() => rootFieldState.value.placeholder),\n meta: computed(() => rootFieldState.value.meta),\n // Lifecycle (form-level only — not on FieldState).\n submitting,\n submitCount,\n submitError,\n canUndo,\n canRedo,\n historySize,\n // Per-`useForm()`-call identity. Stable for one mount; new on\n // re-mount; orthogonal to `form.key` (which is the user-supplied\n // shared identifier). Useful for devtools panels disambiguating\n // shared-key instances, telemetry hooks tagging events with\n // \"which mount\", and E2E tests stamping `data-form-id`.\n instanceId: formInstanceId,\n })\n ) as FormMeta<Form>\n\n // --- Persistence handle (cached on FormStore by useAbstractForm\n // when persist: is configured). The persist + clearPersistedDraft\n // APIs below close over this; reset / resetField also poke it. ---\n const persistence = state.modules.get(PERSISTENCE_MODULE_KEY) as PersistenceModule | undefined\n\n // --- Reset ---\n // Reset semantics are \"fresh start across every layer\" — drafts are\n // transient, so a reset that left stale storage behind would surprise\n // on next mount (form would re-hydrate the discarded draft). The\n // opt-in registry is NOT touched: directives are still mounted and\n // the next user keystroke on an opted-in input re-populates the\n // entry naturally.\n const reset = (nextDefaultValues?: DeepPartial<DefaultValuesShape<Form>>): void => {\n if (nextDefaultValues === undefined) {\n state.reset()\n } else {\n // Walk the consumer's overrides for `unset` symbols, replacing\n // them with the schema's slim defaults and capturing the marked\n // paths. The cleaned values land in form storage via state.reset;\n // the marked paths get added back via direct setValueAtPath\n // calls AFTER the reset so the FormStore's own reset (which\n // clears the blank set in the args branch) doesn't\n // wipe them.\n const walked = walkUnsetSentinels(\n nextDefaultValues,\n state.schema as unknown as Parameters<typeof walkUnsetSentinels>[1]\n )\n // After the walker, `cleanedValues` has had every `unset` symbol\n // replaced with the schema's slim default — the result is\n // structurally compatible with `WriteShape<Form>`, so the cast\n // here is safe.\n state.reset(walked.cleanedValues as DeepPartial<unknown> as Parameters<typeof state.reset>[0])\n for (const pathKey of walked.paths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n state.setValueAtPath(segments, state.schema.getDefaultAtPath(segments), {\n blank: true,\n })\n // Mirror the new baseline into originalBlankPaths so the\n // post-reset state is the dirty=false reference.\n state.originalBlankPaths.add(pathKey as PathKey)\n }\n }\n if (persistence !== undefined) {\n // Fire-and-forget — reset is sync from the consumer's POV; the\n // wipe lands a moment later. Errors are absorbed by the adapter\n // contract (best-effort).\n void persistence.clearPersistedDraft().catch(() => undefined)\n }\n }\n\n const resetField = (pathInput: string): void => {\n const segments = canonicalizePath(pathInput).segments\n state.resetField(segments)\n if (persistence !== undefined) {\n void persistence.clearPersistedDraft(segments).catch(() => undefined)\n }\n }\n\n // --- Persistence (imperative APIs) ---\n\n const persist = async (\n pathInput: string | Path,\n options?: { acknowledgeSensitive?: boolean }\n ): Promise<void> => {\n const segments = canonicalizePath(pathInput).segments\n enforceSensitiveCheck(segments, options?.acknowledgeSensitive === true)\n if (persistence === undefined) return // persist: not configured → silent no-op\n await persistence.writePathImmediately(segments)\n }\n\n const clearPersistedDraft = async (pathInput?: string | Path): Promise<void> => {\n if (persistence === undefined) return\n if (pathInput === undefined) {\n await persistence.clearPersistedDraft()\n return\n }\n const segments = canonicalizePath(pathInput).segments\n await persistence.clearPersistedDraft(segments)\n }\n\n // --- Focus / scroll to first error ---\n // Both helpers scope to `formInstanceId` so two `useForm()` callsites\n // sharing a `key` (e.g. sidebar + main mounting the same form) only\n // focus / scroll within their own registered elements.\n const focusFirstError = (options?: { preventScroll?: boolean }): boolean => {\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return false\n target.element.focus(options)\n return true\n }\n\n const scrollToFirstError = (options?: ScrollIntoViewOptions): boolean => {\n const target = state.getFirstErrorElement(formInstanceId)\n if (target === null) return false\n target.element.scrollIntoView(options)\n return true\n }\n\n // --- Field arrays ---\n const fieldArrays = buildFieldArrayApi(state)\n\n // --- Bulk blank introspection ---\n // Read-only view of the form's blank path set. Vue 3.5\n // tracks `.has()` / `for..of` / size accesses on a reactive Set,\n // so the computed below is a lazy, dependency-tracked passthrough.\n // Wrapped in a Proxy that traps mutating methods so consumers can't\n // pollute the snapshot they receive (`Object.freeze` does NOT make\n // a Set readonly — `add` / `delete` / `clear` still work on frozen\n // Sets). Writes still go through `setValue(_, unset)` /\n // `markBlank()` / the directive's input listener.\n const blankPathsView = computed<ReadonlySet<string>>(() => {\n return readonlySetSnapshot(state.blankPaths)\n })\n\n // --- Pinia-style reactive readonly proxy over the form's value ---\n // `valuesProxyComputed.value` is a deeply-readonly Vue proxy. The\n // computed wrapping ensures `state.form.value` reassignments (the\n // `applyFormReplacement` path used by `reset()` and whole-form\n // `setValue`) invalidate the inner readonly proxy and produce a\n // fresh one keyed to the new target. The callable proxy itself is\n // identity-stable — consumers caching `form.values` get a stable\n // reference whose underlying data tracks the live form value.\n const valuesProxy = buildValuesProxy(state.form)\n\n // --- Pinia-style reactive per-field state proxy ---\n // Allocated once per buildFormApi call (one per consumer). Each Proxy\n // node memoizes its descendants and the per-path FieldState\n // computed it reads through, so repeated access to the same path\n // (`form.fields.email` twice) returns the same object — useful\n // for downstream `===` checks and Vue's render diff.\n const fieldStateProxy = buildFieldStateProxy(state)\n\n return {\n handleSubmit,\n // `values` is the callable readonly Proxy. Each `get` trap reads\n // through `inner.value` (a `computed(() => readonly(form.value))`)\n // so reactivity tracking propagates at the call site. Identity-\n // stable across whole-form swaps (the inner readonly proxy\n // re-keys; the outer callable proxy stays the same instance).\n values: valuesProxy as unknown as UseFormReturnType<Form, GetValueFormType>['values'],\n fields: fieldStateProxy as unknown as UseFormReturnType<Form, GetValueFormType>['fields'],\n setValue: setValueImpl as UseFormReturnType<Form, GetValueFormType>['setValue'],\n validate: validate as UseFormReturnType<Form, GetValueFormType>['validate'],\n validateAsync: validateAsync as UseFormReturnType<Form, GetValueFormType>['validateAsync'],\n register: register as UseFormReturnType<Form, GetValueFormType>['register'],\n key: state.formKey,\n errors: errorsProxy as unknown as FormErrorsSurface<Form>,\n toRef: pathToRef as UseFormReturnType<Form, GetValueFormType>['toRef'],\n setFieldErrors,\n addFieldErrors,\n clearFieldErrors,\n setFormErrors,\n clearFormErrors,\n meta: formMeta,\n reset: reset as UseFormReturnType<Form, GetValueFormType>['reset'],\n resetField: resetField as UseFormReturnType<Form, GetValueFormType>['resetField'],\n persist: persist as UseFormReturnType<Form, GetValueFormType>['persist'],\n clearPersistedDraft: clearPersistedDraft as UseFormReturnType<\n Form,\n GetValueFormType\n >['clearPersistedDraft'],\n focusFirstError,\n scrollToFirstError,\n undo,\n redo,\n append: fieldArrays.append as UseFormReturnType<Form, GetValueFormType>['append'],\n prepend: fieldArrays.prepend as UseFormReturnType<Form, GetValueFormType>['prepend'],\n insert: fieldArrays.insert as UseFormReturnType<Form, GetValueFormType>['insert'],\n remove: fieldArrays.remove as UseFormReturnType<Form, GetValueFormType>['remove'],\n swap: fieldArrays.swap as UseFormReturnType<Form, GetValueFormType>['swap'],\n move: fieldArrays.move as UseFormReturnType<Form, GetValueFormType>['move'],\n replace: fieldArrays.replace as UseFormReturnType<Form, GetValueFormType>['replace'],\n blankPaths: blankPathsView,\n }\n}\n","import { computed, markRaw, reactive, ref, watch, type ComputedRef, type Ref } from 'vue'\nimport type {\n AbstractSchema,\n CoercionRegistry,\n FormKey,\n DefaultValuesResponse,\n ValidateOn,\n ValidationError,\n WriteMeta,\n} from '../types/types-api'\nimport type { DeepPartial, GenericForm, WriteShape } from '../types/types-core'\nimport { DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS } from './defaults'\nimport { applyChangedKeys, diffAndApply, structuralSnapshot, type Patch } from './diff-apply'\nimport { AttaformErrorCode } from './error-codes'\nimport {\n canonicalizePath,\n segmentsForPathKey,\n type Path,\n type PathKey,\n type Segment,\n} from './paths'\nimport {\n getAtPath,\n isPlainRecord,\n mergeStructural,\n setAtPath,\n setAtPathWithSchemaFill,\n} from './path-walker'\nimport { __DEV__ } from './dev'\nimport { resolveCoercionIndex, type CoercionIndex } from './schema-coerce'\nimport { isSlimPrimitiveValid } from './slim-primitive-gate'\nimport { walkUnspecified } from './unset-walker'\nimport {\n createPersistOptInRegistry,\n type PersistOptInRegistry,\n} from './persistence/opt-in-registry'\n\n/**\n * Per-form closure state — the single store owned by each `useForm` call.\n * Bundles the form value, the summary record, element references, field\n * state, the meta tracker, and the error stores under one keyed-by-\n * `(formKey, path)` instance so cross-form DOM state cannot collide.\n *\n * This is NOT a singleton. Each call to `useForm` creates its own FormStore\n * instance and holds onto it via closure. The registry provides SSR\n * hydration; otherwise the state is per-component-per-form.\n */\n\n/** Per-path field status. Replaced wholesale (not mutated in place) on every change. */\nexport type FieldRecord = {\n readonly path: Path\n readonly updatedAt: string | null\n readonly connected: boolean\n readonly focused: boolean | null\n readonly blurred: boolean | null\n readonly touched: boolean | null\n}\n\n// Hydration shape guards — defend against rolling deploys / stale cache\n// where the SSR bundle's record shape diverges from the client's. The\n// `as FieldRecord` / `as ValidationError[]` casts in the hydration loop\n// would otherwise silently admit malformed entries; downstream reads of\n// `.touched` / `.code` then crash with \"Cannot read properties of\n// undefined\" far away from the actual cause. Skip the malformed entries\n// and warn once per key in dev so the rolling-deploy diagnosis is loud.\nfunction isHydratedFieldRecord(value: unknown): value is FieldRecord {\n if (typeof value !== 'object' || value === null) return false\n const r = value as Partial<FieldRecord>\n return (\n Array.isArray(r.path) &&\n (typeof r.updatedAt === 'string' || r.updatedAt === null) &&\n typeof r.connected === 'boolean' &&\n (typeof r.focused === 'boolean' || r.focused === null) &&\n (typeof r.blurred === 'boolean' || r.blurred === null) &&\n (typeof r.touched === 'boolean' || r.touched === null)\n )\n}\n\nfunction isHydratedValidationErrorArray(value: unknown): value is ValidationError[] {\n if (!Array.isArray(value)) return false\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null) return false\n const e = entry as Partial<ValidationError>\n if (typeof e.message !== 'string') return false\n if (!Array.isArray(e.path)) return false\n if (typeof e.formKey !== 'string') return false\n if (typeof e.code !== 'string') return false\n }\n return true\n}\n\nfunction warnMalformedHydration(formKey: FormKey, kind: string, rawKey: string): void {\n if (!__DEV__) return\n console.warn(\n `[attaform] hydration: skipping malformed ${kind} entry at key '${rawKey}' on form '${formKey}'. ` +\n `This usually means the SSR bundle is on a different version than the client (rolling deploy / stale cache).`\n )\n}\n\n/** Per-path DOM element tracking. Client-only. */\nexport type ElementRecord = {\n /**\n * Original Path captured at first registration. Stored alongside the\n * elements Set so the DOM-order sort cache can recover the structured\n * Path without round-tripping through `JSON.parse(pathKey)`.\n */\n readonly path: Path\n readonly elements: Set<HTMLElement>\n}\n\n/**\n * Per-path record stored in `originals`. Pairing `segments` with the tracked\n * value means `dirty` and `resetField`'s container loop don't have to\n * `JSON.parse(pathKey)` on every iteration — the canonical Path is already\n * sitting next to the value it belongs to. PathKey still keys the Map (the\n * stable string is the only collision-free identifier), but downstream\n * iteration reads `segments` directly.\n */\nexport type OriginalsRecord = {\n readonly segments: Path\n readonly value: unknown\n}\n\nexport type FormStore<F extends GenericForm, G extends GenericForm = F> = {\n readonly formKey: FormKey\n readonly form: Ref<F>\n readonly fields: Map<PathKey, FieldRecord>\n readonly elements: Map<PathKey, ElementRecord>\n /**\n * Schema-driven errors. Written ONLY by the schema validation pipeline:\n * `scheduleFieldValidation`, `handleSubmit`, the construction-time seed,\n * history restore, and hydration. Cleared by `reset` / `resetField` and by\n * a successful submit. `setFieldErrors*` APIs do NOT touch this Map.\n */\n readonly schemaErrors: Map<PathKey, ValidationError[]>\n /**\n * User-injected errors. Written ONLY by the `setFieldErrors*` API surfaces\n * (and history / hydration replay). Survives schema revalidation and\n * successful submits — the consumer owns its lifetime explicitly.\n */\n readonly userErrors: Map<PathKey, ValidationError[]>\n /**\n * Reactively-derived \"No value supplied\" errors. Pure function of\n * `(blankPaths, schema.isRequiredAtPath)` — no writers, no clears.\n * Membership tracks `blankPaths` automatically: typing a value into\n * a blank required numeric field removes the path from `blankPaths`\n * and the derived error vanishes; clearing the numeric input re-adds\n * the path and the error reappears. The `errors` proxy and\n * `getErrorsForPath` merge this map in alongside `schemaErrors` and\n * `userErrors`, so consumers see the \"this required field is empty\"\n * error the moment it's true — no `validate()` / `handleSubmit`\n * call required. Honors the founding principle that\n * `errors = f(schema, state)`.\n *\n * Most entries flow through this map for `number` / `bigint` leaves\n * (where the side-channel is needed to distinguish \"user typed 0\"\n * from \"user supplied nothing\"). String / boolean leaves only land\n * here when the consumer explicitly opted in via the `unset`\n * sentinel — see `docs/recipes/blank-inputs.md`.\n */\n readonly derivedBlankErrors: ComputedRef<ReadonlyMap<PathKey, ValidationError[]>>\n readonly originals: Map<PathKey, OriginalsRecord>\n /**\n * Reactive set of paths whose displayed state should be EMPTY even\n * though storage holds a real, schema-conformant value (the slim\n * default). It exists exclusively to record **storage / display\n * divergence** — the case where the runtime can't tell \"user typed\n * 0\" from \"user supplied nothing\" by looking at storage alone.\n *\n * The mechanism shines for `number` / `bigint`: storage holds the\n * slim default (`0` / `0n`) but the DOM input shows `''`, so the\n * directive's input listener marks the path here on clear. Strings\n * and booleans don't need it — `''` storage equals `''` display,\n * `false` storage equals unchecked display — so they're never\n * auto-marked. Consumers can still mark any primitive leaf\n * explicitly via the `unset` sentinel (`defaultValues: { x: unset }`,\n * `setValue('x', unset)`, `reset({ x: unset })`); the mark is then\n * a documented signal of consumer intent rather than runtime\n * inference.\n *\n * Reads (`displayValue` computed, `fields.<path>.blank`,\n * `derivedBlankErrors` computed) track via Vue 3.5's reactive Set\n * handlers. Writes happen inside `setValueAtPath` (gate-hook\n * bookkeeping: `blank: true` meta adds the path; any other write\n * removes it) and `reset`.\n *\n * Storage NEVER reflects this set — calculations and reads against\n * `form.value` see the slim default. The set is purely a UI/intent\n * channel that `derivedBlankErrors` consults to surface\n * \"No value supplied\" errors for required schemas.\n *\n * See `docs/recipes/blank-inputs.md` for the conceptual model.\n */\n readonly blankPaths: Set<PathKey>\n /**\n * Snapshot of `blankPaths` captured at construction (and\n * re-captured on `reset(args)`). Used by dirty calculation: a path\n * whose membership differs from the snapshot is dirty even if\n * storage matches the original. Eagerly populated to avoid a \"dirty\n * on first read\" race after construction.\n */\n readonly originalBlankPaths: Set<PathKey>\n readonly schema: AbstractSchema<F, G>\n\n /**\n * Server-side flag, plumbed in from `registry.ssr`. The\n * `register()`-returned `markConnectedOptimistically()` reads this\n * before flipping `connected: true`; on the client it's a no-op so\n * the eventual directive lifecycle remains the source of truth.\n */\n readonly ssr: boolean\n\n // --- submission lifecycle ---\n // Driven by buildProcessForm's handleSubmit wrapper. See use-abstract-form.ts\n // for the public readonly surface. Mutations happen in exactly one place\n // (the submit handler) so there's no \"source of truth\" ambiguity — these\n // refs live on FormStore so a `reset()` can clear them too.\n //\n // `activeSubmissions` is the source of truth for \"is anything in flight\".\n // `submitting` mirrors `activeSubmissions > 0` and is what consumers\n // read; tracking the counter separately means overlapping submissions\n // don't prematurely flip submitting to false when the first completes.\n readonly submitting: Ref<boolean>\n readonly activeSubmissions: Ref<number>\n readonly submitCount: Ref<number>\n readonly submitError: Ref<unknown>\n /**\n * Incremented by every `reset()` call. The submit wrapper captures\n * this at entry and skips writing `submitError` from a catch that\n * fires *after* a reset — otherwise a reset-during-submit would\n * visibly clear `submitError` and then have it reappear when the\n * in-flight promise rejects.\n */\n readonly submissionGeneration: Ref<number>\n /**\n * Counts in-flight validation calls across every `validate()` ref and\n * every `validateAsync(...)` / `handleSubmit` pre-check. `validating`\n * on the public API mirrors `activeValidations.value > 0`. Tracked\n * separately from submissions because a validate-while-submitting\n * (e.g. a debounced field check overlapping a submit) needs to show\n * the union of both surfaces.\n */\n readonly activeValidations: Ref<number>\n /**\n * `true` once the form has completed at least one validation pass\n * — flips when `activeValidations` returns to 0 from any positive\n * value. Until that happens, `meta.valid` and `field.valid` report\n * `false` even when `schemaErrors.size === 0`, because the absence\n * of errors at frame 1 is just \"we haven't checked yet,\" not \"we\n * checked and it's clean.\"\n *\n * This closes the brief flash window for schemas where the slim\n * default-derivation parse strips refinements (`.refine`,\n * `.superRefine`, async validators): the slim parse passes, no\n * construction-time errors land, and the queued microtask hasn't\n * run yet — so without the gate, frame 1 paints the form as\n * \"valid\" before the real verdict arrives a tick later.\n *\n * Initialized to `!strict`: non-strict consumers opt out of the\n * validation pipeline by design, so locking them on\n * `firstValidationDone === false` would defeat the opt-out.\n * Reset is left untouched — the post-reset validation flips it\n * back true on completion, same as the construction-time path.\n */\n readonly firstValidationDone: Ref<boolean>\n /**\n * `true` when the sub-schema rooted at `path` (or any of its\n * descendants) declares async work — composes\n * `schema.getSchemasAtPath(path)` with each candidate's\n * `needsAsyncValidation()`, memoised per canonical path key for\n * the lifetime of the FormStore. Used by `meta.valid` /\n * `field.valid` to skip the `firstValidationDone` gate on subtrees\n * that are fully synchronous: their verdict resolves at construction\n * (or on the next per-field run) without waiting on a microtask, so\n * honouring the form-wide gate would just play dumb about a known\n * answer.\n */\n pathHasAsyncValidation(path: Path): boolean\n /**\n * Per-path counter of in-flight field-level validation runs.\n * `field.validating` on `FieldState` mirrors\n * `(fieldValidationCounts.get(key) ?? 0) > 0`.\n *\n * Incremented at the same point as `activeValidations` inside\n * `scheduleFieldValidation`'s `run` closure (right before the schema\n * call) and decremented in the matching `.finally` — so the per-path\n * bookkeeping is exactly co-extensive with the form-wide counter for\n * the field-scheduled branch. Whole-form `validate()` /\n * `validateAsync()` runs touch `activeValidations` only; they don't\n * have a single field path and so don't contribute here.\n *\n * Counter (not Set) because two runs for the same path can briefly\n * overlap: when an in-flight run is aborted and a new run starts,\n * the new run increments before the aborted run's `.finally`\n * decrements. With `> 0` semantics the field stays \"validating\"\n * across the abort/restart boundary.\n *\n * Reactive Map: Vue 3's `reactive(new Map())` proxy makes `.get()`,\n * `.has()`, and `.size` track per-key, so the FieldState\n * computed only re-runs when the count for ITS key changes.\n */\n readonly fieldValidationCounts: Map<PathKey, number>\n\n // --- form mutations ---\n /**\n * Replace the form value wholesale. Optional `meta` is forwarded to\n * every `onFormChange` listener so they can decide whether THIS write\n * is one they care about — most importantly, the persistence layer\n * only writes when `meta?.persist === true`. Internal callers that\n * don't pass meta default to no-persist.\n */\n applyFormReplacement(next: F, meta?: WriteMeta): void\n /**\n * Set a single path's value. `meta` is forwarded to listeners via\n * `applyFormReplacement` (see above). The directive's input handler\n * computes `meta.persist` from the per-element opt-in registry; other\n * internal call sites pass `meta.persist = hasAnyOptInForPath(path)`.\n * Public `form.setValue` passes no meta.\n *\n * Returns `false` when the slim-primitive gate rejects the write\n * (the value's primitive shape doesn't match the schema's slim\n * shape at the path). The store is unchanged in that case.\n */\n setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean\n getValueAtPath(path: Path): unknown\n\n // --- reset ---\n reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void\n resetField(path: Path): void\n\n // --- errors ---\n // Schema-driven writers. Used by the validation pipeline + handleSubmit.\n setSchemaErrorsForPath(path: Path, errors: ValidationError[]): void\n setAllSchemaErrors(errors: readonly ValidationError[]): void\n clearSchemaErrors(path?: Path): void\n\n // User-driven writers. Used by build-form-api's setFieldErrors* surfaces.\n setAllUserErrors(errors: readonly ValidationError[]): void\n addUserErrors(errors: readonly ValidationError[]): void\n clearUserErrors(path?: Path): void\n\n /**\n * Merged read — returns `[...schemaErrors[path], ...userErrors[path]]`.\n * Schema errors come first (structural validation before business logic),\n * matching the iteration order for `getFirstErrorElement` and the\n * top-level `errors` drillable Proxy.\n */\n getErrorsForPath(path: Path): ValidationError[]\n\n /**\n * Returns a stable schema-declaration ordinal for `key`, assigning a\n * fresh one if the path hasn't been seen before. Drives\n * `form.meta.errors` sort order so the aggregate is a function of the\n * SET of errors currently present (not the temporal order their\n * Map keys were last `set`). Construction-time seed walks every leaf\n * in the schema's slim default; runtime callers (DU variant 2, dynamic\n * array indices, refines targeting cross-field paths) pick up\n * first-encounter ordinals and keep them for the form's lifetime.\n */\n ensurePathOrdinal(key: PathKey): number\n\n // --- DOM ---\n /**\n * Register `element` as a binding for `path`, tagged with the calling\n * `useForm()` instance's `formInstanceId`. The ID is the disambiguator\n * used by `getFirstErrorElement` to scope focus / scroll to elements\n * THIS form instance owns — important when two `useForm()` calls share\n * a `key` (e.g. sidebar + main rendering the same form), since both\n * write into one shared element store.\n */\n registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean\n deregisterElement(path: Path, element: HTMLElement): number\n markFocused(path: Path, focused: boolean): void\n markTouched(path: Path): void\n /**\n * SSR-only optimistic mark: flip `connected: true` on the field\n * record without an actual DOM element. Called by the `vRegisterHint`\n * compile-time transform via `RegisterValue.markConnectedOptimistically()`\n * for every element rendered with `v-register`. Idempotent + no-op on\n * the client (the directive's `created` hook is the authoritative\n * source there).\n */\n markConnectedOptimistically(path: Path): void\n\n // --- derived ---\n /**\n * Leaf-only pristine check. `originals` is populated via\n * `diffAndApply`'s `added` patches, which fire only on primitive\n * leaves — a container path (e.g. `['profile']`) that isn't in\n * `originals` returns `true` here even when a descendant is dirty.\n * Callers that need container semantics should either loop over\n * leaves or walk `originals` manually. The public `getFieldState`\n * surface is typed to accept leaf paths only, so in practice this\n * isn't exposed to consumers.\n */\n isPristineAtPath(path: Path): boolean\n getFieldRecord(path: Path): FieldRecord | undefined\n getOriginalAtPath(path: Path): unknown\n /**\n * Returns the first errored field's first connected, visible DOM\n * element scoped to `formInstanceId` — the target that\n * `focusFirstError` / `scrollToFirstError` act on. \"First\" is\n * VISUAL-first (DOM-tree order via `compareDocumentPosition`), not\n * schema-declaration order, so a field rendered above another in the\n * template focuses first regardless of which one the schema declared\n * earlier. CSS `order:` flexbox/grid reordering is NOT respected\n * (DOM-tree order wins) — documented as a tradeoff against forcing\n * sync layout on every comparison.\n *\n * The `formInstanceId` filter scopes focus to elements registered\n * through THIS form instance. When two `useForm({ key })` calls share\n * a key, both register into the same element store; without the\n * filter, the sidebar form's submit could focus the main form's\n * input. With it, each `useForm()` callsite focuses only its own\n * elements.\n *\n * Returns `null` when every errored path has no currently-attached\n * element registered to this instance (fields behind `v-if=\"false\"`,\n * unmounted components, or a hidden `display:none` parent). Callers\n * get the choice of no-op or a dev-only warning.\n */\n getFirstErrorElement(formInstanceId: string): { path: Path; element: HTMLElement } | null\n\n /**\n * Cancel every in-flight field-level validation run — clears timers\n * for debounced 'change' runs that haven't fired, aborts controllers\n * for runs whose async parse is in flight. Called by `handleSubmit`\n * at entry (submit validation is authoritative) and by `reset()`.\n */\n cancelFieldValidation(): void\n\n /**\n * Kick off (or schedule) a field-level validation run for `path`. Pass\n * `path = []` to cover the whole form; `applySchemaErrorsForSubtree`\n * then wipes every `schemaErrors` entry and replaces them with the\n * adapter's full async response. Used by persistence's post-hydration\n * revalidation and by the construction-time async-refine seed.\n *\n * `immediate: true` skips the debounce window — the runtime kicks off\n * the adapter call on the next microtask. Internal callsites use this\n * for one-shot triggers; the per-keystroke writers pass `false` to\n * coalesce rapid mutations under the configured debounceMs.\n */\n scheduleFieldValidation(path: Path, immediate: boolean): void\n\n /**\n * Subscribe to every `applyFormReplacement`. Fires synchronously\n * after `form.value` has been swapped to `next` and all field /\n * originals bookkeeping has run. Used by persistence + undo/redo\n * to hook the single mutation funnel. The optional `meta` carries\n * the originating call site's intent — the persistence subscription\n * filters on `meta?.persist === true`; subscribers that don't care\n * about meta can ignore the parameter. Returns an unsubscribe\n * function.\n */\n onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void\n\n /**\n * Subscribe to successful submissions. Fires after the consumer's\n * `onSubmit` callback has resolved — not on validation failure,\n * not on callback throw. Used by persistence's `clearOnSubmitSuccess`\n * to drop the stored payload once the form is safely through the\n * server round-trip. Returns an unsubscribe function.\n */\n onSubmitSuccess(listener: () => void): () => void\n\n /**\n * Subscribe to `reset()` calls. Fires AFTER reset has replaced\n * the form and cleared errors + lifecycle, so listeners see the\n * fresh post-reset state. Used by the history module to drop the\n * undo/redo stack on reset. Returns an unsubscribe function.\n */\n onReset(listener: () => void): () => void\n\n /**\n * Internal: notify submit-success subscribers. Called by\n * `handleSubmit` in `process-form.ts` once the user callback has\n * resolved. Consumers shouldn't call this directly.\n */\n emitSubmitSuccess(): void\n\n /**\n * Register a teardown function whose lifetime is bound to the\n * FormStore itself (not a consumer's Vue effect scope). Called by\n * `dispose()` when the last consumer unmounts. Used by persistence /\n * history wiring so their subscribers aren't detached prematurely\n * when only the first consumer unmounts but others remain.\n */\n registerCleanup(fn: () => void): void\n\n /**\n * Register an async drain function. Called by the registry before\n * `dispose()` so async background work — chiefly the persistence\n * layer's debounced storage writes — has a chance to settle without\n * losing the last keystroke. Each registered function is awaited in\n * parallel; failures are swallowed to keep eviction reliable.\n */\n registerDrain(fn: () => Promise<void>): void\n\n /**\n * Drain async work registered via `registerDrain`. Resolves once\n * every registered drain has settled (in parallel). Safe to call\n * repeatedly — registered drains decide their own idempotency.\n */\n awaitPendingWrites(): Promise<void>\n\n /**\n * Cache for per-state modules (history, persistence) that must\n * outlive any single consumer. Subsequent `useForm` / `injectForm`\n * calls for the same key read from this map so the public API shape\n * is identical regardless of mount order. Keyed by a string identifier\n * owned by the caller (e.g. `'history'`).\n */\n readonly modules: Map<string, unknown>\n\n /**\n * Per-element persistence opt-in tracker. Empty by default; the\n * `v-register` directive populates entries on `mount` for each binding\n * that passed `register('foo', { persist: true })` and clears them on\n * `beforeUnmount`. Two SFCs sharing a key share this registry — opt-ins\n * are per-DOM-element, not per-component. Internal to the persistence\n * subsystem; not part of the consumer API surface.\n */\n readonly persistOptIns: PersistOptInRegistry\n\n /**\n * Resolved schema-coercion index — the merged config from\n * `createAttaform({ defaults: { coerce } })` ∪ `useForm({ coerce })`,\n * keyed by `${input}->${output}` for O(1) per-keystroke dispatch.\n * Empty Map when coercion is disabled. Read at `register()` time\n * by `buildCoerceFn` to bake the per-path coerce closure on\n * `RegisterValue.coerce`.\n */\n readonly coerceIndex: CoercionIndex\n\n /**\n * Tear down non-reactive resources owned by this FormStore. Invoked\n * by the registry when the last consumer unmounts. Cancels pending\n * field-validation timers, drops every subscriber, and fires each\n * cleanup hook registered via `registerCleanup`.\n */\n dispose(): void\n}\n\n/**\n * Hydration payload shape accepted by `createFormStore`. When provided, the\n * initial form value comes from here rather than from `schema.getDefaultValues`.\n * Used to replay SSR state on the client; originals are reconstructed from\n * the schema because they're not serialised.\n */\nexport type FormStoreHydration = {\n readonly form: unknown\n /**\n * Schema-driven errors snapshot. Replayed into `schemaErrors` at\n * construction; takes precedence over the construction-time seed.\n */\n readonly schemaErrors: ReadonlyArray<readonly [string, unknown]>\n /**\n * User-injected errors snapshot. Replayed into `userErrors` at\n * construction. Allows server-side `setFieldErrors` /\n * `addFieldErrors` calls (typically fed from `parseApiErrors`) to\n * round-trip through hydration.\n */\n readonly userErrors: ReadonlyArray<readonly [string, unknown]>\n readonly fields: ReadonlyArray<readonly [string, unknown]>\n /**\n * Path keys that were in the form's `blankPaths` set at\n * SSR time. Replayed into the reactive Set on the client so the\n * \"displayed empty\" state survives the round-trip. Optional —\n * pre-v3 envelopes don't carry it; missing means \"no transient-\n * empty paths\".\n */\n readonly blankPaths?: ReadonlyArray<string>\n}\n\nexport type CreateFormStoreOptions<F extends GenericForm, G extends GenericForm = F> = {\n readonly formKey: FormKey\n readonly schema: AbstractSchema<F, G>\n readonly defaultValues?: DeepPartial<WriteShape<F>> | undefined\n readonly strict?: boolean | undefined\n readonly hydration?: FormStoreHydration | undefined\n /**\n * When per-field validation runs. Default `'change'`. See `ValidateOn`.\n * The discriminated union `ValidateOnConfig` lives at the public\n * `useForm` boundary; the internal store accepts the resolved\n * fields directly so the type-narrowing dance stays at the public\n * surface.\n */\n readonly validateOn?: ValidateOn | undefined\n /**\n * Per-field debounce when `validateOn === 'change'`. Default `0`\n * (disabled). Ignored under `'blur'` and `'submit'`.\n */\n readonly debounceMs?: number | undefined\n readonly ssr?: boolean | undefined\n /**\n * Path keys to seed the `blankPaths` set with at construction.\n * Only consulted when `hydration` is undefined — hydration data is\n * authoritative when present (its own `blankPaths` field\n * takes precedence). Used by `useAbstractForm`'s `unset`-symbol pre-\n * pass (commit 7 wires the producer); commit 2 plumbs the channel\n * through with no callers yet.\n */\n readonly initialBlankPaths?: ReadonlyArray<string> | undefined\n /**\n * Whether to remember per-variant typed state across discriminated-\n * union switches. Default `true`. See `UseFormConfiguration.rememberVariants`\n * for full semantics.\n */\n readonly rememberVariants?: boolean | undefined\n /**\n * Schema-driven coercion config. See\n * `UseFormConfiguration.coerce` for the full contract. Resolved\n * once via `resolveCoercionIndex(options.coerce)` and cached on\n * `FormStore.coerceIndex`.\n */\n readonly coerce?: boolean | CoercionRegistry | undefined\n}\n\n/**\n * `true` when the JSON-encoded PathKey identifies a path strictly\n * nested under `parentPath` — i.e. shares every parent segment and\n * has at least one more. Used by the union-variant reshape to clear\n * blank-bookkeeping for paths that no longer exist in the new\n * variant's effective shape.\n */\nfunction isPathKeyUnder(existingKey: PathKey, parentPath: Path): boolean {\n const parsed = segmentsForPathKey(existingKey)\n if (parsed === null) return false\n if (parsed.length <= parentPath.length) return false\n for (let i = 0; i < parentPath.length; i++) {\n if (parsed[i] !== parentPath[i]) return false\n }\n return true\n}\n\nexport function createFormStore<F extends GenericForm, G extends GenericForm = F>(\n options: CreateFormStoreOptions<F, G>\n): FormStore<F, G> {\n const { formKey, schema, defaultValues, strict = true, hydration } = options\n const ssr = options.ssr === true\n const rememberVariants: boolean = options.rememberVariants !== false\n const fieldValidationMode: ValidateOn = options.validateOn ?? 'change'\n const fieldValidationDebounceMs: number =\n options.debounceMs ?? DEFAULT_FIELD_VALIDATION_DEBOUNCE_MS\n\n type FieldValidationEntry = {\n controller: AbortController\n timer: ReturnType<typeof setTimeout> | null\n }\n const fieldValidationState = new Map<PathKey, FieldValidationEntry>()\n\n // Plain Sets (not reactive) — these fire imperative callbacks; no\n // template should ever depend on \"how many listeners are attached\".\n const formChangeListeners = new Set<(next: F, meta?: WriteMeta) => void>()\n const submitSuccessListeners = new Set<() => void>()\n const resetListeners = new Set<() => void>()\n\n // Per-element persistence opt-ins. Constructed up-front so the\n // directive can populate entries before the persistence module wires\n // its subscription (mount order between the directive and\n // wirePersistence isn't guaranteed).\n const persistOptIns = createPersistOptInRegistry()\n\n // Resolve the coercion config to a concrete index ONCE per form.\n // The index is keyed by `${input}->${output}` for O(1) per-keystroke\n // dispatch. `register()` reads it via `state.coerceIndex` to bake\n // path-scoped coerce closures on each `RegisterValue`.\n const coerceIndex: CoercionIndex = resolveCoercionIndex(options.coerce)\n\n // State-scoped teardown hooks. Persistence / history / any other\n // per-state module registers its disposer here so the cleanup is\n // bound to the FormStore's own lifetime (`dispose()` call at\n // registry-eviction) and not the first consumer's effect scope.\n const cleanupHooks: (() => void)[] = []\n const modules = new Map<string, unknown>()\n\n // Schema is ALWAYS consulted: we need the schema-derived originals even\n // when hydrating, so pristine/dirty computation survives SSR round-trip.\n // The form's actual starting value, though, prefers hydration data.\n //\n // Run consumer-supplied `defaultValues` through `mergeStructural` first\n // so partial constraints against tuple shapes (e.g. `coords: [42]` for\n // `z.tuple([_, _, _])`) get padded with position defaults BEFORE the\n // adapter's validate-then-fix loop sees them. Without this, the\n // adapter's wholesale-replace fix-up would lose the consumer's data.\n const completedConstraints =\n defaultValues === undefined\n ? undefined\n : (mergeStructural(schema, [], defaultValues) as DeepPartial<WriteShape<F>>)\n const schemaResponse: DefaultValuesResponse<F> = schema.getDefaultValues({\n useDefaultSchemaValues: true,\n constraints: completedConstraints,\n strict,\n })\n const schemaInitialData = schemaResponse.data\n\n // Clone per instance so two forms sharing a schema (or one form\n // re-mounted from the same schema cache) don't alias the same\n // initial-data object. Without the clone, the in-place merge that\n // `applyFormReplacement` runs on every setValue would reach across\n // the alias and mutate sibling forms' state.\n const initialData: F =\n hydration !== undefined ? (hydration.form as F) : (structuralSnapshot(schemaInitialData) as F)\n\n const form = ref(initialData) as Ref<F>\n\n // Per-path state. `reactive(new Map())` uses Vue's collection handlers —\n // reads of specific keys track those keys only, so a change to one field\n // doesn't invalidate computeds watching another.\n const fields = reactive(new Map<PathKey, FieldRecord>()) as Map<PathKey, FieldRecord>\n const elements = reactive(new Map<PathKey, ElementRecord>()) as Map<PathKey, ElementRecord>\n\n // Per-element form-instance tag. WeakMap so detached elements GC\n // freely — `deregisterElement` does an explicit `.delete()` defensively\n // (in case the element is still strongly referenced elsewhere), but\n // the WeakMap keeps cleanup correct even when the consumer drops the\n // element without going through deregister.\n //\n // Read by `getFirstErrorElement` to scope focus/scroll targets to the\n // calling `useForm()` instance — load-bearing when two forms share a\n // `key` and both register into the same `elements` Map.\n const elementToFormInstance = new WeakMap<HTMLElement, string>()\n\n // Lazy DOM-order sort cache. Holds every registered element flattened\n // across paths, sorted by `compareDocumentPosition` (DOM-tree order).\n // Invalidated to `null` on any register/deregister; rebuilt on next\n // `getFirstErrorElement` read. The cache amortises the sort across\n // multiple submit failures between mutations — a 100-field form with\n // 5 failed submits and no DOM changes pays one O(n log n) sort, not\n // five.\n //\n // Note: `compareDocumentPosition` is DOM-tree order, NOT visual order.\n // CSS `order:` flexbox/grid reorders visually but not in tree, so a\n // child with `order: -1` will sort AFTER its tree-earlier siblings.\n // Real visual order would need `getBoundingClientRect`, which forces\n // sync layout per comparison and breaks under `display: none`. Tree-\n // order is the right tradeoff for a hot path; the 99% case (semantic\n // source-order rendering) works correctly.\n let sortedRegistrationsCache: Array<{ path: Path; element: HTMLElement }> | null = null\n // Errors are split by source so each writer touches exactly one slot.\n // Schema validation owns `schemaErrors`; the `setFieldErrors*` APIs own\n // `userErrors`. The two stores merge on read via `getErrorsForPath` and\n // the top-level `errors` drillable Proxy in build-form-api.\n const schemaErrors = reactive(new Map<PathKey, ValidationError[]>()) as Map<\n PathKey,\n ValidationError[]\n >\n const userErrors = reactive(new Map<PathKey, ValidationError[]>()) as Map<\n PathKey,\n ValidationError[]\n >\n\n // Originals are captured at init and on first appearance of a path; never\n // re-assigned. Not reactive — the set is append-only per form's lifetime.\n // Value is a {segments, value} record so consumers iterating this Map\n // (dirty, resetField's container loop) don't need to `JSON.parse(key)`\n // to recover the canonical Path.\n // Reactive: the dirty computed iterates this map AND accesses\n // `form.value` per entry. With `applyFormReplacement` mutating\n // `form.value` in place (so deep watches fire only for genuinely-\n // changed paths), the form Ref's value-setter dep no longer fires\n // for every write — so a plain Map here would leave the dirty\n // computed stuck on stale deps when new originals are added (e.g.\n // `append` introduces a new array index and seeds an originals\n // entry for it). Wrapping in `reactive(new Map(...))` makes the\n // Map's iteration / set / delete fire Vue's collection deps,\n // picking up exactly the change that prompted the originals\n // mutation.\n const originals = reactive(new Map<PathKey, OriginalsRecord>()) as Map<PathKey, OriginalsRecord>\n\n // Blank bookkeeping. The reactive Set tracks paths whose\n // displayed state should be EMPTY even though storage holds a real\n // slim default; the originals snapshot mirrors construction-time\n // membership so dirty calculation can detect the user's clear /\n // un-clear actions. Hydration takes precedence over `initialBlankPaths`\n // (the SSR snapshot wins when present), matching how the hydrated\n // `form` value overrides the schema's getDefaultValues result.\n const initialTransientList: ReadonlyArray<string> =\n hydration?.blankPaths ?? options.initialBlankPaths ?? []\n const blankPaths = reactive(new Set<PathKey>()) as Set<PathKey>\n const originalBlankPaths = new Set<PathKey>()\n for (const raw of initialTransientList) {\n blankPaths.add(raw as PathKey)\n originalBlankPaths.add(raw as PathKey)\n }\n\n // Per-form variant memory. On a discriminated-union switch the\n // outgoing variant's subtree (deep-cloned) and its blank-path\n // bookkeeping are stashed here keyed by `(unionPath, oldDiscValue)`;\n // on switch-in the entry for the incoming discriminator is\n // restored. Memory is in-memory only (never persisted, never on\n // form.value), and is cleared on `reset()` / whole-form replace /\n // `resetField` of an ancestor of the union path. Disabled when\n // `rememberVariants === false`.\n type VariantSnapshot = {\n readonly value: unknown\n readonly blankPaths: ReadonlyArray<PathKey>\n }\n const variantMemory = new Map<PathKey, Map<unknown, VariantSnapshot>>()\n\n // Schema-declaration ordinal map for `form.meta.errors` sort order.\n // Plain (non-reactive) Map: it's mutated lazily from inside the\n // `metaErrors` computed when an unseen path appears, and a reactive\n // Map would retrigger that computed on every assignment. Plain\n // Map.set is invisible to Vue 3.5's reactivity tracking, so the\n // computed only re-runs when one of the error stores changes — not\n // when we extend the ordinal book during the same pass.\n //\n // Lifetime = FormStore lifetime. Never shrinks: an ordinal is\n // assigned once per path and survives `reset()`, undo/redo, and\n // hydration replay. Clearing then re-introducing an error at the\n // same path returns to the SAME slot, so `meta.errors` doesn't\n // shuffle when the user fixes a field and breaks it again.\n const pathOrdinals = new Map<PathKey, number>()\n let nextOrdinal = 0\n function ensurePathOrdinal(key: PathKey): number {\n let ordinal = pathOrdinals.get(key)\n if (ordinal === undefined) {\n ordinal = nextOrdinal\n pathOrdinals.set(key, ordinal)\n nextOrdinal += 1\n }\n return ordinal\n }\n\n // Reactively-derived blank-required errors. Recomputes whenever\n // `blankPaths` mutates (Vue 3.5 reactive Set handlers track size + has).\n // The schema's `isRequiredAtPath` is referentially stable for a given\n // form (schema is fixed at construction), so it doesn't need to be a\n // dep — only the membership of `blankPaths` drives invalidation.\n const derivedBlankErrors = computed<ReadonlyMap<PathKey, ValidationError[]>>(() => {\n const result = new Map<PathKey, ValidationError[]>()\n if (blankPaths.size === 0) return result\n for (const pathKey of blankPaths) {\n const segments = segmentsForPathKey(pathKey)\n if (segments === null) continue\n if (!schema.isRequiredAtPath(segments)) continue\n result.set(pathKey, [\n {\n message: 'No value supplied',\n path: [...segments],\n formKey,\n code: AttaformErrorCode.NoValueSupplied,\n },\n ])\n }\n return result\n })\n\n // Submission lifecycle refs. Initial values encode \"no submission has\n // happened yet\": not in flight, zero attempts, no captured error.\n // `activeSubmissions` counts concurrent in-flight submissions so the\n // last completion (count → 0) is what flips `submitting` to false,\n // not just the first.\n const submitting = ref(false)\n const activeSubmissions = ref(0)\n const submitCount = ref(0)\n const submitError = ref<unknown>(null)\n const submissionGeneration = ref(0)\n const activeValidations = ref(0)\n // Initial-validity gate. See `FormStore.firstValidationDone` JSDoc.\n // Only ASYNC-validating strict schemas need the gate: sync schemas\n // either surface refinement errors at construction (slim parse\n // catches checks-style issues) or have nothing for the gate to\n // wait on, so locking them at `false` would just deadlock\n // `meta.valid` until the user touches a field. Async schemas are\n // the genuine flash case — slim parse strips the async refine,\n // construction sees no errors, the queued microtask runs a tick\n // later. The watch flips the gate when `activeValidations`\n // returns to 0 from a positive value (i.e. the construction-time\n // queued validation completes).\n const firstValidationDone = ref(!strict || schema.needsAsyncValidation?.() !== true)\n // `watch(source, cb)` only fires when the source CHANGES (no\n // immediate first-invocation), so `prev` is always the value\n // before the transition — typed as `number`, never `undefined`.\n watch(activeValidations, (now, prev) => {\n if (prev > 0 && now === 0) {\n firstValidationDone.value = true\n }\n })\n // Per-path async-need cache. Keyed by canonical PathKey;\n // populated lazily so a form whose consumers only ever ask about\n // a few prefixes doesn't pay for a full schema walk. The cache is\n // safe to grow unboundedly across the FormStore's lifetime — paths\n // are bounded by the schema, and the FormStore itself is GC'd\n // when its last consumer disposes.\n const pathAsyncCache = new Map<PathKey, boolean>()\n function pathHasAsyncValidation(path: Path): boolean {\n const { key } = canonicalizePath(path)\n const cached = pathAsyncCache.get(key)\n if (cached !== undefined) return cached\n // `getSchemasAtPath` returns every candidate sub-schema (DU\n // variants, intersections all surface here). Async work in any\n // candidate means the prefix is \"could be async\" — be\n // conservative and gate. Adapters that don't expose\n // `needsAsyncValidation` are treated as `false`, matching the\n // optional-method contract on AbstractSchema.\n const candidates = schema.getSchemasAtPath(path)\n const hasAsync = candidates.some((sub) => sub.needsAsyncValidation?.() === true)\n pathAsyncCache.set(key, hasAsync)\n return hasAsync\n }\n // Reactive per-path counter for `field.validating`. See JSDoc on\n // `FormStore.fieldValidationCounts` for semantics.\n const fieldValidationCounts: Map<PathKey, number> = reactive(new Map<PathKey, number>())\n function incFieldValidation(key: PathKey): void {\n fieldValidationCounts.set(key, (fieldValidationCounts.get(key) ?? 0) + 1)\n }\n function decFieldValidation(key: PathKey): void {\n const next = (fieldValidationCounts.get(key) ?? 0) - 1\n if (next <= 0) fieldValidationCounts.delete(key)\n else fieldValidationCounts.set(key, next)\n }\n\n // Populate originals by diffing from empty-form to schema-initial. This is\n // always the schema's shape regardless of hydration, so pristine/dirty\n // comparisons are against what the form was supposed to start as.\n // Same walk seeds `pathOrdinals` — `diffAndApply` visits every leaf in\n // declaration order, so the ordinal map gets schema-declaration order\n // for free with no extra traversal.\n const initStamp = new Date().toISOString()\n diffAndApply({}, schemaInitialData, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n originals.set(key, { segments: patch.path, value: patch.newValue })\n ensurePathOrdinal(key)\n })\n\n // Populate fields from either the hydration payload (preserves exact\n // server-side timestamps and flags) or by walking initialData for leaves.\n if (hydration !== undefined) {\n for (const [rawKey, record] of hydration.fields) {\n if (typeof rawKey !== 'string' || !isHydratedFieldRecord(record)) {\n warnMalformedHydration(formKey, 'FieldRecord', String(rawKey))\n continue\n }\n fields.set(rawKey as PathKey, record)\n }\n // Hydration takes precedence over the construction-time seed\n // below: the server already authored whatever error state the\n // client should mirror, including (deliberately) the empty case.\n // Each store replays from its own snapshot so the source-segregation\n // invariant is preserved across SSR round-trip.\n for (const [rawKey, errs] of hydration.schemaErrors) {\n if (typeof rawKey !== 'string' || !isHydratedValidationErrorArray(errs)) {\n warnMalformedHydration(formKey, 'schemaErrors', String(rawKey))\n continue\n }\n schemaErrors.set(rawKey as PathKey, errs)\n }\n for (const [rawKey, errs] of hydration.userErrors) {\n if (typeof rawKey !== 'string' || !isHydratedValidationErrorArray(errs)) {\n warnMalformedHydration(formKey, 'userErrors', String(rawKey))\n continue\n }\n userErrors.set(rawKey as PathKey, errs)\n }\n } else {\n diffAndApply({}, initialData, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n fields.set(key, {\n path: patch.path,\n updatedAt: initStamp,\n connected: false,\n focused: null,\n blurred: null,\n touched: null,\n })\n })\n // No hydration — seed schemaErrors from the construction-time\n // validation result IF the schema rejected the defaults AND the\n // form was constructed in strict mode. Non-strict mode treats\n // default values as \"best-effort,\" so populating errors there\n // would surprise consumers who explicitly opted out via\n // `strict: false`.\n if (strict && !schemaResponse.success) {\n setAllSchemaErrors(schemaResponse.errors)\n }\n }\n\n // Async-only verdicts (e.g. zod's `.refine(async (v) => …)`) can't\n // surface from `getDefaultValues` — that contract is sync, and the\n // adapter degrades to success when the schema's sync parse can't\n // resolve them. When the adapter signals via `needsAsyncValidation`\n // that there's verdicts only an async pass would surface, queue a\n // one-shot full-form validation so the errors land on a later\n // microtask instead of waiting for a user mutation.\n //\n // Two gates:\n // - SKIP on SSR. Microtasks don't get awaited before\n // `renderToString` serialises, so the async chain never\n // completes server-side; firing the schedule would only\n // increment `activeValidations` synchronously and stamp a\n // misleading `validating: true` into the SSR HTML, which\n // the client's hydration pass (taking the hydration branch\n // above) wouldn't reproduce — surface as a hydration\n // mismatch on the `validating…` indicator.\n // - `queueMicrotask` so the increment lands AFTER Vue's\n // synchronous hydration / first render. SSR HTML and the\n // client's first render both observe `activeValidations: 0`;\n // the validation kicks off only on the next microtask, by\n // which point hydration is done and Vue handles the reactive\n // re-render normally.\n //\n // Gated to strict mode AND to schemas that actually need async\n // work — sync-only schemas would otherwise pay a redundant\n // microtask + briefly flash `meta.validating: true` post-mount,\n // misrepresenting \"validation is running\" when nothing is.\n if (!ssr && strict && schema.needsAsyncValidation?.() === true) {\n queueMicrotask(() => scheduleFieldValidation([], true /* immediate */))\n }\n\n function touchFieldRecord(\n pathKey: PathKey,\n path: Path,\n patch: Partial<Omit<FieldRecord, 'path'>>\n ): void {\n const current = fields.get(pathKey)\n fields.set(pathKey, {\n path,\n updatedAt: patch.updatedAt ?? current?.updatedAt ?? null,\n connected: patch.connected ?? current?.connected ?? false,\n focused: patch.focused ?? current?.focused ?? null,\n blurred: patch.blurred ?? current?.blurred ?? null,\n touched: patch.touched ?? current?.touched ?? null,\n })\n }\n\n function applyFormReplacement(next: F, meta?: WriteMeta): void {\n const prev = form.value\n if (Object.is(prev, next)) return\n // Capture the diff before any mutation lands — bookkeeping below\n // needs the per-leaf patches against the OLD shape.\n const now = new Date().toISOString()\n const patches: Patch[] = []\n diffAndApply(prev, next, [], (patch) => {\n patches.push(patch)\n })\n // Mutate `form.value` in place so Vue's deep-reactivity dependencies\n // fire ONLY for paths that genuinely changed. A wholesale\n // `form.value = next` would fire every deep watch (including\n // watches on sub-trees that didn't change), which deadlocks the\n // browser when a watcher reacts by writing back to the form (the\n // canonical \"same as pickup address\" mirror pattern).\n //\n // On a top-level shape mismatch (object → array, etc.) fall back\n // to wholesale replacement — that's the only case where in-place\n // merging can't preserve existing reactive proxies anyway.\n if (!applyChangedKeys(prev, next)) {\n form.value = next\n }\n // Bookkeeping: per-leaf metadata bumped from the captured patches.\n // Runtime-added paths (e.g. `append('posts', {...})` introducing a\n // new array index) must compare against `undefined` for `dirty` —\n // appearing IS a mutation. Only `reset()` rebaselines the originals\n // map; this branch records absence-as-original so the first\n // appearance is correctly seen as dirty.\n for (const patch of patches) {\n const { key } = canonicalizePath(patch.path)\n if (patch.kind === 'added' && !originals.has(key)) {\n originals.set(key, { segments: patch.path, value: undefined })\n }\n touchFieldRecord(key, patch.path, { updatedAt: now })\n }\n // Notify any subscribed modules (persistence, undo/redo) — fire\n // after field bookkeeping so listeners see a fully-updated form.\n // Listener throws are isolated so one misbehaving subscriber\n // can't block the others. `meta` propagates the call-site's\n // intent (e.g. persist: true) to subscribers that filter on it.\n for (const listener of formChangeListeners) {\n try {\n listener(form.value, meta)\n } catch (err) {\n console.error('[attaform] onFormChange threw:', err)\n }\n }\n }\n\n function setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean {\n // Slim-primitive write gate: every leaf in the value must match\n // the schema's slim primitive set at its sub-path. Refinement-level\n // constraints (.email/.min/enum membership/etc.) are NOT enforced\n // here — they're a validation concern. See ./slim-primitive-gate.ts.\n if (!isSlimPrimitiveValid(schema, form, path, value)) {\n return false\n }\n\n // Discriminated-union variant transitions. Writing a discriminator\n // — whether as a leaf write to the discriminator key or as a\n // wholesale write of the union value carrying a different\n // discriminator — changes the schema's effective shape at the\n // union's location. Old-variant keys (e.g. `address` on the email\n // branch) become foreign once `channel: 'sms'` lands; new-variant\n // required keys need their slim defaults populated so the\n // errors-as-state pipeline sees the new shape. Two flavours, both\n // routed through `reshapeUnionVariant`:\n //\n // Case A — leaf write to the discriminator key\n // (`setValue('notify.channel', 'sms')`). Parent path is the\n // union; the new value names a variant directly.\n //\n // Case B — wholesale write of the union itself\n // (`setValue('notify', { channel: 'sms', number: '...' })`).\n // Path is the union; the consumer's value carries the\n // discriminator. Layer the consumer's value on top of the\n // matched variant default so consumer-supplied keys win.\n if (meta?.skipDiscriminatorReshape !== true) {\n // Case A: discriminator-key write.\n if (path.length > 0) {\n const last = path[path.length - 1]\n if (typeof last === 'string') {\n const parentPath = path.slice(0, -1)\n const parentDU = schema.getUnionDiscriminatorAtPath(parentPath)\n if (parentDU?.discriminatorKey === last) {\n const oldValue = getAtPath(form.value, path)\n if (!Object.is(oldValue, value)) {\n const variantDefault = parentDU.getVariantDefault(value)\n if (variantDefault !== undefined) {\n return reshapeUnionVariant(\n parentPath,\n oldValue,\n value,\n variantDefault,\n undefined,\n meta\n )\n }\n }\n }\n }\n }\n // Case B: whole-union write.\n if (isPlainRecord(value)) {\n const selfDU = schema.getUnionDiscriminatorAtPath(path)\n if (selfDU !== undefined) {\n const valueRecord = value as Record<string, unknown>\n const discValue = valueRecord[selfDU.discriminatorKey]\n if (discValue !== undefined) {\n const variantDefault = selfDU.getVariantDefault(discValue)\n if (variantDefault !== undefined && isPlainRecord(variantDefault)) {\n const currentUnionValue = getAtPath(form.value, path)\n const oldDiscValue = isPlainRecord(currentUnionValue)\n ? (currentUnionValue as Record<string, unknown>)[selfDU.discriminatorKey]\n : undefined\n return reshapeUnionVariant(\n path,\n oldDiscValue,\n discValue,\n variantDefault,\n valueRecord,\n meta\n )\n }\n }\n }\n }\n }\n\n // Blank bookkeeping. `blank: true` adds the path\n // to the set (the call site declares \"this write represents an\n // empty intent\"); any other write removes it (the user typed a\n // real value or programmatically reassigned). The mark/unmark sit\n // BEFORE the identity short-circuit so transitions that don't\n // change storage value (e.g. typing 0 over slim-default 0) still\n // update the visual / blank state correctly.\n const pathKey = canonicalizePath(path).key\n if (meta?.blank === true) {\n blankPaths.add(pathKey)\n } else if (blankPaths.has(pathKey)) {\n blankPaths.delete(pathKey)\n }\n\n // Structural-completeness invariant: every write must leave the\n // form satisfying the slim schema. Two ingress points to fill:\n // 1. The target value (consumer may have passed a partial; the\n // schema's element default fills missing keys / array\n // elements via mergeStructural).\n // 2. Intermediate gaps along the path (missing object property,\n // array length below target index — setAtPathWithSchemaFill\n // asks the schema for defaults at each gap site).\n // The common case (write to existing slot with a complete value)\n // hits no schema lookups: mergeStructural short-circuits on\n // ref-equal sub-trees, and the fill walker only queries the\n // schema at gap sites.\n const completedValue = mergeStructural(schema, path, value)\n // Identity short-circuit: if the path's current value already\n // matches what we'd write, skip the replacement. Without this,\n // every keystroke that produces an unchanged trimmed/cast value\n // (e.g. typing a trailing space into a `.trim` input — trim → \"\"\n // → form already at \"\") would still replace `form.value` with a\n // new object identity, triggering Vue to re-render the input and\n // patch the `:value` binding (which compares against the live\n // DOM `el.value`, not the previous vnode prop). The patch\n // overwrites the user's transient whitespace and the spacebar\n // appears broken.\n const currentValue = getAtPath(form.value, path)\n if (Object.is(currentValue, completedValue)) {\n return true\n }\n const nextForm = setAtPathWithSchemaFill(form.value, schema, path, completedValue) as F\n applyFormReplacement(nextForm, meta)\n if (fieldValidationMode === 'change') {\n scheduleFieldValidation(path, false /* debounced */)\n }\n return true\n }\n\n /**\n * Replace the union's parent storage with the activated variant's\n * value, atomically. Two flavours fold into one machine:\n *\n * - `oldDiscValue !== newDiscValue` is a TRUE switch. The\n * outgoing variant's subtree (deep-cloned) and its blank-path\n * bookkeeping under `parentPath` snapshot into `variantMemory`\n * keyed by the union's PathKey. Then memory is consulted for\n * `newDiscValue`: a hit restores the prior typed state; a miss\n * falls back to `variantDefault` (the adapter's slim default\n * for the matching `z.object`).\n * - `oldDiscValue === newDiscValue` is NOT a switch — the\n * reshape was entered via Case B with a partial whole-union\n * write. Skip memory I/O entirely (memory is for switches),\n * just merge `consumerOverrides` on top of `variantDefault`.\n *\n * `consumerOverrides` carries Case B's whole-union value (e.g.\n * `setValue('notify', { channel: 'email', address: 'x' })`).\n * Merge order: memory baseline (or `variantDefault`) first,\n * consumer overrides on top — so a memory-restored `address`\n * survives a partial write that doesn't override it. Case A\n * passes `undefined` for `consumerOverrides`.\n *\n * Direct write — the resolved value IS structurally complete\n * (from the adapter's `deriveDefault` or a matching prior\n * snapshot). Routing through `mergeStructural` would re-add\n * foreign keys from the FIRST variant (the union's\n * `getDefaultAtPath` falls back to the first option), which is\n * exactly what the reshape is meant to clear.\n */\n function reshapeUnionVariant(\n parentPath: Path,\n oldDiscValue: unknown,\n newDiscValue: unknown,\n variantDefault: unknown,\n consumerOverrides: Record<string, unknown> | undefined,\n meta?: WriteMeta\n ): boolean {\n const sameDisc = Object.is(oldDiscValue, newDiscValue)\n const parentKey = canonicalizePath(parentPath).key\n\n // Snapshot OUTGOING. Deep-clone the value: `getAtPath(form.value,\n // parentPath)` returns a Vue reactive proxy into the live tree\n // (form is `ref(initialData)`); after the upcoming `form.value =\n // nextForm` overwrites the union path, the proxy still points to\n // the orphaned raw target. JSON-cycle through the proxy reads to\n // produce a plain-object copy detached from reactivity — form\n // values are JSON-serializable by construction (slim primitive\n // write gate enforces this). `structuredClone` does NOT work\n // here: it rejects Vue's Proxy with `DataCloneError`. Skip when\n // `oldDiscValue` is undefined (initial state had no\n // discriminator) — nothing meaningful to remember.\n let baseline: unknown = variantDefault\n let restoredBlanks: PathKey[] | undefined\n if (rememberVariants && !sameDisc) {\n if (oldDiscValue !== undefined) {\n const currentValue: unknown = JSON.parse(JSON.stringify(getAtPath(form.value, parentPath)))\n const outgoingBlanks: PathKey[] = []\n for (const k of blankPaths) {\n if (isPathKeyUnder(k, parentPath)) outgoingBlanks.push(k)\n }\n let memoryForUnion = variantMemory.get(parentKey)\n if (memoryForUnion === undefined) {\n memoryForUnion = new Map<unknown, VariantSnapshot>()\n variantMemory.set(parentKey, memoryForUnion)\n }\n memoryForUnion.set(oldDiscValue, {\n value: currentValue,\n blankPaths: outgoingBlanks,\n })\n }\n // Look up INCOMING. Stored value is already a deep clone — safe\n // to use directly without re-cloning.\n const memoryForUnion = variantMemory.get(parentKey)\n const restored = memoryForUnion?.get(newDiscValue)\n if (restored !== undefined) {\n baseline = restored.value\n restoredBlanks = [...restored.blankPaths]\n }\n }\n\n // Layer consumer overrides on top of the baseline (Case B).\n // For Case A (`consumerOverrides === undefined`), the baseline\n // is the final value.\n const finalValue: unknown =\n consumerOverrides !== undefined\n ? { ...(baseline as Record<string, unknown>), ...consumerOverrides }\n : baseline\n\n // New blanks: restored from memory (preserves the user's prior\n // explicit blanks + numeric auto-marks together) or recomputed\n // from the resolved `finalValue` (mount-time rule: storage /\n // display divergence for `number` / `bigint` numeric leaves).\n // Compute BEFORE the drop loop so we know which old keys survive\n // — `Set.add` on a deleted-and-re-added key re-inserts at the END\n // of insertion order, which would shift `derivedBlankErrors` (and\n // therefore `form.meta.errors`) on every same-disc reshape even\n // when nothing about the post-reshape shape actually changed.\n let newBlankPaths: PathKey[]\n if (restoredBlanks !== undefined) {\n newBlankPaths = restoredBlanks\n } else {\n newBlankPaths = []\n walkUnspecified(finalValue, [...parentPath], newBlankPaths)\n }\n const survivingBlankKeys = new Set<PathKey>(newBlankPaths)\n // Drop blank-path bookkeeping under `parentPath` — those paths\n // belong to the OLD variant's leaves and don't exist in the new\n // effective shape. Skip keys present in `survivingBlankKeys`: the\n // `add` below is a no-op for an existing Set member (preserves the\n // original insertion slot).\n for (const existingKey of [...blankPaths]) {\n if (isPathKeyUnder(existingKey, parentPath) && !survivingBlankKeys.has(existingKey)) {\n blankPaths.delete(existingKey)\n }\n }\n\n const currentValue = getAtPath(form.value, parentPath)\n if (Object.is(currentValue, finalValue)) {\n // Apply the auto-marks even on no-op (the bookkeeping must\n // catch up even when storage identity matches by coincidence).\n for (const k of newBlankPaths) blankPaths.add(k)\n return true\n }\n const nextForm =\n parentPath.length === 0\n ? (finalValue as F)\n : (setAtPath(form.value, parentPath, finalValue) as F)\n // Sync-validate AHEAD of the form mutation when the schema\n // permits it. Both writes (schemaErrors + form.value) then land\n // in the same Vue reactive batch, so a single render emits the\n // fully-consistent post-reshape state. Without this, the render\n // queued by `applyFormReplacement` runs BEFORE the async\n // validation lands — the active-path filter hides the OLD\n // variant's schemaErrors (their leaves vanished from form.value)\n // and the NEW variant's haven't been written yet, producing a\n // visible `{}` flicker between the two meaningful states.\n //\n // We pass `{ sync: true }` to opt into the adapter's sync arm.\n // The adapter MAY still return a Promise (async refinements,\n // async transforms / pipes — schemas where sync isn't possible);\n // we detect that with `instanceof Promise` and fall through to\n // the existing debounced async pipeline in that case.\n let appliedSync = false\n if (fieldValidationMode === 'change') {\n const syncOrPromise = schema.validateAtPath(finalValue, parentPath, { sync: true })\n if (!(syncOrPromise instanceof Promise)) {\n const reStamped = syncOrPromise.success\n ? []\n : syncOrPromise.errors.map((err) => ({\n ...err,\n path: [...parentPath, ...(err.path as Segment[])],\n }))\n applySchemaErrorsForSubtree(parentPath, reStamped)\n // Cancel any in-flight async validation at this path so a\n // late-arriving result can't clobber the sync write.\n const { key: parentKey } = canonicalizePath(parentPath)\n const prevValidation = fieldValidationState.get(parentKey)\n if (prevValidation !== undefined) {\n if (prevValidation.timer !== null) clearTimeout(prevValidation.timer)\n prevValidation.controller.abort()\n fieldValidationState.delete(parentKey)\n }\n appliedSync = true\n }\n }\n applyFormReplacement(nextForm, meta)\n for (const k of newBlankPaths) blankPaths.add(k)\n if (fieldValidationMode === 'change' && !appliedSync) {\n scheduleFieldValidation(parentPath, false /* debounced */)\n }\n return true\n }\n\n /**\n * Schedule (or kick off immediately) a field-level validation run\n * for `path`. Per-path AbortController semantics: a new schedule\n * cancels any prior in-flight run for the same path, so rapid\n * successive writes don't pile up concurrent validations.\n *\n * The validation reads the current value at `path` from `form.value`\n * AT THE TIME THE TIMER FIRES, not at schedule time. That's the\n * correct semantics for a debounced change trigger: the user's\n * latest-keystroke value is what matters, not whichever value\n * tripped the timer scheduler N milliseconds ago.\n */\n function scheduleFieldValidation(path: Path, immediate: boolean): void {\n if (fieldValidationMode === 'submit') return\n const { key } = canonicalizePath(path)\n const prev = fieldValidationState.get(key)\n if (prev !== undefined) {\n if (prev.timer !== null) clearTimeout(prev.timer)\n prev.controller.abort()\n }\n const controller = new AbortController()\n const fresh: FieldValidationEntry = { controller, timer: null }\n fieldValidationState.set(key, fresh)\n\n const run = () => {\n fresh.timer = null\n if (controller.signal.aborted) return\n const data = getAtPath(form.value, path)\n activeValidations.value += 1\n incFieldValidation(key)\n void Promise.resolve()\n .then(() => schema.validateAtPath(data, path))\n .then((response) => {\n if (controller.signal.aborted) return\n // The adapter emits issue paths relative to the sub-schema it\n // parsed (e.g. `[]` for a leaf string). Re-stamp each error\n // with the absolute field path so the schemaErrors store and\n // `form.errors.<dotted path>` reads agree on the canonical\n // key.\n const reStamped = response.success\n ? []\n : response.errors.map((err) => ({\n ...err,\n path: [...path, ...(err.path as Segment[])],\n }))\n // Apply at the LEAF level: when the scheduled path is a\n // container (e.g. `['notify']` after a DU reshape), the\n // adapter returns multiple issues at distinct leaf paths.\n // Storing them all under the scheduled key would (a) hide\n // them from the canonical-key lookup `form.errors.notify.X`\n // and (b) survive across variant switches as ghost entries\n // because `setSchemaErrorsForPath(parent, [])` only clears\n // the parent's own key, not the descendants written by a\n // previous run.\n applySchemaErrorsForSubtree(path, reStamped)\n })\n .catch(() => {\n // Adapter contract forbids throws — swallow here so a misbehaving\n // custom adapter doesn't surface as an uncaught rejection. The\n // silent drop matches the reactive `validate()` ref's catch\n // branch for adapter-level throws (see process-form.ts).\n })\n .finally(() => {\n activeValidations.value = Math.max(0, activeValidations.value - 1)\n decFieldValidation(key)\n })\n }\n\n // `debounceMs: 0` is the off switch — `setTimeout(fn, 0)` would\n // punt to the next macrotask (browsers also clamp to ~4 ms), and\n // the indirection serves no purpose when the consumer asked for\n // \"no debounce.\" Run synchronously like the `immediate` branch.\n if (immediate || fieldValidationDebounceMs === 0) {\n run()\n } else {\n fresh.timer = setTimeout(run, fieldValidationDebounceMs)\n }\n }\n\n function cancelFieldValidation(): void {\n for (const entry of fieldValidationState.values()) {\n if (entry.timer !== null) clearTimeout(entry.timer)\n entry.controller.abort()\n }\n fieldValidationState.clear()\n }\n\n function onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void {\n formChangeListeners.add(listener)\n return () => {\n formChangeListeners.delete(listener)\n }\n }\n\n function onSubmitSuccess(listener: () => void): () => void {\n submitSuccessListeners.add(listener)\n return () => {\n submitSuccessListeners.delete(listener)\n }\n }\n\n function onReset(listener: () => void): () => void {\n resetListeners.add(listener)\n return () => {\n resetListeners.delete(listener)\n }\n }\n\n function emitSubmitSuccess(): void {\n for (const listener of submitSuccessListeners) {\n try {\n listener()\n } catch (err) {\n console.error('[attaform] onSubmitSuccess threw:', err)\n }\n }\n }\n\n function registerCleanup(fn: () => void): void {\n cleanupHooks.push(fn)\n }\n\n const drainHooks: (() => Promise<void>)[] = []\n\n function registerDrain(fn: () => Promise<void>): void {\n drainHooks.push(fn)\n }\n\n async function awaitPendingWrites(): Promise<void> {\n if (drainHooks.length === 0) return\n // Run drains in parallel — each owns its own retry / failure\n // semantics; we just need to know when all have settled.\n await Promise.allSettled(drainHooks.map((fn) => fn()))\n }\n\n function dispose(): void {\n // Run state-scoped teardowns BEFORE clearing listener sets, so a\n // module that wants to flush something by emitting one last event\n // from its cleanup (unlikely but harmless) doesn't find the\n // listener set already empty. Each hook runs inside try/catch so\n // one misbehaving module can't block the others.\n for (const hook of cleanupHooks) {\n try {\n hook()\n } catch (err) {\n console.error('[attaform] cleanup threw:', err)\n }\n }\n cleanupHooks.length = 0\n drainHooks.length = 0\n modules.clear()\n cancelFieldValidation()\n formChangeListeners.clear()\n submitSuccessListeners.clear()\n resetListeners.clear()\n // Drop opt-ins so a directive that survives FormStore eviction\n // (it shouldn't, but defensive) doesn't keep the registry alive\n // through stale path entries on a disposed store.\n persistOptIns.clear()\n }\n\n function getValueAtPath(path: Path): unknown {\n return getAtPath(form.value, path)\n }\n\n // --- Errors ---\n // Two source-segregated stores: `schemaErrors` (validation-owned) and\n // `userErrors` (API-injected). Writers below are strict — each function\n // touches exactly one Map. The merged view is exposed via\n // `getErrorsForPath` and the top-level `errors` drillable Proxy.\n\n /**\n * Append every entry in `entries` to its target Map at the canonical\n * path key. Existing entries at that key are preserved (merge-append),\n * which matches the documented `addFieldErrors` semantics. Allocates a\n * fresh array per target key to keep the reactive trigger surface\n * obvious — Vue's collection handlers fire on `.set`, not on in-place\n * push.\n */\n function appendErrorsTo(\n map: Map<PathKey, ValidationError[]>,\n entries: readonly ValidationError[]\n ): void {\n for (const err of entries) {\n const { key } = canonicalizePath(err.path as Path)\n const current = map.get(key)\n if (current === undefined) {\n map.set(key, [err])\n } else {\n map.set(key, [...current, err])\n }\n }\n }\n\n /**\n * Clear `map` and rebuild it from `entries`. Two reactive notifications\n * fire (one for `.clear`, one per `.set`), but Vue's microtask batching\n * collapses the burst so subscribers see one re-render. A diff-and-patch\n * variant is a deferred follow-up — profile first.\n */\n function replaceErrorsIn(\n map: Map<PathKey, ValidationError[]>,\n entries: readonly ValidationError[]\n ): void {\n map.clear()\n appendErrorsTo(map, entries)\n }\n\n function clearErrorsIn(map: Map<PathKey, ValidationError[]>, path: Path | undefined): void {\n if (path === undefined) {\n map.clear()\n return\n }\n const { key } = canonicalizePath(path)\n map.delete(key)\n }\n\n // --- Schema writers (validation pipeline + handleSubmit + history/hydration) ---\n\n function setSchemaErrorsForPath(path: Path, entries: ValidationError[]): void {\n const { key } = canonicalizePath(path)\n if (entries.length === 0) {\n schemaErrors.delete(key)\n return\n }\n schemaErrors.set(key, [...entries])\n }\n\n /**\n * Replace the schemaErrors subtree rooted at `path` with `entries`,\n * keying each entry by its OWN absolute path rather than `path`.\n * Used by `scheduleFieldValidation` so a re-validation of a\n * container (e.g. a DU parent after reshape) lands every leaf-keyed\n * issue at its canonical store key — `form.errors.<path>` reads\n * hit, and stale entries from a previous variant don't survive.\n *\n * Insertion-order stability: `Map.set` on an EXISTING key updates the\n * value in place and preserves the slot's position; `Map.delete`\n * followed by `Map.set` re-inserts at the END. `form.meta.errors`\n * iterates this Map in insertion order, so a per-field\n * re-validation that delete-then-sets the scheduled key flips the\n * aggregate's order on every keystroke. The grouped pass below\n * computes the surviving key set FIRST so we only delete keys that\n * genuinely drop out (an old DU-variant leaf that the new pass\n * doesn't write); keys that survive get an in-place `set` that keeps\n * their original slot.\n */\n function applySchemaErrorsForSubtree(path: Path, entries: ValidationError[]): void {\n const { key: parentKey } = canonicalizePath(path)\n // Group by each error's own canonical leaf path FIRST so we know\n // which keys survive this pass. Multiple issues at the same path\n // (e.g. two refinements failing the same leaf) merge into one\n // array — preserves adapter ordering within the leaf.\n const grouped = new Map<PathKey, ValidationError[]>()\n for (const err of entries) {\n const { key } = canonicalizePath(err.path as Path)\n const list = grouped.get(key)\n if (list === undefined) grouped.set(key, [err])\n else list.push(err)\n }\n // Drop the parent key only if not in the new pass.\n if (!grouped.has(parentKey)) schemaErrors.delete(parentKey)\n // Drop stale descendants: existing keys under `path` that the new\n // pass doesn't write (DU-variant leaves that disappeared on\n // reshape). Keys that DO appear in `grouped` stay where they are\n // — the `set` below updates them in place.\n for (const existingKey of [...schemaErrors.keys()]) {\n if (isPathKeyUnder(existingKey, path) && !grouped.has(existingKey)) {\n schemaErrors.delete(existingKey)\n }\n }\n for (const [leafKey, group] of grouped) {\n schemaErrors.set(leafKey, group)\n }\n }\n\n function setAllSchemaErrors(entries: readonly ValidationError[]): void {\n replaceErrorsIn(schemaErrors, entries)\n }\n\n function clearSchemaErrors(path?: Path): void {\n clearErrorsIn(schemaErrors, path)\n }\n\n // --- User writers (setFieldErrors* surfaces + history/hydration) ---\n\n function setAllUserErrors(entries: readonly ValidationError[]): void {\n replaceErrorsIn(userErrors, entries)\n }\n\n function addUserErrors(entries: readonly ValidationError[]): void {\n appendErrorsTo(userErrors, entries)\n }\n\n function clearUserErrors(path?: Path): void {\n clearErrorsIn(userErrors, path)\n }\n\n // --- Merged read ---\n\n function getErrorsForPath(path: Path): ValidationError[] {\n const { key } = canonicalizePath(path)\n const schemaForKey = schemaErrors.get(key)\n const userForKey = userErrors.get(key)\n const blankForKey = derivedBlankErrors.value.get(key)\n if (schemaForKey === undefined && userForKey === undefined && blankForKey === undefined) {\n return []\n }\n const result: ValidationError[] = []\n if (schemaForKey !== undefined) result.push(...schemaForKey)\n if (blankForKey !== undefined) result.push(...blankForKey)\n if (userForKey !== undefined) result.push(...userForKey)\n return result\n }\n\n // --- DOM ---\n\n function registerElement(path: Path, element: HTMLElement, formInstanceId: string): boolean {\n const { key } = canonicalizePath(path)\n const record = elements.get(key)\n // `markRaw` keeps HTMLElement out of Vue's auto-proxy machinery\n // (DOM nodes have circular refs and external state that fight\n // reactivity, and consumers comparing `===` against the original\n // ref expect to get back what they registered). The Set itself\n // is reactive so add/delete on an existing record fires\n // FieldState's `element` / `elements` accessors.\n const raw = markRaw(element)\n if (record === undefined) {\n elements.set(key, { path, elements: reactive(new Set([raw])) })\n } else {\n if (record.elements.has(raw)) return false\n record.elements.add(raw)\n }\n elementToFormInstance.set(element, formInstanceId)\n sortedRegistrationsCache = null\n touchFieldRecord(key, path, { connected: true })\n return true\n }\n\n function deregisterElement(path: Path, element: HTMLElement): number {\n const { key } = canonicalizePath(path)\n const record = elements.get(key)\n if (record === undefined) return 0\n const removed = record.elements.delete(element)\n if (removed) {\n elementToFormInstance.delete(element)\n sortedRegistrationsCache = null\n }\n const remaining = record.elements.size\n if (remaining === 0) {\n elements.delete(key)\n touchFieldRecord(key, path, { connected: false })\n }\n return remaining\n }\n\n function markConnectedOptimistically(path: Path): void {\n // Client-side: the directive's `created` / `beforeUnmount` hooks are\n // authoritative for `connected`, so this is a no-op there. SSR is\n // the only environment where we can't observe the DOM and need an\n // upfront hint that the field WILL be wired up after hydration.\n if (!ssr) return\n const { key } = canonicalizePath(path)\n const current = fields.get(key)\n if (current?.connected === true) return\n touchFieldRecord(key, path, { connected: true })\n }\n\n function markFocused(path: Path, focused: boolean): void {\n const { key } = canonicalizePath(path)\n touchFieldRecord(key, path, {\n focused,\n blurred: !focused,\n // `touched` flips to true on blur and stays true thereafter; while\n // a field is currently focused we keep whatever value it held.\n touched: focused ? (fields.get(key)?.touched ?? null) : true,\n })\n // On blur (focused → false), `validateOn: 'blur'` fires an\n // immediate (no-debounce) validation for this path. Ignored for\n // change/submit modes so behaviour matches the declared config.\n if (!focused && fieldValidationMode === 'blur') {\n scheduleFieldValidation(path, true /* immediate */)\n }\n }\n\n function markTouched(path: Path): void {\n const { key } = canonicalizePath(path)\n touchFieldRecord(key, path, { touched: true })\n }\n\n // --- Reset ---\n\n function reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void {\n // Fall back to construction-time `defaultValues` when the caller\n // doesn't provide a fresh override. Otherwise `reset()` produces\n // schema-only defaults — losing the consumer's initial state from\n // `useForm({ defaultValues: ... })`. The structural-completeness\n // invariant covers post-write correctness; preserving construction\n // defaults across reset is a separate semantic the consumer expects.\n const next = schema.getDefaultValues({\n useDefaultSchemaValues: true,\n constraints: nextDefaultValues ?? defaultValues,\n strict,\n }).data\n // Replace form in one shot — applyFormReplacement will emit diffAndApply\n // patches and touch field records for every changed leaf.\n applyFormReplacement(next)\n // Rebuild originals from the new baseline. The set becomes the\n // post-reset pristine reference — a subsequent dirty comparison\n // returns false until the consumer mutates again.\n originals.clear()\n diffAndApply({}, next, [], (patch) => {\n if (patch.kind !== 'added') return\n const { key } = canonicalizePath(patch.path)\n originals.set(key, { segments: patch.path, value: patch.newValue })\n })\n // Blank: with `nextDefaultValues` provided, both sets\n // adopt the new baseline (commit 7 plugs the `unset`-symbol walker\n // into this branch — for now the new defaults can't carry unset\n // symbols at the type level, so the post-reset baseline is empty).\n // With no args, restore `blankPaths` from the snapshot so\n // construction-time membership returns; originalBlankPaths is\n // preserved (the snapshot encodes the consumer's last declared\n // baseline, which `reset()` should honour).\n if (nextDefaultValues !== undefined) {\n blankPaths.clear()\n originalBlankPaths.clear()\n } else {\n blankPaths.clear()\n for (const key of originalBlankPaths) {\n blankPaths.add(key)\n }\n }\n // Drop every recorded error — the form is a fresh surface again.\n // Both stores clear: reset is \"fresh start\" semantics, so user-injected\n // errors are not preserved across a reset (different from submit-success,\n // which preserves them).\n schemaErrors.clear()\n userErrors.clear()\n // Blow away touched/focused/blurred per field. connected stays as-is\n // (the DOM elements haven't detached — that's a separate concern from\n // form state) and updatedAt stamps to now.\n const now = new Date().toISOString()\n for (const [pathKey, record] of fields) {\n fields.set(pathKey, {\n path: record.path,\n updatedAt: now,\n connected: record.connected,\n focused: null,\n blurred: null,\n touched: null,\n })\n }\n // Clear submission lifecycle so a reset surface reports \"nothing has\n // been submitted yet\" rather than holding on to the prior run's\n // count. The generation counter is bumped first so any in-flight\n // submission's catch block knows its error write would land on the\n // post-reset state and skips it. `activeSubmissions` is zeroed\n // unconditionally — the finally-block's Math.max clamps the\n // decrement at zero, and `submitting` stays false afterwards\n // because the clamped value never exceeds zero.\n submissionGeneration.value += 1\n submitting.value = false\n activeSubmissions.value = 0\n submitCount.value = 0\n submitError.value = null\n // Drop any pending field-validation timers / in-flight runs. Writes\n // that reached the controller-aborted branch resolve to a no-op, so\n // the error store stays clean after the reset clears it above.\n cancelFieldValidation()\n // Variant memory is UX state — a fresh start drops the per-variant\n // typed-data cache too. Without this, a post-reset switch would\n // surface stale variant values from before the reset.\n variantMemory.clear()\n // Notify subscribers (history module clears its stack, persistence\n // sees the reset via onFormChange already). Listener throws are\n // isolated so one bad subscriber can't block the others.\n for (const listener of resetListeners) {\n try {\n listener()\n } catch (err) {\n console.error('[attaform] onReset threw:', err)\n }\n }\n }\n\n function resetField(path: Path): void {\n const { key: targetKey, segments: targetSegments } = canonicalizePath(path)\n\n // Variant memory: drop any union memory whose path equals or sits\n // under `targetSegments`. Memory under the reset subtree is\n // semantically \"user's prior typed state at a discriminator that\n // no longer corresponds to anything live\"; preserving it would\n // surface stale variants on a future switch. Memory ABOVE the\n // reset subtree (e.g. union at ['notify'] for resetField('notify.address'))\n // is intentionally preserved — the snapshot self-corrects on the\n // next switch-out.\n for (const memKey of [...variantMemory.keys()]) {\n const memSegments = segmentsForPathKey(memKey)\n if (memSegments === null) continue\n if (isPathPrefix(targetSegments, memSegments)) {\n variantMemory.delete(memKey)\n }\n }\n\n // Leaf shortcut: direct originals hit means one setValueAtPath does it.\n const leafEntry = originals.get(targetKey)\n if (leafEntry !== undefined) {\n const wrote = setValueAtPath(targetSegments, leafEntry.value)\n if (!wrote) {\n // Originals come from the construction-time pipeline, which\n // guarantees primitive-correctness. A rejected reset write\n // signals an invariant violation upstream.\n console.error(\n `[attaform] resetField: leaf write rejected for path '${targetKey}' — ` +\n `originals contain a value that doesn't satisfy the slim primitive shape. ` +\n `This is a bug in the construction pipeline.`\n )\n }\n schemaErrors.delete(targetKey)\n userErrors.delete(targetKey)\n clearFieldRecordFlags(targetKey)\n return\n }\n\n // Container case — reconstruct the subtree by walking originals for\n // every leaf whose path is a descendant of `targetSegments`. We assemble\n // the subtree first, then apply it in one setValueAtPath so diffAndApply\n // sees a single coherent replacement (rather than N mutations).\n //\n // The iteration reads `entry.segments` directly; the alternative\n // (JSON.parse on the Map key) both allocates and pays a parse cost per\n // entry even on cold paths.\n let subtree: unknown = undefined\n let anyMatch = false\n for (const [, entry] of originals) {\n const leafSegments = entry.segments\n if (!isPathPrefix(targetSegments, leafSegments)) continue\n if (leafSegments.length === targetSegments.length) continue // covered by the leaf shortcut above\n anyMatch = true\n const relative = leafSegments.slice(targetSegments.length)\n if (subtree === undefined) {\n // Seed root container type from the first relative segment. Numeric\n // index → array; string key → plain object. setAtPath will stay\n // consistent with that choice for the rest of the walk.\n subtree = typeof relative[0] === 'number' ? [] : {}\n }\n subtree = setAtPath(subtree, relative, entry.value)\n }\n if (!anyMatch) return // nothing tracked under this prefix; no-op\n\n const wroteSubtree = setValueAtPath(targetSegments, subtree)\n if (!wroteSubtree) {\n console.error(\n `[attaform] resetField: subtree write rejected at path '${targetKey}' — ` +\n `originals contain values that don't satisfy the slim primitive shape. ` +\n `This is a bug in the construction pipeline.`\n )\n }\n\n // Clear errors and reset field-record flags for the target + every\n // descendant. Segments come from the stored records (each ValidationError\n // carries its own `path`, each FieldRecord carries `path`), so neither\n // loop has to `JSON.parse` the Map key. Both error stores walk in\n // parallel — resetField is \"fresh start at this subtree\" semantics, so\n // user-injected errors under the prefix go too.\n deleteErrorsUnderPrefix(schemaErrors, targetSegments)\n deleteErrorsUnderPrefix(userErrors, targetSegments)\n for (const [fieldKey, record] of Array.from(fields.entries())) {\n if (isPathPrefix(targetSegments, record.path)) clearFieldRecordFlags(fieldKey)\n }\n }\n\n function deleteErrorsUnderPrefix(\n map: Map<PathKey, ValidationError[]>,\n prefix: readonly Segment[]\n ): void {\n for (const [errorKey, errs] of Array.from(map.entries())) {\n const first = errs[0]\n if (first === undefined) continue\n if (isPathPrefix(prefix, first.path as readonly Segment[])) {\n map.delete(errorKey)\n }\n }\n }\n\n function clearFieldRecordFlags(pathKey: PathKey): void {\n const record = fields.get(pathKey)\n if (record === undefined) return\n fields.set(pathKey, {\n path: record.path,\n updatedAt: new Date().toISOString(),\n connected: record.connected,\n focused: null,\n blurred: null,\n touched: null,\n })\n }\n\n /**\n * True iff `prefix` is a path-prefix of `candidate`. Equal arrays count as\n * a prefix (every array is a prefix of itself). Segment equality is strict\n * `===` — `'0'` and `0` are distinct here even though canonicalizePath\n * normalises them upstream; both paths always come from the same\n * canonicalisation so the check holds.\n */\n function isPathPrefix(prefix: readonly Segment[], candidate: readonly Segment[]): boolean {\n if (prefix.length > candidate.length) return false\n for (let i = 0; i < prefix.length; i++) {\n if (prefix[i] !== candidate[i]) return false\n }\n return true\n }\n\n // --- Derived ---\n\n function isPristineAtPath(path: Path): boolean {\n const { key, segments } = canonicalizePath(path)\n // Storage match is necessary but not sufficient: a primitive leaf\n // toggled between \"displayed empty\" (blank + slim default)\n // and \"explicitly the slim default\" carries the same storage value\n // but differs visually. Compare both surfaces against the originals\n // snapshot so the blank contract dirties when membership\n // diverges.\n if (blankPaths.has(key) !== originalBlankPaths.has(key)) return false\n const entry = originals.get(key)\n if (entry === undefined) return true\n return Object.is(getAtPath(form.value, segments), entry.value)\n }\n\n function getFieldRecord(path: Path): FieldRecord | undefined {\n const { key } = canonicalizePath(path)\n return fields.get(key)\n }\n\n function getOriginalAtPath(path: Path): unknown {\n const { key } = canonicalizePath(path)\n return originals.get(key)?.value\n }\n\n function getFirstErrorElement(\n formInstanceId: string\n ): { path: Path; element: HTMLElement } | null {\n // Single-pass DOM-order walk over every registered element. The\n // sort cache is rebuilt lazily on the first read after a register/\n // deregister; subsequent calls amortise to O(n) until the next\n // mutation.\n sortedRegistrationsCache ??= rebuildSortedRegistrations()\n\n for (const entry of sortedRegistrationsCache) {\n // Scope to this form instance — when two `useForm()` calls share\n // a key, both write into `elements`; this filter keeps each\n // form's submit from focusing the other's input.\n if (elementToFormInstance.get(entry.element) !== formInstanceId) continue\n\n // `el.isConnected` covers \"component was unmounted, element\n // removed from DOM\" cases that lag the FieldRecord.connected\n // flag. `el.offsetParent === null` catches `display:none` and\n // its ancestor chain — the browser won't focus or scroll to a\n // hidden element anyway, so we keep walking.\n if (!entry.element.isConnected) continue\n if (entry.element.offsetParent === null) continue\n\n const { key } = canonicalizePath(entry.path)\n const hasSchemaErr = (schemaErrors.get(key)?.length ?? 0) > 0\n const hasUserErr = (userErrors.get(key)?.length ?? 0) > 0\n if (!hasSchemaErr && !hasUserErr) continue\n\n return { path: entry.path, element: entry.element }\n }\n return null\n }\n\n function rebuildSortedRegistrations(): Array<{ path: Path; element: HTMLElement }> {\n const flat: Array<{ path: Path; element: HTMLElement }> = []\n for (const [, record] of elements) {\n for (const el of record.elements) flat.push({ path: record.path, element: el })\n }\n // `compareDocumentPosition` returns a bitmask. The\n // `DOCUMENT_POSITION_FOLLOWING` bit (0x04) is set when the argument\n // node FOLLOWS the receiver in document order, which means the\n // receiver comes first → return -1 to keep `a` before `b`.\n flat.sort((a, b) =>\n a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1\n )\n return flat\n }\n\n return {\n formKey,\n form,\n fields,\n elements,\n schemaErrors,\n userErrors,\n derivedBlankErrors,\n originals,\n schema,\n ssr,\n submitting,\n activeSubmissions,\n submitCount,\n submitError,\n submissionGeneration,\n activeValidations,\n firstValidationDone,\n pathHasAsyncValidation,\n fieldValidationCounts,\n\n applyFormReplacement,\n setValueAtPath,\n getValueAtPath,\n\n reset,\n resetField,\n\n setSchemaErrorsForPath,\n setAllSchemaErrors,\n clearSchemaErrors,\n setAllUserErrors,\n addUserErrors,\n clearUserErrors,\n getErrorsForPath,\n ensurePathOrdinal,\n\n registerElement,\n deregisterElement,\n markFocused,\n markTouched,\n markConnectedOptimistically,\n\n isPristineAtPath,\n getFieldRecord,\n getOriginalAtPath,\n getFirstErrorElement,\n cancelFieldValidation,\n scheduleFieldValidation,\n onFormChange,\n onSubmitSuccess,\n onReset,\n emitSubmitSuccess,\n registerCleanup,\n registerDrain,\n awaitPendingWrites,\n modules,\n persistOptIns,\n coerceIndex,\n blankPaths,\n originalBlankPaths,\n dispose,\n }\n}\n\nexport type { Path, PathKey, Segment }\n","import type { AbstractSchema, FormKey } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\n\n/**\n * Accept schema as either a direct value or a factory function `(key) => schema`.\n * The factory form is documented but rarely used — it exists for schemas that\n * want to embed the formKey into their identity.\n */\nexport function getComputedSchema<F extends GenericForm, GetValueFormType>(\n formKey: FormKey,\n schemaOrCallback:\n | AbstractSchema<F, GetValueFormType>\n | ((formKey: FormKey) => AbstractSchema<F, GetValueFormType>)\n): AbstractSchema<F, GetValueFormType> {\n if (typeof schemaOrCallback === 'function') return schemaOrCallback(formKey)\n return schemaOrCallback\n}\n","import { computed, shallowRef, type ComputedRef } from 'vue'\nimport type { HistoryConfig, ValidationError } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport type { FormStore } from './create-form-store'\nimport { DEFAULT_HISTORY_MAX_SNAPSHOTS } from './defaults'\nimport { structuralSnapshot } from './diff-apply'\nimport type { PathKey } from './paths'\n\n/**\n * Bounded undo/redo snapshot stack for a FormStore. Subscribes to\n * `onFormChange` to push a snapshot on every mutation; `undo` /\n * `redo` restore via `applyFormReplacement` plus the schema + user\n * error writers. `onReset` clears both stacks and seeds a fresh baseline.\n *\n * Snapshots include:\n * - `form` — the whole form value, captured by reference. Vue's\n * form ref is replaced wholesale on every mutation, so the\n * snapshot reference is stable: old references don't mutate.\n * - `blankPaths` — set membership at capture time. A numeric field\n * can be in two visually-distinct states with the same storage\n * value (`0` typed vs `0` cleared); the blank set is what\n * distinguishes them. Replaying form alone strands a cleared\n * field on the screen as `0`.\n * - `schemaErrors` + `userErrors` — shallow-cloned Map entries from\n * each source-segregated store. Captured separately so undo\n * preserves the lifecycle distinction (schema errors are validation\n * output; user errors are consumer-owned).\n *\n * Field record state (touched / focused / blurred / connected) is\n * deliberately NOT snapshotted. Those flags represent UI\n * interaction history and shouldn't rewind when the user hits\n * undo — a field that was touched stays touched.\n */\n\nexport type HistorySnapshot<F> = {\n readonly form: F\n readonly blankPaths: ReadonlyArray<PathKey>\n readonly schemaErrors: ReadonlyArray<readonly [PathKey, ValidationError[]]>\n readonly userErrors: ReadonlyArray<readonly [PathKey, ValidationError[]]>\n}\n\nexport type HistoryModule = {\n undo(): boolean\n redo(): boolean\n canUndo: Readonly<ComputedRef<boolean>>\n canRedo: Readonly<ComputedRef<boolean>>\n historySize: Readonly<ComputedRef<number>>\n dispose(): void\n}\n\nexport function createHistoryModule<F extends GenericForm>(\n state: FormStore<F>,\n config: HistoryConfig\n): HistoryModule {\n const max =\n typeof config === 'object'\n ? (config.max ?? DEFAULT_HISTORY_MAX_SNAPSHOTS)\n : DEFAULT_HISTORY_MAX_SNAPSHOTS\n\n // undoStack[-1] is the CURRENT state. undo() pops that onto redo\n // and restores undoStack[-2]. redoStack[-1] is the next-available\n // redo target. This layout keeps `canUndo = undoStack.length > 1`\n // and `canRedo = redoStack.length > 0` trivially.\n // shallowRef avoids Vue's UnwrapRef recursion: the stacks are\n // replaced wholesale on every mutation (spread into a new array),\n // so deep reactivity would only add overhead and produce weird\n // typing around `HistorySnapshot<F>` (UnwrapRef<F> !== F for\n // generic constraints).\n const undoStack = shallowRef<HistorySnapshot<F>[]>([])\n const redoStack = shallowRef<HistorySnapshot<F>[]>([])\n\n // When `undo()` / `redo()` calls `applyFormReplacement`, the\n // resulting `onFormChange` must NOT push a new snapshot (that\n // would duplicate the restored state and break the stack\n // ordering). This flag suppresses the next change event.\n let suppressNext = false\n\n function captureSnapshot(): HistorySnapshot<F> {\n // Clone `form.value` so the snapshot is frozen at this moment.\n // `applyFormReplacement` mutates `form.value` in place on every\n // setValue (so deep-watch dependencies fire only for paths that\n // genuinely changed); without the clone, every entry on the\n // undo stack would alias the live form ref and silently follow\n // subsequent mutations.\n //\n // Vue's Ref<F> unwraps via UnwrapRef<F>; at runtime this is just F\n // for all plain object shapes, but the compile-time types differ.\n // Cast through unknown to reassure TS the snapshot shape matches\n // the generic parameter the caller bound.\n return {\n form: structuralSnapshot(state.form.value) as unknown as F,\n blankPaths: [...state.blankPaths],\n schemaErrors: [...state.schemaErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n userErrors: [...state.userErrors.entries()].map(([k, v]) => [k, [...v]] as const),\n }\n }\n\n function pushSnapshot(snap: HistorySnapshot<F>): void {\n const next = [...undoStack.value, snap]\n // Trim FIFO so the OLDEST snapshot is evicted when the stack\n // exceeds max. The user's most recent history is the one worth\n // keeping.\n undoStack.value = next.length > max ? next.slice(-max) : next\n redoStack.value = []\n }\n\n // Seed with the initial state so `undoStack[-1]` always equals\n // the current form. The first user mutation pushes a second\n // entry, enabling `undo()`.\n pushSnapshot(captureSnapshot())\n\n const unsubscribeChange = state.onFormChange(() => {\n if (suppressNext) {\n suppressNext = false\n return\n }\n pushSnapshot(captureSnapshot())\n })\n\n const unsubscribeReset = state.onReset(() => {\n // reset() fires onFormChange first (applyFormReplacement\n // emits it), then onReset. By the time we land here, a\n // snapshot for the reset state has already been pushed.\n // Clear both stacks and re-seed so the reset state becomes\n // the new baseline.\n undoStack.value = []\n redoStack.value = []\n pushSnapshot(captureSnapshot())\n })\n\n function restore(snap: HistorySnapshot<F>): void {\n suppressNext = true\n // Re-seed `blankPaths` BEFORE the form replacement fires. Listeners\n // on `onFormChange` (persistence's onFormChange tap, devtools, the\n // user's own subscriptions) read the form alongside `blankPaths`\n // when deciding what to persist or surface; updating both before\n // the listener loop runs keeps the pair consistent. If blankPaths\n // landed AFTER applyFormReplacement, the listeners would see new\n // form + stale blank set for one tick.\n state.blankPaths.clear()\n for (const key of snap.blankPaths) state.blankPaths.add(key)\n // Undo / redo replays a whole-form snapshot, so the persist decision\n // can't be made per-path. Rule: if the form has any opted-in path\n // at all, the rewind reaches the persistence layer (so the durable\n // record matches what the user just rolled back to). If nothing is\n // opted in, no write — matches the per-element default.\n state.applyFormReplacement(snap.form, {\n persist: !state.persistOptIns.isEmpty(),\n })\n // Rebuild both error stores from the snapshot. Each writer clears +\n // repopulates its own Map; the two sources stay isolated. Order is\n // arbitrary because the writers touch separate Maps with no\n // cross-dependency, but writing schema first keeps the per-key\n // insertion order matching the schema-first iteration invariant.\n const schemaFlat = snap.schemaErrors.flatMap(([, errs]) => errs)\n const userFlat = snap.userErrors.flatMap(([, errs]) => errs)\n state.setAllSchemaErrors(schemaFlat)\n state.setAllUserErrors(userFlat)\n }\n\n function undo(): boolean {\n if (undoStack.value.length <= 1) return false\n const current = undoStack.value[undoStack.value.length - 1]\n const prev = undoStack.value[undoStack.value.length - 2]\n if (current === undefined || prev === undefined) return false\n redoStack.value = [...redoStack.value, current]\n undoStack.value = undoStack.value.slice(0, -1)\n restore(prev)\n return true\n }\n\n function redo(): boolean {\n if (redoStack.value.length === 0) return false\n const next = redoStack.value[redoStack.value.length - 1]\n if (next === undefined) return false\n redoStack.value = redoStack.value.slice(0, -1)\n undoStack.value = [...undoStack.value, next]\n restore(next)\n return true\n }\n\n const canUndo = computed(() => undoStack.value.length > 1)\n const canRedo = computed(() => redoStack.value.length > 0)\n const historySize = computed(() => undoStack.value.length + redoStack.value.length)\n\n return {\n undo,\n redo,\n canUndo,\n canRedo,\n historySize,\n dispose() {\n unsubscribeChange()\n unsubscribeReset()\n undoStack.value = []\n redoStack.value = []\n },\n }\n}\n","/**\n * Deterministic non-cryptographic string hash. Used to compact long\n * structural-fingerprint strings into bounded-size storage-key tokens\n * (`attaform:formKey:<hash>` instead of\n * `attaform:formKey:object{\"a\":string,\"b\":number,...}`).\n *\n * Output: 11-char base36 string with leading zeros padded —\n * stable size regardless of input. ~53 bits of entropy (base of the\n * cyrb53 algorithm); collision space is 2^53. For the storage-key\n * disambiguation use case (a single app's worth of form schemas, all\n * fingerprinted at runtime) this is overkill.\n *\n * Properties:\n * - **Deterministic**: same input always produces the same output.\n * - **Sync, no allocations beyond the result**: hot-path-friendly;\n * no `crypto.subtle` (async) or `node:crypto` (server-only).\n * - **Browser + Node compatible**: only `Math.imul` and `String`\n * methods.\n *\n * NOT suitable for security-sensitive uses (auth tokens, integrity\n * checks). cyrb53 is non-cryptographic by design.\n *\n * Reference: bryc's collection of small JS hash functions\n * (https://github.com/bryc/code/blob/master/jshash/PRNGs.md).\n */\nexport function hashStableString(input: string, seed = 0): string {\n let h1 = 0xdeadbeef ^ seed\n let h2 = 0x41c6ce57 ^ seed\n for (let i = 0; i < input.length; i++) {\n const ch = input.charCodeAt(i)\n h1 = Math.imul(h1 ^ ch, 2654435761)\n h2 = Math.imul(h2 ^ ch, 1597334677)\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)\n // Combine the two 32-bit halves into a 53-bit value, base36-encode.\n // `padStart(11, '0')` keeps the output a fixed length so storage\n // keys are visually aligned and easy to grep.\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).padStart(11, '0')\n}\n","import { getCurrentInstance, getCurrentScope, onScopeDispose, provide, toRaw, useId } from 'vue'\nimport { buildFormApi } from '../core/build-form-api'\nimport { createFormStore, type FormStore } from '../core/create-form-store'\nimport {\n ANONYMOUS_FORM_KEY_PREFIX,\n DEFAULT_PERSISTENCE_DEBOUNCE_MS,\n PERSISTENCE_KEY_PREFIX,\n RESERVED_KEY_PREFIX,\n} from '../core/defaults'\nimport { __DEV__ } from '../core/dev'\nimport { captureUserCallSite } from '../core/dev-stack-trace'\nimport { AnonPersistError, InvalidUseFormConfigError, ReservedFormKeyError } from '../core/errors'\nimport { extractSchemaFields } from '../core/extract-schema-fields'\nimport type { FieldState } from '../core/field-state-api'\nimport { getComputedSchema } from '../core/get-computed-schema'\nimport { createHistoryModule, type HistoryModule } from '../core/history'\nimport {\n buildPersistedPayload,\n cleanupOrphanKeys,\n createDebouncedWriter,\n filterErrorsByPaths,\n getStorageAdapter,\n mergeSparseHydration,\n normalizePersistConfig,\n PERSISTENCE_MODULE_KEY,\n pluckPaths,\n readPersistedPayload,\n resolveStorageKeyBase,\n sweepAllOrphansAcrossStandardStores,\n sweepNonConfiguredStandardStoresForOrphans,\n type PersistenceModule,\n} from '../core/persistence'\nimport { hashStableString } from '../core/hash'\nimport { canonicalizePath, type Path, type PathKey } from '../core/paths'\nimport { deleteAtPath, getAtPath, setAtPath, isPlainRecord } from '../core/path-walker'\nimport { ensureAttaformInstalled } from '../core/plugin'\nimport { kFormContext, kFormInstanceId, useRegistry } from '../core/registry'\nimport { walkUnsetSentinels } from '../core/unset-walker'\nimport type {\n AbstractSchema,\n AttaformDefaults,\n FormKey,\n PersistConfigOptions,\n UseFormReturnType,\n UseFormConfiguration,\n ValidationError,\n} from '../types/types-api'\nimport type { DeepPartial, DefaultValuesShape, GenericForm, WriteShape } from '../types/types-core'\n\n/**\n * Schema-agnostic `useForm`. Accepts any object that implements\n * `AbstractSchema` — useful when integrating a custom schema\n * adapter or a third-party validation library.\n *\n * ```ts\n * import { useForm } from 'attaform'\n *\n * const form = useForm({\n * schema: myCustomAdapter,\n * defaultValues: { name: '' },\n * })\n * ```\n *\n * Most consumers prefer a typed entry point that wraps the underlying\n * library's schema with the matching adapter automatically; see the\n * subpath documentation for the available adapters.\n *\n * Returns the same form API as the typed entry points; see\n * `UseFormReturnType` for the full surface.\n */\n\nexport function useAbstractForm<\n Form extends GenericForm,\n GetValueFormType extends GenericForm = Form,\n>(\n configuration: UseFormConfiguration<\n Form,\n GetValueFormType,\n AbstractSchema<Form, GetValueFormType>,\n DeepPartial<DefaultValuesShape<Form>>\n >\n): UseFormReturnType<Form, GetValueFormType> {\n // Foot-gun guard: catches `useForm()` (no args), `useForm(null)`,\n // `useForm(rawSchema)` (any schema-like object passed as the first\n // argument — its `.schema` field is undefined), and the explicit\n // `useForm({ schema: undefined })` case. Throws synchronously\n // before any downstream code reads `configuration.schema`.\n if (\n configuration === undefined ||\n configuration === null ||\n (configuration as { schema?: unknown }).schema === undefined\n ) {\n throw new InvalidUseFormConfigError()\n }\n\n const key = resolveFormKey(configuration.key)\n\n // Resolve the schema (accepts either an AbstractSchema or a factory).\n // Preserve both generics — dropping `GetValueFormType` here would make\n // `state.schema.getSchemasAtPath(...)` return `AbstractSchema<_, Form>[]`\n // for consumers whose schema intentionally produces a different runtime\n // shape (e.g. an adapter that narrows via a transform).\n const resolvedSchema = getComputedSchema(key, configuration.schema)\n\n // Eager throw: persistence configured without an explicit `key:`. An\n // anonymous synthetic key (`__atta:anon:*`) drifts across mounts (HMR /\n // route changes / SSR↔CSR) and can collide between unrelated forms —\n // refusing here keeps the namespace stable and forecloses on the\n // future encrypted-backend case where collision becomes a key-derivation\n // overlap. Throws in dev and prod alike. The error body carries the\n // schema's top-level fields and a captured call-site so the offender\n // is identifiable from the message alone.\n if (configuration.persist !== undefined && configuration.key === undefined) {\n throw new AnonPersistError({\n cause: 'no-key',\n schemaFields: extractSchemaFields(resolvedSchema),\n callSite: captureUserCallSite(),\n })\n }\n\n // One FormStore per (app, formKey). Multiple useForm calls with the same\n // key resolve to the same instance — that's the shared-store semantic\n // for forms that explicitly opt in to a stable key.\n //\n // Lazy-install: if the consumer hasn't called `createAttaform()`,\n // attach the registry now. Idempotent — explicit installs (Nuxt\n // module, manual `app.use(createAttaform({ defaults }))`) win when\n // they ran first. The strict `useRegistry()` below still throws\n // `OutsideSetupError` when called outside setup; the lazy install\n // only ever fires when an instance is available.\n const instance = getCurrentInstance()\n if (instance !== null) ensureAttaformInstalled(instance.appContext.app)\n const registry = useRegistry()\n\n // Merge app-level defaults from the registry over per-form options.\n // Per-form values always win for scalars; `validateOn` and `debounceMs`\n // resolve independently so consumers can set `debounceMs` globally\n // and override `validateOn` per-form. Every downstream read uses\n // `merged` so the merge happens exactly once.\n const merged = mergeWithDefaults(registry.defaults, configuration)\n\n const existing = registry.forms.get(key) as FormStore<Form, GetValueFormType> | undefined\n if (__DEV__ && existing !== undefined) {\n // Shared-key semantics are a feature when consumers OPT in to them\n // (two `useForm({ key: 'x' })` calls that genuinely want the same\n // store). They're a silent-collision footgun when two unrelated\n // parts of an app happen to agree on a key. Fingerprinting the\n // schema turns collision into a diagnosable warning: if the\n // second call's schema has a different structural fingerprint\n // than the first's, the forms almost certainly shouldn't be\n // sharing. The second call's schema is then silently dropped in\n // favour of the first's — matching what already happens (only\n // the first caller's config wires the FormStore).\n warnOnSchemaFingerprintMismatch(key, existing.schema, resolvedSchema)\n }\n const state: FormStore<Form, GetValueFormType> =\n existing ?? buildFreshState<Form, GetValueFormType>(key, resolvedSchema, merged, registry)\n\n // Ref-count this consumer. When the component's effect scope tears down,\n // release the count; the registry evicts the FormStore once the last\n // consumer disposes. Guarded on `getCurrentScope()` so callers without an\n // effect-scope context (defensive — setup() always provides one) don't\n // leak a pinned consumer. See registry.trackConsumer for the counter.\n if (getCurrentScope() !== undefined) {\n const releaseConsumer = registry.trackConsumer(key)\n onScopeDispose(releaseConsumer)\n }\n\n // Wire persistence (opt-in) — only on fresh state creation, skipped\n // on SSR. `existing` means a prior useForm() already mounted and\n // wired persistence; we don't double-subscribe. The handle is cached\n // on `state.modules` so `buildFormApi` can plug `form.persist` /\n // `form.clearPersistedDraft` into the consumer-facing API. The\n // disposer is registered on the FormStore (not on this consumer's\n // scope) so persistence survives any single consumer unmounting — it\n // tears down only when the last consumer releases and the registry\n // evicts the state.\n //\n // The shorthand input (`persist: 'local'`, `persist: customAdapter`)\n // is normalised to the resolved options bag once at this boundary —\n // Anonymous + persist enforcement. Dev throws (catches the bug at\n // the offending useForm() call); prod returns `true` so the wiring\n // block below skips entirely AND cleans up any prior persisted\n // entries — we'd rather pretend persist wasn't configured than\n // silently mis-route data between forms that happened to share an\n // anon id. Runs regardless of SSR / first-mount-vs-rehook so the\n // dev-mode throw fires on the SSR pass too (without a server-side\n // throw, the SSR pass would succeed silently and the client would\n // throw on hydration — that surfaces as a confusing hydration\n // mismatch instead of pointing at the actual config bug).\n const persistDisabledByAnonRule =\n merged.persist !== undefined && enforceAnonPersistRule(state.formKey, registry.ssr)\n // everything below operates on the resolved shape.\n if (existing === undefined && !registry.ssr) {\n if (merged.persist !== undefined && !persistDisabledByAnonRule) {\n const resolvedPersist = normalizePersistConfig(merged.persist)\n const persistenceBase = resolveStorageKeyBase(resolvedPersist, state.formKey)\n // Cross-store orphan cleanup: any standard backend not matching\n // the configured one gets every attaform-managed key under the\n // base wiped (unfingerprinted AND stale-fingerprint alike).\n // Ensures stale drafts can't survive in stores the dev migrated\n // AWAY from. Fire-and-forget; backend unavailability is silent.\n void sweepNonConfiguredStandardStoresForOrphans(resolvedPersist.storage, persistenceBase)\n const persistenceModule = wirePersistence(state, resolvedPersist)\n state.modules.set(PERSISTENCE_MODULE_KEY, persistenceModule)\n // Drain BEFORE the synchronous teardown: the registry will await\n // `awaitPendingWrites` before calling `dispose`, so the last\n // debounced keystroke gets to disk before the FormStore is\n // evicted from the registry's `forms` map.\n state.registerDrain(() => persistenceModule.awaitPendingWrites())\n state.registerCleanup(() => persistenceModule.dispose())\n } else {\n // Either the dev didn't configure `persist:` OR we just disabled\n // it via the anon-persist rule. Either way, sweep every\n // attaform-managed key under this form's base across all standard\n // backends so dropping (or refusing to wire) persistence\n // actually leaves storage clean.\n void sweepAllOrphansAcrossStandardStores(`${PERSISTENCE_KEY_PREFIX}${state.formKey}`)\n }\n }\n\n // Wire history (opt-in). Fresh-state-only — the module subscribes\n // to FormStore events, so subscribing twice would double-push\n // snapshots. Cache the module on the FormStore so subsequent\n // `useForm` / `injectForm` calls for the same key retrieve the\n // SAME instance, keeping `canUndo` / `canRedo` / `historySize` /\n // `undo` / `redo` consistent across mount order.\n if (existing === undefined && merged.history !== undefined) {\n const historyModule = createHistoryModule(state, merged.history)\n state.modules.set(HISTORY_MODULE_KEY, historyModule)\n state.registerCleanup(() => historyModule.dispose())\n }\n\n // Provide the FormStore to descendants via `kFormContext` so\n // `injectForm()` can resolve it without prop-threading.\n //\n // ONLY anonymous `useForm()` calls fill the ambient slot. Keyed forms\n // are explicitly addressable via `injectForm<F>(key)` and don't\n // pollute the ambient context — keeping the two resolution modes\n // semantically distinct. A descendant of a keyed-only parent that\n // calls `injectForm<F>()` (no key) gets the \"no ambient form\"\n // throw, which is the right error: the form has a name; address it.\n //\n // Ambient mode is still \"last-provide wins\" among siblings: if two\n // anonymous `useForm()` calls run in the same component, the second\n // overwrites the first and descendants only see the second. We record\n // the per-instance history of ANONYMOUS provides here (silently) so\n // that a descendant's `injectForm<F>()` call can walk up, detect\n // the collision, and warn lazily. Recording is skipped on SSR so the\n // client-side warn fires once, not once-per-render-pass.\n if (configuration.key === undefined) {\n recordAmbientProvide(registry.ssr)\n provide(kFormContext, state as FormStore<GenericForm>)\n }\n\n // Per-`useForm()`-call instance ID. Distinct from `state.formKey`:\n // the key identifies a SHARED FormStore (so two `useForm({ key:\n // 'signup' })` calls return the same store), while `formInstanceId`\n // identifies THIS specific callsite — important for `focusFirstError`\n // / `scrollToFirstError` to scope to the elements THIS caller's\n // `v-register` directives bound to. SSR-safe via Vue 3.5+'s\n // `useId()`. Outside Vue setup (tests, ad-hoc composable use) we\n // fall back to a module-local counter — uniqueness is what matters,\n // and tests don't share form-instance state across mounts anyway.\n const formInstanceId =\n getCurrentInstance() !== null ? useId() : `atta:form-instance:${formInstanceCounter++}`\n // Provided so descendants reaching via `injectForm()` inherit this ID\n // and their locally-registered elements tag against the same instance.\n // Sibling `useForm()` calls (different tree positions) provide their\n // own IDs and stay isolated.\n if (getCurrentInstance() !== null) {\n provide(kFormInstanceId, formInstanceId)\n }\n\n const apiOptions: Parameters<typeof buildFormApi<Form, GetValueFormType>>[2] = {}\n if (merged.onInvalidSubmit !== undefined) {\n apiOptions.onInvalidSubmit = merged.onInvalidSubmit\n }\n const history = state.modules.get(HISTORY_MODULE_KEY) as HistoryModule | undefined\n if (history !== undefined) {\n apiOptions.history = history\n }\n return buildFormApi<Form, GetValueFormType>(state, formInstanceId, apiOptions)\n}\n\n/**\n * Merge app-level defaults from the registry over a per-form\n * configuration. Per-form values always win for scalars; `validateOn`\n * and `debounceMs` resolve independently so a default like\n * `{ debounceMs: 100 }` carries through even when the per-form call\n * passes `{ validateOn: 'blur' }`. See `AttaformDefaults` for the\n * full merge contract.\n */\nfunction mergeWithDefaults<\n Form extends GenericForm,\n GetValueFormType extends GenericForm,\n Schema extends AbstractSchema<Form, GetValueFormType>,\n Defaults extends DeepPartial<DefaultValuesShape<Form>>,\n>(\n defaults: AttaformDefaults,\n configuration: UseFormConfiguration<Form, GetValueFormType, Schema, Defaults>\n): UseFormConfiguration<Form, GetValueFormType, Schema, Defaults> {\n // exactOptionalPropertyTypes rejects explicit `undefined` on optional\n // properties (different from omitting), so conditionally spread each\n // resolved value rather than assigning undefined into the field.\n const strict = configuration.strict ?? defaults.strict\n const onInvalidSubmit = configuration.onInvalidSubmit ?? defaults.onInvalidSubmit\n const history = configuration.history ?? defaults.history\n const rememberVariants = configuration.rememberVariants ?? defaults.rememberVariants\n const coerce = configuration.coerce ?? defaults.coerce\n const validateOn = configuration.validateOn ?? defaults.validateOn\n // `debounceMs` is type-narrowed in the public discriminated union to\n // disallow non-`'change'` mode + debounce; here at the resolution\n // boundary we only see the unwrapped fields, so the access is\n // unconditional. The runtime check in `create-form-store.ts` ignores\n // the value under non-`'change'` modes regardless.\n const debounceMs = (configuration as { debounceMs?: number }).debounceMs ?? defaults.debounceMs\n return {\n ...configuration,\n ...(strict === undefined ? {} : { strict }),\n ...(onInvalidSubmit === undefined ? {} : { onInvalidSubmit }),\n ...(history === undefined ? {} : { history }),\n ...(rememberVariants === undefined ? {} : { rememberVariants }),\n ...(coerce === undefined ? {} : { coerce }),\n ...(validateOn === undefined ? {} : { validateOn }),\n ...(debounceMs === undefined ? {} : { debounceMs }),\n } as UseFormConfiguration<Form, GetValueFormType, Schema, Defaults>\n}\n\n/**\n * Shared key for the per-state history module cache. Exported would be\n * over-sharing — the only callers are this file and `injectForm`.\n */\nconst HISTORY_MODULE_KEY = 'history'\n\nfunction buildFreshState<F extends GenericForm, G extends GenericForm = F>(\n key: FormKey,\n schema: AbstractSchema<F, G>,\n configuration: UseFormConfiguration<\n F,\n G,\n AbstractSchema<F, G>,\n DeepPartial<DefaultValuesShape<F>>\n >,\n registry: ReturnType<typeof useRegistry>\n): FormStore<F, G> {\n const pending = registry.pendingHydration.get(key)\n if (pending !== undefined) registry.pendingHydration.delete(key)\n // Pre-pass: replace every `unset` sentinel in defaultValues with the\n // schema's slim default and collect the corresponding path keys.\n // Also auto-marks every primitive leaf the consumer did NOT cover —\n // a freshly opened form has no user input yet, so unspecified leaves\n // are logically blank. Devs opt a leaf out by supplying a non-`unset`\n // value for it. The walker mirrors `DefaultValuesShape<T>`'s\n // recursion; runtime landing of `unset` at a non-primitive leaf\n // produces a dev-warn (TS catches this at compile time but plain-JS\n // consumers bypass).\n const walked = walkUnsetSentinels(\n configuration.defaultValues,\n schema as unknown as AbstractSchema<GenericForm, GenericForm>\n )\n // Hydration precedence: when a hydration payload is present its\n // `blankPaths` field is the authoritative truth. We still\n // run the walker to scrub `unset` symbols out of `defaultValues` (so\n // they never reach storage), but discard the discovered paths in\n // favour of the hydrated set. Without this, a server-rendered form\n // with no blank paths would gain ones the client's\n // construction-time defaults invented.\n const initialBlankPaths: ReadonlyArray<string> | undefined =\n pending === undefined ? walked.paths : undefined\n const createOptions: Parameters<typeof createFormStore<F, G>>[0] = {\n formKey: key,\n schema,\n defaultValues: walked.cleanedValues as DeepPartial<WriteShape<F>> | undefined,\n ...(configuration.strict !== undefined ? { strict: configuration.strict } : {}),\n hydration: pending,\n ...(configuration.validateOn !== undefined ? { validateOn: configuration.validateOn } : {}),\n ...((configuration as { debounceMs?: number }).debounceMs !== undefined\n ? { debounceMs: (configuration as { debounceMs?: number }).debounceMs }\n : {}),\n ssr: registry.ssr,\n ...(configuration.rememberVariants !== undefined\n ? { rememberVariants: configuration.rememberVariants }\n : {}),\n ...(configuration.coerce !== undefined ? { coerce: configuration.coerce } : {}),\n ...(initialBlankPaths !== undefined ? { initialBlankPaths } : {}),\n }\n const state = createFormStore<F, G>(createOptions)\n // Storage type is FormStore<GenericForm>; the lookup above narrows\n // back to the caller's (F, G) via the `existing as FormStore<Form,\n // GetValueFormType>` cast. The registry Map is intentionally\n // generic-erased — the alternative (parameterising the Map) would\n // force every internal caller to carry both generics.\n ;(registry.forms as Map<FormKey, FormStore<GenericForm>>).set(\n key,\n state as unknown as FormStore<GenericForm>\n )\n return state\n}\n\n/**\n * Module-local counter for the \"no Vue instance in scope\" fallback\n * (tests, raw composable calls outside setup). Collisions with\n * user-supplied keys are avoided by the reserved `__atta:anon:` prefix\n * (consumer keys starting with `__atta:` are rejected at construction).\n * Inside\n * setup — the common path — `useId()` produces a tree-position-stable\n * id that matches across SSR hydration, so two mounts of the same\n * component tree resolve to the same anonymous key and hydration\n * works without user bookkeeping.\n */\nlet anonCounter = 0\n\n/**\n * Module-local counter for `formInstanceId` allocation outside Vue\n * setup (tests, ad-hoc composable usage). The setup-context path uses\n * `useId()` for SSR-stable IDs; this counter is the test-only fallback.\n */\nlet formInstanceCounter = 0\n\n/**\n * One entry per ANONYMOUS `useForm()` call that landed in a\n * component's ambient provide slot. Keyed forms aren't recorded —\n * they don't fill the ambient slot in the first place. `source` is\n * the best-effort user call site (first non-attaform frame off\n * `new Error().stack`) — printed in the collision warning so the\n * author can navigate to each offending call site.\n */\nexport type AmbientProvideEntry = {\n readonly source: string | undefined\n}\n\n/**\n * Tracks which Vue component instances have already run\n * `provide(kFormContext, ...)` via `useAbstractForm`. Dev-only —\n * `null` in production so the WeakMap allocation tree-shakes out.\n * A `WeakMap` keyed by the instance object lets Vue GC each\n * component's entry when it unmounts without us tracking\n * lifecycle.\n *\n * Exported so `injectForm<F>()` (no key) can walk the parent\n * chain and emit a collision warning only when a descendant\n * actually consumes the ambient slot — eager warning in\n * `useForm()` misfired on components that call useForm multiple\n * times intentionally but have no keyless consumer.\n */\nexport const ambientProvideHistory: WeakMap<object, AmbientProvideEntry[]> | null = __DEV__\n ? new WeakMap<object, AmbientProvideEntry[]>()\n : null\n\nfunction recordAmbientProvide(ssr: boolean): void {\n if (!__DEV__ || ssr || ambientProvideHistory === null) return\n const instance = getCurrentInstance()\n if (instance === null) return\n const instanceKey = instance as unknown as object\n // Caller already gated on `configuration.key === undefined`, so every\n // recorded entry corresponds to an anonymous useForm() call. No need\n // to carry a key — synthetic `__atta:anon:<id>` keys aren't addressable\n // by the author and would only add noise to the warning.\n const entry: AmbientProvideEntry = {\n source: captureUserCallSite(),\n }\n const existing = ambientProvideHistory.get(instanceKey)\n if (existing === undefined) {\n ambientProvideHistory.set(instanceKey, [entry])\n return\n }\n existing.push(entry)\n}\n\n/**\n * Normalise `configuration.key` into a concrete FormKey. Explicit keys\n * pass through after a reserved-namespace check (anything starting\n * with `__atta:` is rejected with `ReservedFormKeyError`); empty /\n * nullish keys are treated as anonymous and allocated a unique id\n * under the `__atta:anon:` prefix. The reserved-prefix reject + the\n * synthetic-prefix reservation together guarantee zero collision\n * between consumer-chosen keys and library-allocated synthetic ones.\n *\n * Anonymous semantics: each `useForm({ schema })` call without a key\n * resolves to a distinct FormStore. Descendant components reach it via\n * ambient `injectForm<F>()`; cross-component lookup by key is not\n * possible (and not meaningful — the key is synthetic). Callers that\n * need shared state, distant lookup, persistence defaults, or a\n * recognisable DevTools label should pass an explicit `key`.\n */\nfunction resolveFormKey(key: FormKey | undefined): FormKey {\n if (key !== undefined && key !== null && key !== '') {\n // Reject any consumer-supplied key in the reserved `__atta:`\n // namespace. Without this, a consumer key like `__atta:anon:0`\n // could silently collide with the synthetic anonymous-key\n // allocation below — both would land on the same FormStore in\n // the registry, and the dev-mode schema-fingerprint warning\n // only catches collisions when schemas differ. Throwing here\n // makes the collision impossible by construction.\n if (key.startsWith(RESERVED_KEY_PREFIX)) {\n throw new ReservedFormKeyError(key)\n }\n return key\n }\n // In setup context, `useId()` threads through Vue's SSR id-allocator\n // so server-rendered and client-hydrated trees agree on the same\n // synthetic key.\n if (getCurrentInstance() !== null) {\n return `${ANONYMOUS_FORM_KEY_PREFIX}${useId()}`\n }\n // Outside setup (tests, ad-hoc composable use) there's no Vue\n // instance to draw from; fall back to a module-local counter.\n return `${ANONYMOUS_FORM_KEY_PREFIX}${anonCounter++}`\n}\n\n/**\n * Dev-only: warn when a second `useForm` lands on the same key with\n * a structurally-different schema. Two schemas compute their own\n * fingerprints; we compare the strings and flag mismatches. An\n * adapter-thrown `fingerprint()` is caught (never crashes the form)\n * and surfaced as a `console.error` in dev — the mismatch check is\n * skipped, matching the \"allow the inconsistency\" failure mode. See\n * `AbstractSchema.fingerprint()` in types-api.ts for the contract.\n */\nfunction warnOnSchemaFingerprintMismatch(\n key: FormKey,\n existing: AbstractSchema<GenericForm, GenericForm>,\n incoming: AbstractSchema<GenericForm, GenericForm>\n): void {\n let existingFp: string\n let incomingFp: string\n try {\n existingFp = existing.fingerprint()\n incomingFp = incoming.fingerprint()\n } catch (error) {\n console.error(\n `[attaform] fingerprint() threw for key \"${key}\"; skipping mismatch check.`,\n error\n )\n return\n }\n if (existingFp === incomingFp) return\n console.warn(\n `[attaform] useForm() calls with key \"${key}\" use different schemas; first wins, second is ignored. Use identical schemas or unique keys.\\n existing: ${existingFp}\\n incoming: ${incomingFp}`\n )\n}\n\n/**\n * Wire persistence to a fresh FormStore:\n *\n * 1. Resolve the storage adapter (dynamic-imported — `'local'` never\n * pulls IDB code; tree-shakes cleanly).\n * 2. Async-read any persisted payload and apply it via\n * `applyFormReplacement`. First render shows schema defaults\n * (the \"flash of default state\" — documented tradeoff for\n * async backends).\n * 3. Subscribe a debounced writer to `onFormChange`; every mutation\n * schedules a write.\n * 4. Subscribe a `removeItem` on submit-success (when\n * `clearOnSubmitSuccess` is not explicitly false).\n * 5. Return a disposer that flushes any pending write, cancels\n * the debounce, and removes subscribers. Called on consumer\n * teardown.\n */\nfunction wirePersistence<F extends GenericForm>(\n state: FormStore<F>,\n config: PersistConfigOptions\n): PersistenceModule {\n // Fingerprint the schema once and bake it into the storage key. Any\n // structural schema change (added/removed/renamed field, type swap)\n // produces a different fingerprint, so the new mount looks up a fresh\n // key — the old draft becomes an orphan, cleaned up in the same mount\n // by `cleanupOrphanKeys` below. No manual version protocol required.\n // Hash the long structural fingerprint into a fixed-size token before\n // baking it into the storage key. The raw fingerprint is the\n // schema's full shape stringified (`object{\"address\":object{...}}`),\n // which works correctly for invalidation but produces 200+ char\n // storage keys for non-trivial schemas AND leaks the schema's\n // structure into client-side storage. The hash preserves\n // determinism (same schema → same hash) without either downside.\n const fingerprint = hashStableString(state.schema.fingerprint())\n const base = resolveStorageKeyBase(config, state.formKey)\n const key = `${base}:${fingerprint}`\n const debounceMs = config.debounceMs ?? DEFAULT_PERSISTENCE_DEBOUNCE_MS\n const include = config.include ?? 'form'\n const clearOnSubmitSuccess = config.clearOnSubmitSuccess ?? true\n\n // Single shared adapter promise — both the hydration path and the\n // write/clear paths await it. Avoids a race where an early write\n // (fast debounceMs) would see `adapter === null` and skip silently\n // because the dynamic-import hadn't resolved yet.\n const adapterPromise = getStorageAdapter(config.storage)\n let disposed = false\n // Tracks the in-flight final flush kicked off by `dispose()`. Returned\n // by `awaitPendingWrites` so the registry can drain pending storage\n // writes before evicting the FormStore — without this, the last\n // debounced keystroke is silently dropped on unmount.\n let inFlightFinalFlush: Promise<void> | null = null\n // Snapshot of opt-in paths captured at SCHEDULE time. Vue's unmount\n // lifecycle runs directive `beforeUnmount` (which clears per-element\n // opt-ins) BEFORE the effect-scope dispose that triggers our drain.\n // Without a snapshot, a write flushed during the drain sees zero\n // opt-ins and wipes the storage entry. The snapshot lets the eventual\n // write reflect the moment-in-time opt-ins as the user typed.\n let pendingOptedInPaths: Set<PathKey> | null = null\n\n const writer = createDebouncedWriter(async () => {\n // No bail at entry: this closure runs from two paths — the\n // debounce timer firing (which already gated on `disposed` via the\n // schedule call) and the final flush from `dispose()`. The final\n // flush's invocation order (flush BEFORE disposed flips) lets this\n // write complete; the post-await guards below catch the rare case\n // where adapter resolution is slow enough to overlap with the\n // disposed flip.\n //\n // Use the schedule-time snapshot if present (handles the unmount\n // race where beforeUnmount has cleared the live registry). Falls\n // back to the live registry for any non-listener-triggered path.\n const optedInPaths = pendingOptedInPaths ?? new Set<PathKey>(state.persistOptIns.optedInPaths())\n pendingOptedInPaths = null\n const adapter = await adapterPromise\n if (disposed) return\n // Sparse-payload reshape: the persisted form contains only paths\n // that were opted in via `register('foo', { persist: true })`. If\n // every opt-in has been torn down, wipe the entry rather than\n // write a hollow envelope (matches the per-element security model\n // — no opt-ins → nothing to persist).\n if (optedInPaths.size === 0) {\n await adapter.removeItem(key)\n return\n }\n // Unwrap the reactive form to a plain object before handing it to\n // the adapter — IDB's `structuredClone` can't serialise Vue\n // proxies (DATA_CLONE_ERR), and local/session stringify the\n // proxy's own-enumerable keys anyway.\n const rawForm = toRaw(state.form.value)\n const filteredForm = pluckPaths(rawForm, optedInPaths) as F\n // Build the envelope with the attaform-internal envelope version baked\n // in by `buildPersistedPayload`. Consumers no longer manage `v` —\n // schema-content invalidation lives at the storage-key level via\n // the fingerprint suffix.\n const filteredSchemaErrors = filterErrorsByPaths(state.schemaErrors, optedInPaths)\n const filteredUserErrors = filterErrorsByPaths(state.userErrors, optedInPaths)\n // Blank paths are part of the restorable UI state, so\n // they ride the same opt-in gate as form values: only persist\n // the entries whose paths are also opted in for persistence.\n const filteredTransientEmpty = new Set<string>()\n for (const tk of state.blankPaths) {\n if (optedInPaths.has(tk as PathKey)) filteredTransientEmpty.add(tk)\n }\n const payload = buildPersistedPayload<F>(\n filteredForm,\n include,\n filteredSchemaErrors,\n filteredUserErrors,\n filteredTransientEmpty\n )\n await adapter.setItem(key, payload)\n }, debounceMs)\n\n const unsubscribeChange = state.onFormChange((_next, meta) => {\n if (disposed || inFlightFinalFlush !== null) return\n // Per-element opt-in: only writes whose source declared `persist: true`\n // reach the storage adapter. Programmatic `form.setValue`, history\n // undo without opt-ins, devtools edits to non-opted paths, and\n // `reset()` all bypass this gate by passing no meta (or `persist:\n // false`).\n if (meta?.persist !== true) return\n // Snapshot opt-in paths NOW — Vue's unmount fires directive\n // beforeUnmount (which calls persistOptIns.removeAllFor) BEFORE\n // the scope-dispose that drives our drain. Capturing at schedule\n // time means the eventual write sees the opt-ins as they were\n // when the user typed, not as they were stripped.\n pendingOptedInPaths = new Set<PathKey>(state.persistOptIns.optedInPaths())\n writer.schedule()\n })\n\n const unsubscribeSuccess = clearOnSubmitSuccess\n ? state.onSubmitSuccess(() => {\n if (disposed) return\n // Flush any pending/in-flight write BEFORE removing — otherwise\n // a timer that fires between submit and removeItem re-persists\n // the now-stale state. `flush()` awaits the in-flight promise\n // if one exists; if there's only a timer, it fires it\n // immediately and awaits. After that, removeItem wins.\n void (async () => {\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n await adapter.removeItem(key)\n })()\n })\n : () => undefined\n\n // Async setup: resolve the adapter, then read back the persisted\n // payload. If the caller unmounts before this finishes, `disposed`\n // is true — the restore is skipped.\n void (async () => {\n const adapter = await adapterPromise\n if (disposed) return\n // Orphan cleanup: delete any attaform-managed key under the same base\n // whose fingerprint suffix doesn't match the current schema. Runs\n // once per mount, fire-and-forget. Bounded cost: typically 0-1\n // orphans per form.\n void cleanupOrphanKeys(adapter, base, key)\n try {\n const raw = await adapter.getItem(key)\n const payload = readPersistedPayload<F>(raw)\n if (payload === null) {\n // Truly-absent entries are a no-op. A non-null raw that didn't\n // parse is a stale payload — wrong attaform envelope version, or\n // malformed shape — wipe so the next mount reads cleanly.\n if (raw !== null && raw !== undefined) {\n await adapter.removeItem(key)\n }\n return\n }\n if (disposed) return\n // Sparse-aware replacement: the persisted form may contain only\n // a subset of paths (the ones opted into persistence on the\n // previous mount). Merge over the current form (which carries\n // schema defaults at this point — wirePersistence runs before\n // any user mutation could have happened) so non-persisted paths\n // keep their schema defaults.\n const merged = mergeSparseHydration(\n toRaw(state.form.value) as F,\n payload.data.form,\n state.schema as unknown as Parameters<typeof mergeSparseHydration>[2]\n )\n state.applyFormReplacement(merged)\n // payload. Persistence is per-element opt-in, so the persisted\n // payload only covers paths within the opt-in scope (the leaf\n // paths populated in `payload.data.form`). Construction-time\n // auto-marks for paths OUTSIDE that scope must survive —\n // without this, a non-opted-in numeric field's slim default\n // (`0`) would lose its blank mark on hydrate and surface as\n // `'0'` in its <input> instead of empty.\n //\n // Within the opt-in scope, the persisted state IS the truth: a\n // persisted path that's no longer blank (the user\n // typed) clears the construction-time mark, and a persisted\n // path that IS blank (still slim default) re-asserts.\n const persistedLeafPaths = collectPersistedLeafPaths(payload.data.form)\n for (const k of persistedLeafPaths) {\n state.blankPaths.delete(k)\n state.originalBlankPaths.delete(k)\n }\n for (const k of payload.data.blankPaths ?? []) {\n state.blankPaths.add(k as PathKey)\n state.originalBlankPaths.add(k as PathKey)\n }\n if (include === 'form+errors') {\n // Each store rebuilds independently from its persisted entries.\n // Consumers who bumped `version` already had their payload\n // rejected above.\n if (payload.data.schemaErrors !== undefined) {\n const flat = payload.data.schemaErrors.flatMap(([, errs]) => errs)\n state.setAllSchemaErrors(flat)\n }\n if (payload.data.userErrors !== undefined) {\n const flat = payload.data.userErrors.flatMap(([, errs]) => errs)\n state.setAllUserErrors(flat)\n }\n }\n // Post-hydration revalidation: the construction-time seed ran\n // against the empty default, so its errors describe a stale\n // value. Async-only verdicts additionally never fire at\n // construction (the sync seed contract can't surface them;\n // schemas with async refinements / transforms / pipes degrade\n // to success there). A full async run at the root path wipes\n // `schemaErrors` and re-stamps with the authoritative result\n // for the rehydrated value — sync errors get refreshed, async\n // verdicts fire, the form lands in the state the persisted\n // value actually deserves.\n state.scheduleFieldValidation([], true /* immediate */)\n } catch {\n // Adapter IO errors shouldn't surface; storage adapters are\n // \"best-effort\" and already log their own warnings.\n }\n })()\n\n // Note: a \"configured but no fields opted in\" check used to live here\n // (microtask-deferred warn). Removed — having the persist capability\n // configured without spending it on a register() call is a valid\n // dormant state (scaffolding, A/B'd opt-ins, future-flagged fields).\n // The library shouldn't lecture the consumer for not exercising every\n // configured option. Eager throws only fire on actual contradictions\n // (no-key + persist; register-with-persist + no useForm-persist).\n\n /**\n * Imperative one-shot write. Read-merge-write strategy: flush any\n * pending debounced write first (so it can't overwrite our update),\n * read the existing payload, set the path's current value, optionally\n * merge in this path's errors, and write back. Preserves untouched\n * paths in storage.\n */\n async function writePathImmediately(path: Path): Promise<void> {\n if (disposed) return\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n const raw = await adapter.getItem(key)\n const existing = readPersistedPayload<F>(raw)\n const baseForm = existing?.data.form ?? ({} as F)\n const value = getAtPath(toRaw(state.form.value), path)\n const nextForm = setAtPath(baseForm, path, value) as F\n // Refresh this path's blank entry — and any descendants\n // — while preserving entries for OTHER paths the previous mount\n // persisted. Non-leaf writes (`writePathImmediately('user')`)\n // overwrite the entire subtree, so any disk entries below the\n // write path are dropped first; the live in-memory set then\n // contributes whatever marks are still active under that subtree.\n const { key: pathKey } = canonicalizePath(path)\n const transientSet = new Set<string>(\n (existing?.data.blankPaths ?? []).filter(\n (k) => k !== pathKey && !isDescendantPathKey(k, pathKey)\n )\n )\n for (const liveKey of state.blankPaths) {\n if (liveKey === pathKey || isDescendantPathKey(liveKey, pathKey)) {\n transientSet.add(liveKey)\n }\n }\n if (include === 'form') {\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form', new Map(), new Map(), transientSet)\n )\n return\n }\n // include === 'form+errors': preserve the rest of the persisted\n // error map and refresh the entry for this path's canonical key.\n const schemaMap = new Map<string, ValidationError[]>(existing?.data.schemaErrors ?? [])\n const userMap = new Map<string, ValidationError[]>(existing?.data.userErrors ?? [])\n const currentSchema = state.schemaErrors.get(pathKey)\n const currentUser = state.userErrors.get(pathKey)\n if (currentSchema !== undefined && currentSchema.length > 0) {\n schemaMap.set(pathKey, [...currentSchema])\n } else {\n schemaMap.delete(pathKey)\n }\n if (currentUser !== undefined && currentUser.length > 0) {\n userMap.set(pathKey, [...currentUser])\n } else {\n userMap.delete(pathKey)\n }\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form+errors', schemaMap, userMap, transientSet)\n )\n }\n\n /**\n * Wipe the persisted entry. Without `path`, removes the whole key.\n * With `path`, deletes only that subpath (and any matching error\n * entries) and writes back; the entry is removed entirely if the\n * resulting form value is empty.\n */\n async function clearPersistedDraft(path?: Path): Promise<void> {\n if (disposed) return\n await writer.flush()\n if (disposed) return\n const adapter = await adapterPromise\n if (disposed) return\n if (path === undefined) {\n await adapter.removeItem(key)\n return\n }\n const raw = await adapter.getItem(key)\n const existing = readPersistedPayload<F>(raw)\n if (existing === null) return\n const nextForm = deleteAtPath(existing.data.form, path) as F\n if (isEmptyContainer(nextForm)) {\n await adapter.removeItem(key)\n return\n }\n const { key: pathKey } = canonicalizePath(path)\n // Drop the cleared path AND every descendant from the persisted\n // blank list so a later mount doesn't restore an\n // \"empty\" UI state for a path that no longer has any value\n // behind it. Non-leaf clears (`clearPersistedDraft('user')`)\n // wipe the whole user.* subtree.\n const transientSet = new Set(\n (existing.data.blankPaths ?? []).filter(\n (k) => k !== pathKey && !isDescendantPathKey(k, pathKey)\n )\n )\n if (include === 'form') {\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form', new Map(), new Map(), transientSet)\n )\n return\n }\n const schemaErrors = (existing.data.schemaErrors ?? []).filter(([k]) => k !== pathKey)\n const userErrors = (existing.data.userErrors ?? []).filter(([k]) => k !== pathKey)\n const schemaMap = new Map<string, ValidationError[]>(schemaErrors.map(([k, v]) => [k, [...v]]))\n const userMap = new Map<string, ValidationError[]>(userErrors.map(([k, v]) => [k, [...v]]))\n await adapter.setItem(\n key,\n buildPersistedPayload<F>(nextForm, 'form+errors', schemaMap, userMap, transientSet)\n )\n }\n\n function awaitPendingWrites(): Promise<void> {\n // If dispose() already kicked off the final flush, return THAT\n // promise so the registry awaits the same drain instead of\n // scheduling a parallel one.\n if (inFlightFinalFlush !== null) return inFlightFinalFlush\n if (disposed) return Promise.resolve()\n return writer.flush().catch(() => undefined)\n }\n\n function dispose(): void {\n if (disposed || inFlightFinalFlush !== null) return\n unsubscribeChange()\n unsubscribeSuccess()\n // CRITICAL: flush BEFORE flipping `disposed`. The previous order\n // (set disposed=true, then call writer.flush()) caused the writer\n // closure to bail immediately, silently dropping the last\n // keystroke whenever a component unmounted within the debounce\n // window. Now we kick off the flush, then flip `disposed` only\n // after the in-flight write finishes.\n inFlightFinalFlush = writer\n .flush()\n .catch(() => undefined)\n .finally(() => {\n disposed = true\n inFlightFinalFlush = null\n })\n // Fire-and-forget — `awaitPendingWrites` exposes the promise for\n // callers that need to drain (the registry on consumer-eviction;\n // SSR shutdown).\n void inFlightFinalFlush\n }\n\n return {\n writePathImmediately,\n clearPersistedDraft,\n awaitPendingWrites,\n dispose,\n }\n}\n\n/**\n * Treat `null`, `undefined`, `[]`, and `{}` as \"nothing left to keep.\"\n * Used by `clearPersistedDraft(path)` to decide whether to wipe the\n * entire entry instead of writing a hollow envelope back.\n */\nfunction isEmptyContainer(value: unknown): boolean {\n if (value === undefined || value === null) return true\n if (Array.isArray(value)) return value.length === 0\n if (isPlainRecord(value)) return Object.keys(value).length === 0\n return false\n}\n\n/**\n * Tracks the FormStore identities the anon-persist warn already\n * fired for in production. Dev-mode throws (via AnonPersistError)\n * don't need a dedupe set — the throw aborts the call before\n * subsequent identical calls can land.\n */\nconst warnedAnonPersistKeys: Set<string> = new Set<string>()\n\n/**\n * Anonymous + `persist:` is unsafe by construction: the synthetic\n * `__atta:anon:<id>` identity drifts on every remount (Vue's `useId()`\n * allocator is per-app and per-tree-position; HMR rebuilds the\n * instance) AND can collide between two unrelated anon forms that\n * happen to land on the same id. With matching schemas + backend,\n * the second form would read the first's draft and write back over\n * it — actual cross-form data leakage, not just stale entries.\n *\n * Two-tier handling:\n * - **Dev** (`__DEV__` true): throw `AnonPersistError`. Hard-fails\n * the call at the offending useForm() site.\n * - **Prod**: one-shot `console.warn` + return `true` so the\n * caller skips persistence wiring entirely. A deployed app\n * shipping the anti-pattern shouldn't hard-crash, but it also\n * shouldn't silently mis-route data — disabling the mechanism\n * is the safe failure.\n *\n * Returns `true` when persistence MUST be skipped (anon + persist).\n */\nfunction enforceAnonPersistRule(formKey: string, ssr: boolean): boolean {\n if (!formKey.startsWith(ANONYMOUS_FORM_KEY_PREFIX)) return false\n if (__DEV__)\n throw new AnonPersistError({\n cause: 'no-key',\n callSite: captureUserCallSite(),\n })\n // Production: warn + tell the caller to skip wiring. Client-only\n // warn (skip server logs to avoid spamming SSR per-request output).\n // Persist is still skipped on the SSR pass — same disabling\n // outcome — just without the log noise.\n if (!ssr && !warnedAnonPersistKeys.has(formKey)) {\n warnedAnonPersistKeys.add(formKey)\n console.warn(\n \"[attaform] persist: ignored — anonymous useForm() can't safely persist \" +\n '(key drift + cross-form collision risk).\\n' +\n ' Persistence is disabled for this form; the app keeps working.\\n' +\n \" Fix: useForm({ schema, key: 'login', persist: '...' })\"\n )\n }\n return true\n}\n\n/**\n * Walk a sparse persisted form and collect the canonical PathKey of\n * every leaf. \"Leaf\" = anything that isn't a plain object or array\n * (so primitives, null, deserialized Dates / strings all count). The\n * persisted form's leaves correspond 1:1 with the per-element opt-in\n * scope at the time persistence wrote, which the hydration path uses\n * to bound which blank entries to overwrite.\n */\nfunction collectPersistedLeafPaths(form: unknown): PathKey[] {\n const out: PathKey[] = []\n walk(form, [])\n return out\n\n function walk(node: unknown, prefix: Path): void {\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n walk(node[i], [...prefix, i])\n }\n return\n }\n if (isPlainRecord(node)) {\n for (const key of Object.keys(node)) {\n walk((node as Record<string, unknown>)[key], [...prefix, key])\n }\n return\n }\n if (prefix.length === 0) return // root scalar — no path to canonicalize\n out.push(canonicalizePath(prefix).key)\n }\n}\n\n/**\n * `true` when `candidate` names a strict descendant of `ancestor` in\n * canonical PathKey form (`JSON.stringify(segments)`).\n *\n * `'[\"user\"]'` is the ancestor; `'[\"user\",\"age\"]'` and\n * `'[\"user\",\"address\",\"line1\"]'` are descendants. A pure prefix match\n * isn't enough — `'[\"userId\"]'` shares the `'[\"user'` prefix with\n * `'[\"user\"]'` but is not a descendant. The check anchors on the\n * comma that separates the parent's last segment from its first\n * child segment.\n */\nfunction isDescendantPathKey(candidate: string, ancestor: string): boolean {\n if (candidate.length <= ancestor.length) return false\n if (!ancestor.endsWith(']')) return false\n const childPrefix = `${ancestor.slice(0, -1)},`\n return candidate.startsWith(childPrefix)\n}\n\nexport type { FieldState }\n","import { getCurrentInstance, getCurrentScope, inject, onScopeDispose, useId } from 'vue'\nimport { buildFormApi } from '../core/build-form-api'\nimport type { FormStore } from '../core/create-form-store'\nimport { __DEV__ } from '../core/dev'\nimport { captureUserCallSite } from '../core/dev-stack-trace'\nimport type { HistoryModule } from '../core/history'\nimport { ensureAttaformInstalled } from '../core/plugin'\nimport { kFormContext, kFormInstanceId, useRegistry, type AttaformRegistry } from '../core/registry'\nimport type { FormKey, UseFormReturnType } from '../types/types-api'\nimport type { GenericForm } from '../types/types-core'\nimport { ambientProvideHistory } from './use-abstract-form'\n\n/**\n * Module-local counter for the test/ad-hoc fallback when neither an\n * ambient `kFormInstanceId` provide nor a Vue instance is available.\n * Uniqueness is sufficient — these consumers don't share an\n * `instanceId` with anything else in the tree by definition.\n */\nlet injectedInstanceCounter = 0\n\n/**\n * Access an existing form from a descendant component without passing\n * it through props. Counterpart to `useForm` — `useForm` creates and\n * provides; `injectForm` looks up via Vue's inject mechanism.\n *\n * Two ways to call it:\n *\n * ```ts\n * // Reach the nearest ancestor's anonymous useForm() call.\n * const form = injectForm<SignupShape>()\n *\n * // Reach a specific form by its key — works from anywhere in the app.\n * const cart = injectForm<CartShape>('cart')\n * ```\n *\n * Resolution rules (no-key form):\n * - Closest ambient ancestor wins.\n * - Only anonymous `useForm()` (no `key`) fills the ambient slot;\n * keyed forms are reachable only via `injectForm(key)`.\n * - Inherits the resolved ancestor's `formInstanceId`.\n *\n * Resolution rules (keyed form): registry lookup by string key,\n * independent of component-tree position.\n *\n * Returns `null` when no matching form exists (no ambient ancestor, or\n * the named key isn't registered). A dev-mode warning points at the\n * call site to help diagnose typos. Always narrow before using:\n *\n * ```ts\n * const form = injectForm<Shape>('signup')\n * if (!form) return\n * form.register('email')\n * ```\n *\n * Pass the `Form` generic explicitly — Vue's provide/inject erases\n * generics, so the library can't recover the shape automatically.\n *\n * The form is kept alive for this component's lifetime; once every\n * consumer unmounts, the form is cleaned up automatically.\n */\nexport function injectForm<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(\n key?: FormKey\n): UseFormReturnType<Form, GetValueFormType> | null {\n // Lazy-install: if no `useForm` ancestor and no explicit\n // `createAttaform()`, the registry is missing. Auto-install here so\n // `injectForm` collapses to its existing \"no form for that key\" /\n // \"no ambient form context\" null-return + dev-warning paths instead\n // of throwing the misleading `RegistryNotInstalledError`. The strict\n // `useRegistry()` below still surfaces `OutsideSetupError` when\n // called outside setup.\n const instance = getCurrentInstance()\n if (instance !== null) ensureAttaformInstalled(instance.appContext.app)\n const registry = useRegistry()\n\n const state = resolveState<Form>(key, registry)\n if (state === null) return null\n\n // Ref-count this consumer so the FormStore survives until every nested\n // component that reached it has torn down. Mirrors the behaviour in\n // useAbstractForm — see registry.trackConsumer for the counter semantics.\n if (getCurrentScope() !== undefined) {\n const releaseConsumer = registry.trackConsumer(state.formKey)\n onScopeDispose(releaseConsumer)\n }\n\n // Pull the cached history module (if the owning `useForm` wired it)\n // so every consumer's API surface includes `undo` / `redo` / `canUndo`\n // / `canRedo` / `historySize`. Without this, consumers reached via\n // the context would receive inert stubs even when history is enabled\n // on the form.\n const apiOptions: Parameters<typeof buildFormApi<Form, GetValueFormType>>[2] = {}\n const history = state.modules.get('history') as HistoryModule | undefined\n if (history !== undefined) {\n apiOptions.history = history\n }\n // Inherit the ancestor `useForm()`'s instanceId when one is provided.\n // Keeps parent-submit-focus working for inputs registered by deep\n // children using `injectForm()` + their own local `register()` calls\n // — both sides tag against the SAME instance.\n //\n // Falls back to a fresh ID when:\n // - `injectForm('cart')` reaches a form by key from a tree branch\n // that has no ambient provide chain to it (cross-tree access);\n // - or no Vue instance is available (test / ad-hoc usage).\n // In those cases the consumer's local registrations are isolated —\n // the original `useForm()` callsite's `focusFirstError` won't see\n // them, but the consumer's own focus calls work locally.\n const ambientInstanceId = getCurrentInstance() !== null ? inject(kFormInstanceId, null) : null\n const formInstanceId =\n ambientInstanceId ??\n (getCurrentInstance() !== null\n ? useId()\n : `atta:form-instance-injected:${injectedInstanceCounter++}`)\n return buildFormApi<Form, GetValueFormType>(state, formInstanceId, apiOptions)\n}\n\n/**\n * Resolves the FormStore for the requested key (or the ambient slot\n * when no key was passed). Returns `null` on miss; the caller propagates\n * that null straight out to the consumer.\n *\n * Both miss modes log a dev-mode warning carrying the user's call-site\n * frame — a typo'd key reads as \"[attaform] injectForm: no form registered\n * for key 'userz'. Returning null. (pages/profile.vue:42)\" rather than\n * as a stack trace from inside attaform internals.\n */\nfunction resolveState<Form extends GenericForm>(\n key: FormKey | undefined,\n registry: AttaformRegistry\n): FormStore<Form> | null {\n if (key !== undefined) {\n const stored = registry.forms.get(key) as FormStore<Form> | undefined\n if (stored === undefined) {\n warnMiss(`no form registered for key '${key}'`, registry.ssr)\n return null\n }\n return stored\n }\n const ambient = inject(kFormContext, null) as FormStore<Form> | null\n if (ambient === null) {\n warnMiss('no ambient form context', registry.ssr)\n return null\n }\n warnIfAmbientProviderHadDuplicates()\n return ambient\n}\n\n/**\n * Skipped on SSR — Nuxt's `dev:ssr-logs` hook forwards server warns to\n * the browser console alongside the client-side warn that fires from\n * the hydration setup, so the same miss would surface twice per page\n * load. The signal is identical on both passes (registry state is\n * deterministic across SSR/client), so emitting only on the client is\n * lossless and halves dev-mode noise. Production stays silent on both.\n */\nfunction warnMiss(detail: string, ssr: boolean): void {\n if (!__DEV__ || ssr) return\n const frame = captureUserCallSite()\n console.warn(\n `[attaform] injectForm: ${detail}. Returning null.` + (frame !== undefined ? ` ${frame}` : '')\n )\n}\n\n/**\n * Walk up from the current component to the nearest ancestor that\n * registered an ambient provide (tracked in `ambientProvideHistory`).\n * If that ancestor recorded more than one ANONYMOUS `useForm()` call,\n * a descendant reaching for the ambient slot only sees the last one\n * — warn so the author picks between adding a key and splitting the\n * component.\n *\n * The eager version of this check lived at the `useForm()` call site\n * and fired once per extra form regardless of whether any descendant\n * actually used the ambient slot. That made spike / test pages wall-\n * warn for a non-problem; this version fires at most once per\n * `injectForm()` consumer that genuinely collides.\n *\n * Keyed `useForm()` calls don't appear here — they don't fill the\n * ambient slot at all (they're addressable explicitly via\n * `injectForm<F>(key)`), so they can't collide with each other\n * or with anonymous siblings on this axis.\n */\nfunction warnIfAmbientProviderHadDuplicates(): void {\n if (!__DEV__ || ambientProvideHistory === null) return\n let ancestor = getCurrentInstance()?.parent ?? null\n while (ancestor !== null) {\n const history = ambientProvideHistory.get(ancestor as unknown as object)\n if (history !== undefined) {\n if (history.length > 1) {\n const lines = history.map((entry) => ` - ${entry.source ?? '<unknown location>'}`)\n console.warn(\n '[attaform] injectForm<F>() (no key) resolved against ' +\n 'an ancestor with multiple anonymous useForm() calls; descendants ' +\n 'only see the last-provided form. Anonymous useForm() calls were:\\n' +\n lines.join('\\n') +\n '\\nFix: pass a key to each call (e.g. useForm({ schema, key: \"x\" })) ' +\n 'and reach them via injectForm<F>(\"x\"), or split the forms ' +\n 'across separate components.'\n )\n }\n return\n }\n ancestor = ancestor.parent\n }\n}\n"],"names":["out","arr","rec","childRoot","cursorRecord","walk","shouldWarnOnce","walked","ok","segments","options","currentValue","memoryForUnion","parentKey"],"mappings":";;;;AA4BA,SAAS,cAAc,KAAA,EAAuE;AAC5F,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AACxD,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,KAAK,CAAA;AACzC,EAAA,OAAO,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,CAAO,SAAA;AAC5C;AAEA,SAAS,aAAA,CAAc,QAAc,OAAA,EAAwB;AAC3D,EAAA,MAAM,IAAA,GAAkB,IAAI,KAAA,CAAe,MAAA,CAAO,SAAS,CAAC,CAAA;AAC5D,EAAA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