formstand 0.25.0 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +205 -0
- package/dist/chunk-XJ6W5CKB.js +22 -0
- package/dist/chunk-XJ6W5CKB.js.map +1 -0
- package/dist/{createForm-CMVALnc3.d.cts → createForm-BXDd9Tg4.d.cts} +18 -7
- package/dist/{createForm-CMVALnc3.d.ts → createForm-BXDd9Tg4.d.ts} +18 -7
- package/dist/devtools/index.cjs +40 -56
- package/dist/devtools/index.cjs.map +1 -1
- package/dist/devtools/index.js +41 -23
- package/dist/devtools/index.js.map +1 -1
- package/dist/index.cjs +535 -163
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -11
- package/dist/index.d.ts +30 -11
- package/dist/index.js +682 -158
- package/dist/index.js.map +1 -1
- package/dist/testing/index.cjs +7 -11
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +4 -4
- package/dist/testing/index.d.ts +4 -4
- package/dist/testing/index.js +7 -11
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-EQIS5IVH.js +0 -172
- package/dist/chunk-EQIS5IVH.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/array.ts","../src/core/arrayOpLog.ts","../src/core/equality.ts","../src/core/env.ts","../src/core/maps.ts","../src/core/path.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/mode.ts","../src/core/debounce.ts","../src/core/persist.ts","../src/react/usePersistForm.ts","../src/react/useForm.ts","../src/react/inputProps.ts","../src/react/useMaskedInput.ts","../src/react/useFormSelector.ts","../src/react/useFormSteps.ts","../src/react/useFormAction.ts","../src/react/FormContext.tsx","../src/react/useField.ts","../src/react/useVariantField.ts","../src/react/useFieldArray.ts","../src/react/useVariantFieldArray.ts","../src/react/useFormError.ts","../src/react/useFormValues.ts","../src/react/useFields.ts","../src/react/useFormFlags.ts","../src/react/createFormHooks.ts","../src/react/fields.tsx","../src/react/focusError.ts"],"names":["key","containerKindAt","z","inner","createStore","devtools","useRef","useEffect","useMemo","useState","useStore","useShallow","useCallback","useActionState","createContext","jsx","useContext","initialValue","validateAsync","useId","jsxs","Fragment"],"mappings":";;;;;;;;;;;;;AAEO,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI,IAAA,GAAO,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA;AAE9B,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,MACC,CAAA,IAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAEd,IAAM,UAAA,GACX,CAAC,IAAA,EAAc,EAAA,KACf,CAAC,CAAA,KAAM;AACL,EAAA,IAAI,CAAA,KAAM,MAAM,OAAO,EAAA;AACvB,EAAA,IAAI,OAAO,EAAA,IAAM,CAAA,GAAI,QAAQ,CAAA,IAAK,EAAA,SAAW,CAAA,GAAI,CAAA;AACjD,EAAA,IAAI,OAAO,EAAA,IAAM,CAAA,IAAK,MAAM,CAAA,GAAI,IAAA,SAAa,CAAA,GAAI,CAAA;AACjD,EAAA,OAAO,CAAA;AACT,CAAA;AAEK,IAAM,WAAA,GACX,CAAC,CAAA,EAAW,CAAA,KACZ,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI,CAAA,GAAI,CAAA,KAAM,CAAA,GAAI,CAAA,GAAI,CAAA;AAOzB,IAAM,YAAA,GAAe,CAC1B,MAAA,EACA,SAAA,EACA,SAAA,KACsB;AACtB,EAAA,MAAM,WAAW,IAAI,GAAA;AAAA,IACnB,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,SAAA,IAAa,CAAC,CAAA,EAAG,QAAA,KAAa,QAAQ,CAAA,CAAE,OAAA;AAAA,MAC3D,CAAC,QAAA,KAAa;AACZ,QAAA,MAAM,QAAA,G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,mBAAA,GACJ,iBACC,IAAA,KAAS,MAAA,IAAa,SAAS,gBAAA,CAAiB,MAAM,EAAE,MAAA,IAAU,CAAA,CAAA;AACrE,EAAA,MAAM,UAAA,GACJ,YAAA,CAAa,MAAA,GAAS,CAAA,GAClB,YAAA,GACA,sBACE,QAAA,CAAS,MAAA,CAAO,gBAAgB,CAAA,GAChC,EAAC;AACT,EAAA,OAAO,aAAa,UAAU,CAAA;AAChC;AAyBO,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,IAAA,KAA+B;AACtE,EAAA,MAAM,QAAQ,IAAA,IAAQ,QAAA;AACtB,EAAA,OAAO,IAAA,KAAS,EAAA,GAAA,CACX,IAAA,KAAS,MAAA,IACR,QAAA,CAAS,gBAAA,CAAiB,MAAM,CAAA,CAAE,MAAA,IAAU,CAAA,KAC5C,YAAA,CAAa,aAAA,CAAc,KAAK,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA,GAC5D,YAAA,CAAa,cAAA,CAAe,KAAA,EAAO,CAAC,IAAI,CAAC,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA;AACzE","file":"index.cjs","sourcesContent":["export type IndexMapper = (oldIndex: number) => number | null;\n\nexport const removeAt =\n (i: number): IndexMapper =>\n (n) =>\n n === i ? null : n > i ? n - 1 : n;\n\nexport const insertAt =\n (i: number): IndexMapper =>\n (n) =>\n n >= i ? n + 1 : n;\n\nexport const moveFromTo =\n (from: number, to: number): IndexMapper =>\n (n) => {\n if (n === from) return to;\n if (from < to && n > from && n <= to) return n - 1;\n if (from > to && n >= to && n < from) return n + 1;\n return n;\n };\n\nexport const swapIndices =\n (a: number, b: number): IndexMapper =>\n (n) =>\n n === a ? b : n === b ? a : n;\n\n// The new-index → old-index view of an op, materialized as an array (-1\n// marks a position with no old index: a freshly created row). Derived by\n// INVERTING the op's IndexMapper — the same mapper trusted to re-key\n// errors/touched — so the value transform and the id mapping cannot\n// diverge. Consumed by the array-op log for row-id derivation.\nexport const invertMapper = (\n mapper: IndexMapper,\n oldLength: number,\n newLength: number,\n): readonly number[] => {\n const oldByNew = new Map(\n Array.from({ length: oldLength }, (_, oldIndex) => oldIndex).flatMap(\n (oldIndex) => {\n const newIndex = mapper(oldIndex);\n return newIndex === null ? [] : ([[newIndex, oldIndex]] as const);\n },\n ),\n );\n return Array.from(\n { length: newLength },\n (_, newIndex) => oldByNew.get(newIndex) ?? -1,\n );\n};\n\nconst indexAndTail = (\n rest: string,\n): Readonly<{ index: number; tail: string }> | null => {\n const dotIdx = rest.indexOf(\".\");\n const idxStr = dotIdx === -1 ? rest : rest.slice(0, dotIdx);\n const tail = dotIdx === -1 ? \"\" : rest.slice(dotIdx);\n const idx = Number(idxStr);\n if (!Number.isInteger(idx) || idx < 0 || String(idx) !== idxStr) return null;\n return { index: idx, tail };\n};\n\nexport const reKeyByArrayPath = <V>(\n map: Readonly<Record<string, V>>,\n basePath: string,\n mapper: IndexMapper,\n): Readonly<Record<string, V>> => {\n const prefix = basePath === \"\" ? \"\" : `${basePath}.`;\n return Object.fromEntries(\n Object.entries(map).flatMap(([key, value]) => {\n if (key === basePath) return [[key, value]];\n if (!key.startsWith(prefix)) return [[key, value]];\n const parsed = indexAndTail(key.slice(prefix.length));\n if (parsed === null) return [[key, value]];\n const next = mapper(parsed.index);\n if (next === null) return [];\n return [[`${prefix}${next}${parsed.tail}`, value]];\n }),\n );\n};\n","// A per-store, per-path log of recent array ops, recorded by the core's\n// applyArrayOp and replayed by useFieldArray's row-id derivation. The ops\n// carry the EXACT new→old index mapping, so id derivation never has to\n// guess which of two Object.is-equal rows an op removed or moved — the one\n// case value-based reconciliation cannot decide. A sanctioned mutable-ref\n// cache (like the core's subschemaCache): the log is derived bookkeeping,\n// never part of form state, and the WeakMap releases it with the store.\n\nexport type ArrayOpRecord = Readonly<{\n // The array value the op consumed / produced — reference identity is the\n // chain link: a consumer replays from the record whose `from` matches its\n // last-seen array, on through consecutive records, until it reaches the\n // live array (or gives up and falls back to value reconciliation).\n from: readonly unknown[];\n to: readonly unknown[];\n // newIndex → oldIndex; -1 marks a freshly created row.\n mapping: readonly number[];\n}>;\n\n// Bounded two ways, both loss-limited: a path's record COUNT is capped by\n// COMPOSING its two oldest records into one when consecutive (op mappings\n// compose, so an arbitrarily long run of consecutive ops stays fully\n// replayable in OP_LOG_LIMIT records; only a chain already broken by an\n// external write drops its dead head) — and a store accumulating more than\n// MAX_LOG_PATHS distinct array paths (dynamic row paths on a long-lived\n// singleton form) evicts its oldest path's records, degrading that path to\n// value reconciliation.\nconst OP_LOG_LIMIT = 16;\nconst MAX_LOG_PATHS = 256;\n\n// (second ∘ first): newIndex → the FIRST record's old index. A -1 anywhere\n// along the way stays -1 (the row was created inside the composed span).\nconst composeOps = (\n first: ArrayOpRecord,\n second: ArrayOpRecord,\n): ArrayOpRecord => ({\n from: first.from,\n to: second.to,\n mapping: second.mapping.map((mid) =>\n mid === -1 ? -1 : (first.mapping[mid] ?? -1),\n ),\n});\n\nconst logs = new WeakMap<object, Map<string, readonly ArrayOpRecord[]>>();\n\n// Cap a path's record count, composing the two oldest records when they are\n// consecutive (lossless) and dropping the dead head otherwise. The slice\n// work only happens on overflow — the common case appends untouched.\nconst boundOps = (\n ops: readonly ArrayOpRecord[],\n): readonly ArrayOpRecord[] => {\n const [head, second] = ops;\n if (ops.length <= OP_LOG_LIMIT || head === undefined || second === undefined) {\n return ops;\n }\n return head.to === second.from\n ? [composeOps(head, second), ...ops.slice(2)]\n : ops.slice(1);\n};\n\nexport const recordArrayOp = (\n store: object,\n path: string,\n record: ArrayOpRecord,\n): void => {\n const existing = logs.get(store);\n const byPath = existing ?? new Map<string, readonly ArrayOpRecord[]>();\n if (existing === undefined) logs.set(store, byPath);\n const bounded = boundOps([...(byPath.get(path) ?? []), record]);\n byPath.delete(path);\n byPath.set(path, bounded);\n if (byPath.size > MAX_LOG_PATHS) {\n const oldest = byPath.keys().next().value;\n if (oldest !== undefined) byPath.delete(oldest);\n }\n};\n\nexport const arrayOpsFor = (\n store: object,\n path: string,\n): readonly ArrayOpRecord[] => logs.get(store)?.get(path) ?? [];\n\n// Drop a path's records — called by the consumer after a walk consumed them\n// (the log is per-batch bookkeeping, spent once derived).\nexport const clearArrayOps = (store: object, path: string): void => {\n logs.get(store)?.delete(path);\n};\n\n// Drop the records of the written path and its DESCENDANTS — the paths\n// where a value write can reintroduce a previously-seen array reference\n// (the caller supplies the subtree's values; reset/restore reinstate stored\n// ones; an array op re-seats existing descendant arrays under new indices),\n// which stale records could falsely chain against. Ancestor paths are\n// deliberately KEPT: setAtPath always builds fresh spine arrays, so an\n// ancestor reference can never recur — and an ancestor's earlier records\n// are real history the id walk still replays, bridging the gap this write\n// created. \"\" (whole-values writes) clears all. `keepSelf` is for\n// applyArrayOp itself: the op's own path is exactly what it is about to\n// record, and its earlier same-batch records still chain.\nexport const clearArrayOpsUnder = (\n store: object,\n path: string,\n keepSelf = false,\n): void => {\n const byPath = logs.get(store);\n if (byPath === undefined) return;\n if (path === \"\") {\n byPath.clear();\n return;\n }\n const related = [...byPath.keys()].filter(\n (p) => (p === path && !keepSelf) || p.startsWith(`${path}.`),\n );\n related.forEach((p) => byPath.delete(p));\n};\n","export const isPlainObject = (v: unknown): v is Record<string, unknown> => {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n};\n\n// Structural equality used to decide whether a field still matches its initial\n// value. Recurses into arrays and plain objects; Dates compare by timestamp\n// (re-picking the same date must not leave the field permanently dirty);\n// other exotic objects fall back to Object.is so a real change is never\n// mistaken for \"unchanged\".\nexport const valuesEqual = (a: unknown, b: unknown): boolean => {\n if (Object.is(a, b)) return true;\n // Numbers compare with `===` semantics on top of Object.is: Object.is\n // alone keeps NaN equal to itself (wanted) but tells -0 from 0, and a\n // number input renders both as \"0\", so a field holding -0 against an\n // initial 0 read as permanently dirty with nothing visible to undo.\n if (typeof a === \"number\" && typeof b === \"number\") return a === b;\n if (a instanceof Date && b instanceof Date) {\n // Two invalid Dates are equal: their timestamps are both NaN, which\n // `===` denies, so a cleared or half-typed date against an invalid\n // initial read as dirty forever.\n const [ta, tb] = [a.getTime(), b.getTime()];\n return ta === tb || (Number.isNaN(ta) && Number.isNaN(tb));\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => valuesEqual(v, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n // hasOwn matters: equal counts don't imply equal key SETS. Without it,\n // { realname: undefined } vs { nickname: \"Ann\" } passes (1 === 1, and\n // a.realname === missing b.realname === undefined) without b's real key\n // ever being inspected — dirty tracking would read a real change as\n // clean. With hasOwn plus the length check the key sets must match, so\n // the compare is also symmetric.\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((k) => Object.hasOwn(b, k) && valuesEqual(a[k], b[k]))\n );\n }\n return false;\n};\n\n// The deep compare for a container-valued field runs inside store selectors\n// and watch subscriptions, i.e. on every store change — cache verdicts per\n// value object, keyed by the initial-slice reference each was computed for.\n// A small list (not a single slot) so distinct fields/forms sharing one value\n// object (a module-level default, a shared sentinel array) coexist instead of\n// evicting each other; bounded so no entry grows without limit. Form state is\n// immutable, so identical references always mean an identical verdict, and\n// the WeakMap releases everything when the value object dies.\ntype DirtyVerdict = Readonly<{ initial: unknown; dirty: boolean }>;\nconst dirtyCache = new WeakMap<object, readonly DirtyVerdict[]>();\nconst MAX_VERDICTS = 4;\n\n// The single definition of dirtiness: the current value slice differs\n// structurally from its initial-values slice. Derived (rather than tracked by\n// writers) so reads are accurate at any depth.\nexport const isFieldDirty = (value: unknown, initialValue: unknown): boolean => {\n if (Object.is(value, initialValue)) return false;\n if (typeof value !== \"object\" || value === null) {\n return !valuesEqual(value, initialValue);\n }\n const cached = dirtyCache.get(value) ?? [];\n const hit = cached.find((v) => Object.is(v.initial, initialValue));\n if (hit !== undefined) return hit.dirty;\n const dirty = !valuesEqual(value, initialValue);\n dirtyCache.set(\n value,\n [{ initial: initialValue, dirty }, ...cached].slice(0, MAX_VERDICTS),\n );\n return dirty;\n};\n","// The dev-build test the library consults before emitting a console\n// warning. Bundlers that define NODE_ENV fold it to a constant and drop the\n// dev-only branches; the `typeof process` guard keeps the SAME expression\n// from throwing in a runtime that defines no `process` at all (a CDN/ESM\n// consumer, a test runner without the define). That last case matters most\n// on the submit path: handleSubmit promises never to reject, and the\n// warning that fires only when a save failed was the one line that could\n// break the promise exactly on the failure path. It FAILS OPEN on purpose:\n// an unknowable environment gets the warnings, which cost nothing but a\n// console line.\nexport const isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\n\n// The gate for the two sites that EXPOSE form state: the FormstandDevtools\n// panel (renders every value and error into the page) and the zustand\n// devtools middleware (streams every write to the Redux extension). These\n// must FAIL CLOSED: isDevBuild's \"no process means dev\" reading let a\n// CDN/ESM, Deno, or worker production build mount the panel and keep the\n// middleware live for any end user with the extension installed. Only a\n// readable NODE_ENV that is a string other than \"production\" counts as\n// development; no process, no env, or an unset NODE_ENV all read as\n// production here.\nexport const isDevToolsBuild = (): boolean => {\n if (typeof process === \"undefined\") return false;\n const env = process.env?.[\"NODE_ENV\"];\n return typeof env === \"string\" && env !== \"production\";\n};\n","import type { BoolMap } from \"./types\";\n\n// Own-key reads for the path-keyed maps (errors, touched, isValidating).\n// Their keys are user-controlled strings: a schema may declare a field\n// named `constructor`, a server response may name `toString`, and\n// JSON.parse yields own `__proto__` keys. A bare `map[key]` on a plain\n// object walks the prototype chain for those, so an EMPTY error map read\n// `Object` as the error list at \"constructor\" (and `stringArraysEqual`\n// then threw inside setState on `.every`), while `touched[\"toString\"]` was\n// a truthy function. Every read of these maps by a runtime key goes\n// through here; writes are already safe (computed keys and\n// Object.fromEntries define own properties).\nexport const entryAt = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): V | undefined => (Object.hasOwn(map, key) ? map[key] : undefined);\n\nexport const flagAt = (map: BoolMap, key: string): boolean =>\n Object.hasOwn(map, key) && map[key] === true;\n","import { isPlainObject } from \"./equality\";\n\nexport type PathSegment = string | number;\n\n// What setAtPath creates at an ABSENT slot. The segment type alone cannot\n// tell a z.record keyed by numeric strings from an array (both read\n// \"lookup.0\"), so a caller that knows the schema hands in a resolver; it\n// answers for the dotted prefix being created and returns null where it\n// has no opinion, which falls back to the segment-type rule.\nexport type ContainerKind = \"array\" | \"record\";\nexport type ContainerKindAt = (prefix: string) => ContainerKind | null;\n\n// Segment keys containing \".\" are not addressable (paths are split on dots);\n// use nested objects or index-free keys instead.\n\n// Writes above this index are refused — a typo'd path like \"items.4294967296\"\n// must not allocate a multi-gigabyte array.\nconst MAX_ARRAY_INDEX = 100_000;\n\nconst isIndexSegment = (s: string): boolean => {\n const n = Number(s);\n return Number.isInteger(n) && n >= 0 && String(n) === s;\n};\n\n// Hot path: every field subscription re-resolves its path on every store\n// notification (getAtPath in selectors), so parsing is memoized — a form's\n// paths are a small fixed set. Bounded as an LRU over Map insertion order:\n// a hit re-inserts its key (moving it to the back) and an overflow evicts\n// the front, so an app whose LIVE path set exceeds the cap keeps its hot\n// paths cached instead of re-parsing every one of them after each reset\n// (the old wholesale clear). Eviction only costs re-parsing, never\n// correctness. Same delete-then-set recency idiom as useFieldArray's\n// per-path id cache.\nconst PARSE_CACHE_MAX = 4096;\nconst parseCache = new Map<string, readonly PathSegment[]>();\n\nexport const parsePath = (path: string): readonly PathSegment[] => {\n const cached = parseCache.get(path);\n if (cached !== undefined) {\n parseCache.delete(path);\n parseCache.set(path, cached);\n return cached;\n }\n // Frozen because the array is now SHARED across every caller (and cached):\n // parsePath is a public export, and pre-cache each call returned a private\n // array that was safe to mutate. Freezing enforces the `readonly` type at\n // runtime so an external `.sort()`/`.reverse()`/`.push()` throws instead of\n // silently corrupting the cache for every later lookup of this path.\n const segments = Object.freeze(\n path === \"\"\n ? []\n : path.split(\".\").map((s) => (isIndexSegment(s) ? Number(s) : s)),\n );\n if (parseCache.size >= PARSE_CACHE_MAX) {\n const oldest = parseCache.keys().next().value;\n if (oldest !== undefined) parseCache.delete(oldest);\n }\n parseCache.set(path, segments);\n return segments;\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n// The existing container decides how a segment is interpreted: arrays take\n// numeric segments as indices, records take any segment as a string key (so a\n// z.record keyed \"0\" reads/writes the record key, not an array index). Only\n// when the container is absent does the segment type pick what gets created.\nconst readSegment = (obj: unknown, segment: PathSegment): unknown => {\n if (obj == null) return undefined;\n if (Array.isArray(obj)) {\n return typeof segment === \"number\" ? obj[segment] : undefined;\n }\n // Own properties only: a runtime-built path like \"lookup.constructor\" on a\n // z.record must read as absent, not leak Object.prototype members as field\n // values.\n return isPlainRecord(obj) && Object.hasOwn(obj, String(segment))\n ? obj[String(segment)]\n : undefined;\n};\n\nexport const getAtPath = (obj: unknown, path: string): unknown =>\n parsePath(path).reduce<unknown>(readSegment, obj);\n\nexport type SlotAtPath =\n | Readonly<{ exists: true; value: unknown }>\n | Readonly<{ exists: false }>;\n\n// Resolve `path` while checking that every segment is read from a real\n// container: an in-range array index, or a key on a plain record (containers\n// decide, mirroring readSegment). A segment into an absent or non-container\n// value addresses no slot at all — a full-form parse would key that error at\n// the missing ANCESTOR, not here, so field-scoped validation must skip it\n// rather than parse the leaf's subschema against undefined (which would\n// fabricate a spurious \"required\" error the full pass never produces). Note\n// this checks the CONTAINER, not the value: a leaf that is undefined at the\n// FINAL step through a real record is still an addressable (legitimately\n// empty) slot. Returns the resolved value so callers don't walk twice.\nexport const slotAtPath = (obj: unknown, path: string): SlotAtPath => {\n const walked = parsePath(path).reduce<\n Readonly<{ ok: boolean; current: unknown }>\n >(\n (acc, segment) => {\n const container = acc.current;\n const addressable =\n typeof segment === \"number\"\n ? Array.isArray(container)\n ? segment < container.length\n : isPlainRecord(container)\n : isPlainRecord(container);\n return !acc.ok || !addressable\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n );\n return walked.ok ? { exists: true, value: walked.current } : { exists: false };\n};\n\n// Whether the path addresses an OWN slot: every step reads a real\n// container's own key / in-range array index, the final segment included.\n// This is stricter than slotAtPath, which treats a MISSING final key on a\n// real record as an addressable (legitimately empty) slot — here it reads\n// false. The consumer is setValue's identity guard: writing `undefined`\n// over an ABSENT key is NOT a no-op (it creates the key, a real state\n// change — key-count dirtiness, persisted shape), while writing it over a\n// key that exists holding undefined is.\nexport const hasOwnSlot = (obj: unknown, path: string): boolean =>\n parsePath(path).reduce<Readonly<{ ok: boolean; current: unknown }>>(\n (acc, segment) => {\n const container = acc.current;\n const owns = Array.isArray(container)\n ? typeof segment === \"number\" && segment < container.length\n : isPlainRecord(container) && Object.hasOwn(container, String(segment));\n return !acc.ok || !owns\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n ).ok;\n\nconst writeIntoArray = (\n arr: readonly unknown[],\n index: number,\n rest: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): readonly unknown[] => {\n const length = Math.max(arr.length, index + 1);\n return Array.from({ length }, (_, i) =>\n i === index\n ? writeSegments(arr[i], rest, value, kindAt, [...prefix, index])\n : arr[i],\n );\n};\n\nconst refusesHugeIndex = (index: number): boolean => {\n if (index > MAX_ARRAY_INDEX) {\n console.warn(\n `[formstand] refusing to write array index ${index} (max ${MAX_ARRAY_INDEX}); value left unchanged.`,\n );\n return true;\n }\n return false;\n};\n\nconst writeSegments = (\n obj: unknown,\n segments: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): unknown => {\n const [head, ...rest] = segments;\n if (head === undefined) return value;\n\n if (Array.isArray(obj)) {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray(obj, head, rest, value, kindAt, prefix);\n }\n\n // Records take any segment as a string key (mirroring readSegment), so a\n // z.record keyed by a large numeric id is writable — the array-index cap\n // only applies where an array actually exists or would be created.\n if (isPlainRecord(obj)) {\n // Spreading is only safe for PLAIN objects: spreading a Date/Map/Set or\n // class instance keeps own enumerable props but drops the prototype (and\n // for Map/Set, every entry) — the original would be silently destroyed.\n // Refuse, like the other unwritable shapes above.\n if (!isPlainObject(obj)) {\n console.warn(\n `[formstand] cannot write key \"${String(head)}\" through a non-plain object (Date/Map/Set/class instance); value left unchanged.`,\n );\n return obj;\n }\n const key = String(head);\n return {\n ...obj,\n [key]: writeSegments(obj[key], rest, value, kindAt, [...prefix, key]),\n };\n }\n\n // Absent (or non-container) value: create a container. The schema's\n // answer for this slot wins when the caller supplied one (a z.record\n // keyed \"0\" must not become an array, and a z.array must not become a\n // record); otherwise the segment type decides, as the docs state.\n const kind =\n kindAt?.(prefix.map(String).join(\".\")) ??\n (typeof head === \"number\" ? \"array\" : \"record\");\n if (kind === \"array\") {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray([], head, rest, value, kindAt, prefix);\n }\n const key = String(head);\n return { [key]: writeSegments(undefined, rest, value, kindAt, [...prefix, key]) };\n};\n\n// `containerKindAt` is optional so the bare utility keeps its segment-type\n// rule; createForm passes the schema-derived resolver from validation.ts.\nexport const setAtPath = <T>(\n obj: T,\n path: string,\n value: unknown,\n containerKindAt?: ContainerKindAt,\n): T => writeSegments(obj, parsePath(path), value, containerKindAt, []) as T;\n","import { z } from \"zod\";\nimport {\n type ContainerKind,\n type ContainerKindAt,\n type PathSegment,\n parsePath,\n} from \"./path\";\nimport type { ErrorMap } from \"./types\";\n\nexport type SettledValidationResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type ValidationResult<TOutput> =\n | SettledValidationResult<TOutput>\n // Returned by the sync `validate()` when the schema needs async parsing:\n // the async pass has already been started and `promise` resolves with its\n // outcome.\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledValidationResult<TOutput>>;\n }>;\n\nexport type SettledFieldValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: readonly string[] }>;\n\nexport type FieldValidationResult =\n | SettledFieldValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldValidationResult>;\n }>;\n\n// The plural (validateFields) mirrors the singular's discriminated shape\n// instead of returning boolean | Promise<boolean>: a returned Promise is\n// truthy, so the old union let `if (form.validateFields(paths))` silently\n// pass a gate the moment the schema gained an async refinement. `errors`\n// carries only the entries within the requested paths' scope.\nexport type SettledFieldsValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type FieldsValidationResult =\n | SettledFieldsValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldsValidationResult>;\n }>;\n\nconst issuePathToFormPath = (path: readonly PropertyKey[]): string =>\n path\n .filter((segment): segment is string | number => typeof segment !== \"symbol\")\n .join(\".\");\n\ntype FlatIssue = Readonly<{ path: string; message: string }>;\n\n// A failing plain `z.union` produces a single `invalid_union` issue whose real\n// per-branch issues live in `issue.errors` with paths relative to the union's\n// position. Recurse into them (prefixed with the union's own path) so users\n// get field-level messages instead of one generic \"Invalid input\"; keep the\n// union's own message only when no branch supplies anything more specific.\nconst expandIssue = (\n issue: z.core.$ZodIssue,\n prefix: readonly PropertyKey[],\n): readonly FlatIssue[] => {\n const at = [...prefix, ...issue.path];\n if (issue.code === \"invalid_union\") {\n const nested = issue.errors.flatMap((branch) =>\n branch.flatMap((sub) => expandIssue(sub, at)),\n );\n if (nested.length > 0) return nested;\n }\n return [{ path: issuePathToFormPath(at), message: issue.message }];\n};\n\n// Grouped through a Map the reduce itself creates, then materialized once.\n// The previous shape rebuilt the accumulator with `{ ...acc, [path]: ... }`\n// per issue, which is quadratic in the issue count: 3000 empty rows under\n// z.array(z.object({ name: z.string().min(1) })) spent 1.3 s here against\n// zod's 7 ms parse. Mutating the Map (and the per-key message list) is the\n// sanctioned reduce-accumulator exception, and a Map also sidesteps the\n// prototype trap outright: a key of \"__proto__\" or \"constructor\" is just a\n// key. Object.fromEntries defines every key as an own data property, so the\n// returned record carries those keys as own properties too.\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n Object.fromEntries(\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Map<string, string[]>>((acc, { path, message }) => {\n const existing = acc.get(path);\n if (existing === undefined) {\n acc.set(path, [message]);\n } else if (!existing.includes(message)) {\n // Union branches often repeat the same complaint; drop exact\n // duplicates.\n existing.push(message);\n }\n return acc;\n }, new Map()),\n );\n\nexport const validateSync = <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): SettledValidationResult<z.output<TSchema>> => {\n const result = schema.safeParse(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\nexport const validateAsync = async <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): Promise<SettledValidationResult<z.output<TSchema>>> => {\n const result = await schema.safeParseAsync(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\n// The message fallback covers the dual-package hazard: with two zod copies\n// loaded, the thrown error is not an instance of *this* copy's class.\nexport const isAsyncRequiredError = (e: unknown): boolean =>\n e instanceof z.core.$ZodAsyncError ||\n (e instanceof Error &&\n /Encountered Promise during synchronous parse/i.test(e.message));\n\n// True when `key` is `path` itself or a descendant (\"a.b\" under \"a\"). The\n// root \"\" matches only the \"\" key — whole-form scope is never implicit;\n// call sites that want it (validateField(\"\"), focusFirstError's fallback)\n// handle the root explicitly instead of inheriting a wildcard.\nexport const isPathOrChild = (key: string, path: string): boolean =>\n key === path || key.startsWith(`${path}.`);\n\n// Re-key an error map produced by parsing a field's subschema so its keys are\n// absolute form paths (\"\" becomes the field path itself).\nexport const prefixErrorKeys = (errors: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? errors\n : Object.fromEntries(\n Object.entries(errors).map(([k, v]) => [\n k === \"\" ? path : `${path}.${k}`,\n v,\n ]),\n );\n\n// The empty representation a field's schema accepts: undefined when the\n// field is optional (or the wrappers are unrecognized — undefined is the\n// library-wide default empty), null when it is nullable but not optional.\n// Lets a cleared input round-trip to a valid blank based on what the schema\n// states rather than guessing from runtime values.\nexport const emptyValueForSchema = (schema: z.ZodType): null | undefined => {\n const walk = (s: z.ZodType, sawNullable: boolean): null | undefined => {\n if (s instanceof z.ZodOptional) return undefined;\n if (s instanceof z.ZodNullable) {\n return walk(s.unwrap() as z.ZodType, true);\n }\n return sawNullable ? null : undefined;\n };\n return walk(schema, false);\n};\n\n// Whether the schema ACCEPTS its own emptyValue as input — the judgment the\n// string-shaped bindings need before writing it on a cleared input. An\n// optional field takes undefined, a nullable one takes null, and a\n// defaulted/prefaulted one takes undefined too (the default fills it at\n// parse, so clearing reads as \"back to the default\"). A bare required field\n// does NOT: its emptyValue is undefined only as the library-wide fallback,\n// and writing that would trade a visible \"\" the schema can at least judge\n// for a hole it rejects — which is why text and select bindings keep \"\" for\n// non-clearable fields. The check is deliberately as shallow as\n// emptyValueForSchema's walk: a wrapper that hides the optionality from\n// emptyValue (readonly, catch, pipe) hides it here too, so the pair can\n// never disagree about whether the emptyValue is legal.\nexport const isClearableSchema = (schema: z.ZodType): boolean =>\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodNullable ||\n schema instanceof z.ZodDefault ||\n schema instanceof z.ZodPrefault;\n\n// One unwrap step for the lax structural walk below: wrappers that are\n// transparent to a path (optional/nullable/default/readonly/catch/pipe/...)\n// yield their inner schema; anything else returns null and is judged as-is.\nconst unwrapForWalk = (s: z.ZodType): z.ZodType | null => {\n if (s instanceof z.ZodOptional || s instanceof z.ZodNullable) {\n return s.unwrap() as z.ZodType;\n }\n if (\n s instanceof z.ZodDefault ||\n s instanceof z.ZodPrefault ||\n s instanceof z.ZodCatch ||\n s instanceof z.ZodReadonly ||\n s instanceof z.ZodNonOptional\n ) {\n return s.def.innerType as z.ZodType;\n }\n // Form values are z.input, so a pipe is traversed through its input side.\n if (s instanceof z.ZodPipe) return s.def.in as z.ZodType;\n return null;\n};\n\n// Leaves that provably have no children: remaining path segments under one of\n// these cannot exist in the schema.\nconst isLeafSchema = (s: z.ZodType): boolean =>\n s instanceof z.ZodString ||\n s instanceof z.ZodNumber ||\n s instanceof z.ZodBoolean ||\n s instanceof z.ZodBigInt ||\n s instanceof z.ZodDate ||\n s instanceof z.ZodEnum ||\n s instanceof z.ZodLiteral ||\n s instanceof z.ZodNull ||\n s instanceof z.ZodUndefined ||\n s instanceof z.ZodVoid ||\n s instanceof z.ZodNaN ||\n s instanceof z.ZodSymbol;\n\n// Every unwrap and every consumed segment costs one step — generous for any\n// real path, but it bounds pathological wrapper towers.\nconst SCHEMA_WALK_BUDGET = 64;\n\n// Lax structural check: can `path` possibly exist under `schema`? Used to\n// warn when validateField targets a path the schema cannot contain (which\n// would otherwise silently validate as always-valid). Deliberately biased\n// toward \"yes\": objects answer from their shape (a catchall/loose object\n// accepts any key), arrays accept any numeric index into their element, and\n// everything too dynamic to judge — records, maps, tuples, unions,\n// intersections, lazies, any/unknown, unrecognized nodes — answers true so\n// the warning can never be a false positive. Only a provable miss (a key\n// absent from a closed object shape, a string segment into an array, or\n// segments remaining under a scalar leaf) answers false.\nexport const schemaHasPath = (schema: z.ZodType, path: string): boolean => {\n const walk = (\n s: z.ZodType,\n segments: readonly PathSegment[],\n budget: number,\n ): boolean => {\n if (budget <= 0) return true;\n const inner = unwrapForWalk(s);\n if (inner !== null) return walk(inner, segments, budget - 1);\n const [head, ...rest] = segments;\n if (head === undefined) return true;\n if (s instanceof z.ZodObject) {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n // Own-key read: a bare index would walk the prototype chain, so\n // \"constructor\" would resolve to Object's constructor and read as a\n // declared key of the shape.\n const child = Object.hasOwn(shape, String(head))\n ? shape[String(head)]\n : undefined;\n if (child !== undefined) return walk(child, rest, budget - 1);\n // A loose/catchall object accepts keys beyond the shape (a ZodNever\n // catchall — strictObject — rejects them like a closed shape does).\n const catchall = s.def.catchall;\n return catchall !== undefined && !(catchall instanceof z.ZodNever);\n }\n if (s instanceof z.ZodArray) {\n return typeof head === \"number\"\n ? walk(s.element as z.ZodType, rest, budget - 1)\n : false;\n }\n return !isLeafSchema(s);\n };\n return walk(schema, parsePath(path), SCHEMA_WALK_BUDGET);\n};\n\nconst hasChecks = (s: z.ZodType): boolean => {\n const checks = (s.def as Readonly<{ checks?: readonly unknown[] }>).checks;\n return checks !== undefined && checks.length > 0;\n};\n\n// Walk the schema along a dot path so field-level validation can parse just\n// that field instead of the whole form. Returns null (meaning: fall back to a\n// full-form parse) unless every *traversed* level is a plain ZodObject or\n// ZodArray with no checks — a refinement on a traversed level could target\n// this field's path, so extraction would miss or fail to clear its errors.\n// Wrappers (optional/nullable/default/pipe/union/record/...) also bail: their\n// error keying differs from a direct parse of the inner value. The leaf itself\n// may carry any checks — they belong to the field.\n// The subschema at `path` for INTROSPECTION (useField's emptyValue and\n// clearable): what blank does the schema accept here, and may a cleared\n// control write it. Unlike fieldSchemaAtPath (validateField's fast path,\n// which must refuse anything a scoped parse could get wrong), this walk\n// looks THROUGH wrappers at container levels (an optional profile object\n// still has a profile.name) and INTO discriminated unions and unions (a\n// variant's field is read from the first member that declares the key;\n// members rarely disagree on a shared key's wrapper, and the heuristic\n// fallback is what a miss costs). The last segment's own wrapper is kept:\n// it is exactly what the two introspection helpers read.\nexport const fieldSchemaForIntrospection = (\n schema: z.ZodType,\n path: string,\n): z.ZodType | null => {\n const childOf = (s: z.ZodType, segment: PathSegment): z.ZodType | null => {\n const inner = unwrapForWalk(s);\n if (inner !== null) return childOf(inner, segment);\n if (s instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (s instanceof z.ZodArray && typeof segment === \"number\") {\n return s.element as z.ZodType;\n }\n if (s instanceof z.ZodTuple && typeof segment === \"number\") {\n return (s.def.items[segment] as z.ZodType | undefined) ?? null;\n }\n // Every record key shares one value schema, and the walk reads keys\n // as strings, so a numeric segment is a key here too (z.record(\n // z.number(), ...) parses \"5\" as a key at runtime).\n if (s instanceof z.ZodRecord) {\n return s.valueType as z.ZodType;\n }\n if (s instanceof z.ZodDiscriminatedUnion || s instanceof z.ZodUnion) {\n const options = s.def.options as readonly z.ZodType[];\n return options.reduce<z.ZodType | null>(\n (found, option) => found ?? childOf(option, segment),\n null,\n );\n }\n return null;\n };\n return parsePath(path).reduce<z.ZodType | null>(\n (current, segment) => (current === null ? null : childOf(current, segment)),\n schema,\n );\n};\n\n// setAtPath's absent-slot resolver, from the schema: the container the\n// schema declares at `prefix` (wrappers looked through, like the\n// introspection walk above), or null where it declares a leaf, a union,\n// or nothing, which leaves setAtPath on its segment-type rule. A write of\n// \"lookup.0\" into an absent optional z.record used to create an array\n// here, which the record schema then rejected (\"expected record,\n// received array\"); the schema knew the answer all along.\n//\n// This walk is NOT fieldSchemaForIntrospection's: that one reads a union's\n// key from the first member that declares it, which is the right guess for\n// emptyValue/clearable (members rarely disagree on a shared key's wrapper)\n// and the wrong one here, where two variants can declare the same key as\n// an object and as an array (a reviewer's reproduction: `details` as\n// `z.object` in one variant and `z.array` in another made every write\n// create the first variant's record, and the array variant then failed\n// validation). A union anywhere on the path, or at its end, means the\n// schema has no single answer, so the segment-type rule decides, which is\n// also what the typed-paths guide says.\nexport const containerKindAt =\n (schema: z.ZodType): ContainerKindAt =>\n (prefix: string): ContainerKind | null => {\n const unwrapAll = (s: z.ZodType): z.ZodType => {\n const inner = unwrapForWalk(s);\n return inner === null ? s : unwrapAll(inner);\n };\n const step = (s: z.ZodType, segment: PathSegment): z.ZodType | null => {\n const inner = unwrapAll(s);\n if (inner instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = inner.shape;\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (inner instanceof z.ZodArray && typeof segment === \"number\") {\n return inner.element as z.ZodType;\n }\n if (inner instanceof z.ZodTuple && typeof segment === \"number\") {\n return (inner.def.items[segment] as z.ZodType | undefined) ?? null;\n }\n if (inner instanceof z.ZodRecord) {\n return inner.valueType as z.ZodType;\n }\n return null;\n };\n const sub = parsePath(prefix).reduce<z.ZodType | null>(\n (current, segment) => (current === null ? null : step(current, segment)),\n schema,\n );\n if (sub === null) return null;\n const inner = unwrapAll(sub);\n if (inner instanceof z.ZodArray || inner instanceof z.ZodTuple) {\n return \"array\";\n }\n if (inner instanceof z.ZodObject || inner instanceof z.ZodRecord) {\n return \"record\";\n }\n return null;\n };\n\nexport const fieldSchemaAtPath = (\n schema: z.ZodType,\n path: string,\n): z.ZodType | null =>\n parsePath(path).reduce<z.ZodType | null>((current, segment: PathSegment) => {\n if (current === null || hasChecks(current)) return null;\n if (current instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> =\n current.shape;\n // Own-key read, like every other walk in the library: a bare index\n // resolves \"constructor\"/\"__proto__\" through the prototype chain to\n // a non-schema value, which then CRASHES the reduce (def.checks on a\n // function; safeParse on Object.prototype) — and the subschema cache\n // would keep the poisoned entry. Runtime-built paths (server error\n // fields mapped onto validateField) are the realistic entry point.\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (current instanceof z.ZodArray && typeof segment === \"number\") {\n return current.element as z.ZodType;\n }\n return null;\n }, schema);\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { createStore } from \"zustand/vanilla\";\nimport { devtools } from \"zustand/middleware\";\nimport {\n type IndexMapper,\n insertAt,\n invertMapper,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { clearArrayOpsUnder, recordArrayOp } from \"./arrayOpLog\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport { isDevBuild, isDevToolsBuild } from \"./env\";\nimport { entryAt, flagAt } from \"./maps\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n IsUnion,\n PathDepth,\n} from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, hasOwnSlot, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type FieldsValidationResult,\n type SettledFieldValidationResult,\n type SettledFieldsValidationResult,\n type SettledValidationResult,\n type ValidationResult,\n containerKindAt,\n fieldSchemaAtPath,\n isAsyncRequiredError,\n isPathOrChild,\n prefixErrorKeys,\n schemaHasPath,\n validateAsync,\n validateSync,\n} from \"./validation\";\n\nexport type ReadonlyStoreApi<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type CreateFormOptions<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n initialValues: z.input<TSchema>;\n // TYPE-LEVEL ONLY: the typed-path depth budget for this form, in SEGMENTS\n // (default 9). The runtime ignores it entirely — every path API already\n // walks any depth — it only widens (or narrows) the FieldPath union the\n // form's typed surface is checked against. Raising it is a deliberate\n // TypeScript compile-time trade: the union's size grows with every level\n // the type recurses into, and every path-taking call pays for it in the\n // editor. Reach for it when one deep store backs many forms (a global\n // store whose leaves sit past 9 segments); must be a number LITERAL\n // (e.g. `pathDepth: 12`) so the budget stays a compile-time constant.\n // The `PathDepth` constraint (0-25, the Prev table's range) makes an\n // out-of-range literal or a widened `number` variable a compile error at\n // the call site. The intersection additionally rejects a UNION depth\n // (`cond ? 12 : 9` infers D = 9 | 12, a budget assignable to neither\n // Form<S, 9> nor Form<S, 12>): for a single literal the extra operand is\n // `unknown` and the type stays `D`, keeping literal inference intact; for\n // a union it becomes `never`, so the value can't satisfy the property and\n // the call errors instead of minting an unusable Form type.\n pathDepth?: D & (IsUnion<D> extends true ? never : unknown);\n mode?: ValidationMode;\n reValidateMode?: ValidationMode;\n // Run a full validation pass at creation so the error map (and flags derived\n // from it, like `useIsValid`) reflect the initial values immediately rather\n // than reading as error-free until the first blur/change/submit. Async\n // schemas validate in the background. Note this surfaces errors for untouched\n // fields right away — gate error display on `touched` if that's not wanted.\n validateOnMount?: boolean;\n // Connect the form's store to the Redux DevTools extension (zustand's\n // devtools middleware), named so multiple forms are distinguishable:\n // `devtools: \"checkout\"` shows a \"checkout\" instance with every state\n // write inspectable and time-travelable. `true` uses \"formstand\". Off by\n // default; when the extension isn't installed the middleware is inert.\n devtools?: boolean | string;\n}>;\n\nexport type SubmitHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n) => void | Promise<void>;\n\nexport type InvalidSubmitHandler = (errors: ErrorMap) => void;\n\nexport type SubmitOptions = Readonly<{\n force?: boolean;\n // Called when onValid throws or rejects (the \"error\" SubmitResult) — the\n // save-failure hook, mirroring onInvalid for the validation side. The\n // result still resolves {kind: \"error\"}, so imperative submit() callers\n // can keep switching on it instead.\n onError?: (error: unknown) => void;\n}>;\n\n// \"valid\": validation passed and onValid ran to completion. \"invalid\":\n// validation failed (onInvalid ran; errors written and their fields marked\n// touched, unless the values changed while validation was in flight — see\n// submit). \"skipped\": another submit was already in flight and force wasn't\n// set. \"error\": onValid threw or rejected — submit resolves with the thrown\n// value instead of rejecting, so handleSubmit used as an event handler never\n// produces an unhandled rejection. No error state is written for this kind;\n// surface the failure yourself (e.g. via setError).\nexport type SubmitResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>\n | Readonly<{ kind: \"skipped\" }>\n | Readonly<{ kind: \"error\"; error: unknown }>;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key.\ntype ErrorPath<TValues, D extends PathDepth = DefaultPathDepth> =\n | FieldPath<TValues, D>\n | \"\";\n\n// No keepDirty: per-field dirtiness is derived from values vs initialValues,\n// and reset makes those equal by definition — a kept dirty map would say\n// \"dirty\" while every field-level read says \"clean\".\nexport type ResetOptions = Readonly<{\n keepErrors?: boolean;\n keepTouched?: boolean;\n keepSubmitCount?: boolean;\n}>;\n\nexport type FieldSnapshot<TValue> = Readonly<{\n value: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\nconst shallowFieldEqual = <TValue>(\n a: FieldSnapshot<TValue>,\n b: FieldSnapshot<TValue>,\n): boolean =>\n Object.is(a.value, b.value) &&\n a.error === b.error &&\n a.touched === b.touched &&\n a.dirty === b.dirty &&\n a.isValidating === b.isValidating;\n\nexport type Form<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n // Type-level marker only — never present at runtime. It carries the form's\n // typed-path depth budget (createForm's `pathDepth`, default 9) in a\n // directly-inferable position so the React hooks' `Form<TSchema, D>`\n // parameters recover D from the form argument (inferring it out of the\n // FieldPath instantiations in the method types below is not something TS\n // can do). It also makes the budget part of the form's identity:\n // Form<S, 12> is deliberately not assignable to Form<S, 9>.\n \"~pathDepth\"?: D;\n schema: TSchema;\n store: ReadonlyStoreApi<FormState<z.input<TSchema>>>;\n getState: () => FormState<z.input<TSchema>>;\n subscribe: (\n listener: (\n state: FormState<z.input<TSchema>>,\n prev: FormState<z.input<TSchema>>,\n ) => void,\n ) => () => void;\n getField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => () => void;\n // Watches THE WHOLE values object — the name is watchValue + \"s\" as in\n // \"all the values\", not \"watchValue over many paths\". Fires whenever any\n // value changes (reference-compared). A multi-path watcher, if one ever\n // ships, would be a new API rather than a change to this one.\n watchValues: (\n listener: (\n values: z.input<TSchema>,\n previous: z.input<TSchema>,\n ) => void,\n ) => () => void;\n setValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n value: FieldValue<z.input<TSchema>, P>,\n ) => void;\n setValues: (next: z.input<TSchema>) => void;\n setTouched: (path: FieldPath<z.input<TSchema>, D>, touched?: boolean) => void;\n setSubmitting: (value: boolean) => void;\n setMode: (mode: ValidationMode) => void;\n setReValidateMode: (mode: ValidationMode) => void;\n setError: (\n path: ErrorPath<z.input<TSchema>, D>,\n errors: string | readonly string[],\n ) => void;\n setErrors: (errors: ErrorMap) => void;\n // The merge-many sibling of setError: server responses arrive as a MAP\n // of runtime-keyed field errors, and mapping them one setError at a time\n // forced a typed-path cast per call (the docs' own examples did), while\n // setErrors REPLACES the whole channel and cannot be used incrementally.\n // The server channel is inherently runtime-keyed, so this takes the map\n // as-is; an empty array removes its key, like setError.\n addErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>, D>) => void;\n // The patch type omits `errors`: the merged map is derived from\n // schemaErrors/serverErrors, so writing it directly is unrepresentable for\n // TS callers (plain-JS writes are ignored with a warning).\n updateState: (\n updater: (\n state: FormState<z.input<TSchema>>,\n ) => Partial<Omit<FormState<z.input<TSchema>>, \"errors\">>,\n ) => void;\n reset: (\n nextInitial?: Partial<z.input<TSchema>>,\n options?: ResetOptions,\n ) => void;\n // Reset one field to its initial value, clearing its (and its descendants')\n // dirty/touched/error state.\n resetField: (path: FieldPath<z.input<TSchema>, D>) => void;\n adoptValues: (values: z.input<TSchema>) => void;\n // One-shot read of a field's full slice (value/error/touched/dirty/\n // isValidating) — the imperative sibling of useField's state.\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>, D>) => FieldValidationResult;\n // Mirrors validateField's discriminated result — \"pending\" (carrying the\n // already-started async pass's promise) when the schema needs async\n // parsing. A bare boolean | Promise<boolean> union would let a truthy\n // in-flight Promise silently pass `if (form.validateFields(...))` gates.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => FieldsValidationResult;\n // Settled result types, deliberately: an AWAITED async pass can never\n // resolve \"pending\" (the promise IS the pending state), and the wider\n // union forced every exhaustive switch to carry a dead case — against\n // this codebase's own no-default-arm ethos. validateFieldsAsync below\n // was always typed this way; these two now match.\n validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>, D>,\n ) => Promise<SettledFieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => Promise<SettledFieldsValidationResult>;\n submit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => Promise<SubmitResult<z.output<TSchema>>>;\n // Every array op takes an ARRAY path (ArrayFieldPath: variable-length\n // arrays, optional/nullable included, tuples and scalars excluded), so a\n // misaddressed op is blamed on the path argument. The index-only ops\n // used to take any FieldPath and compile against a z.string(), then warn\n // and skip at runtime.\n arrayPush: <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>,\n ) => void;\n arrayRemove: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n index: number,\n ) => void;\n arrayInsert: <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n index: number,\n item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>,\n ) => void;\n arrayMove: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n a: number,\n b: number,\n ) => void;\n handleSubmit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => (event?: {\n preventDefault: () => void;\n }) => Promise<SubmitResult<z.output<TSchema>>>;\n diff: () => Readonly<Record<string, unknown>>;\n dirtyFields: () => readonly string[];\n snapshot: () => FormState<z.input<TSchema>>;\n restore: (snapshot: FormState<z.input<TSchema>>) => void;\n}>;\n\nconst emptyErrors = {} as ErrorMap;\nconst emptyBools = {} as BoolMap;\n\nconst identityMapper: IndexMapper = (n) => n;\n\nconst omitKey = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> =>\n Object.fromEntries(Object.entries(map).filter(([k]) => k !== key));\n\n// The many-keys sibling, one pass over the map. Folding omitKey per key\n// (reduce with omitKey) rebuilt the whole map once per key, quadratic in\n// the number of paths a plural pass carries.\nconst omitKeys = <V>(\n map: Readonly<Record<string, V>>,\n keys: ReadonlySet<string>,\n): Readonly<Record<string, V>> => {\n if (keys.size === 0) return map;\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !keys.has(k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst inScopeOfAny = (key: string, paths: readonly string[]): boolean =>\n paths.some((p) => isPathOrChild(key, p));\n\n// Drop every entry keyed at or under any of `paths` (\"items\" covers\n// \"items.0.name\") — the shared scope filter for the path-keyed maps. Returns\n// the input map unchanged when nothing is in scope, so identity-based\n// subscribers don't re-fire.\nconst omitScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !inScopeOfAny(k, paths));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst pickScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> =>\n Object.fromEntries(\n Object.entries(map).filter(([k]) => inScopeOfAny(k, paths)),\n );\n\n// Replace the slice of `prev` at or under `paths` with `scoped` (whose keys\n// must already be within scope).\nconst mergeScopedErrors = (\n prev: ErrorMap,\n scoped: ErrorMap,\n paths: readonly string[],\n): ErrorMap => ({ ...omitScope(prev, paths), ...scoped });\n\n// Drop entries at `path` itself or an ancestor of it (\"a\" over \"a.b\"). The\n// root \"\" entry is an ancestor of every path, so any value write releases it\n// — a value write below a container stales the container-level server\n// verdict too, per the documented release contract.\nconst releaseAncestorEntries = <V>(\n map: Readonly<Record<string, V>>,\n path: string,\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => k !== \"\" && !isPathOrChild(path, k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\n// Minimal divergent paths between values and initialValues: recurse through\n// plain objects, report anything else (scalars, arrays, type mismatches) at\n// its own path — arrays report their base path, and a divergent non-record\n// root reports \"\". This is the derived source for diff()/dirtyFields(); the\n// boolean per-field question is isFieldDirty.\nconst dirtyPathsOf = (\n values: unknown,\n initial: unknown,\n prefix: string,\n): readonly string[] => {\n if (Object.is(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\n // One structural recursion: the deep compare runs only at leaf/array\n // boundaries below, never per ancestor level — otherwise every node is\n // re-deep-compared once per level above it (O(n × depth) for diff()).\n const keys = new Set([...Object.keys(values), ...Object.keys(initial)]);\n const childPaths = [...keys].flatMap((k) =>\n dirtyPathsOf(\n values[k],\n initial[k],\n prefix === \"\" ? k : `${prefix}.${k}`,\n ),\n );\n if (childPaths.length > 0) return childPaths;\n // Every shared key compared equal, so the key SETS decide: a mismatch\n // where the extra key holds undefined ({} vs { nickname: undefined })\n // reports the object itself, keeping diff()/dirtyFields() non-empty\n // whenever isFieldDirty/useIsDirty say dirty (valuesEqual's own rule).\n const sameKeySet =\n Object.keys(values).length === Object.keys(initial).length &&\n Object.keys(values).every((k) => Object.hasOwn(initial, k));\n return sameKeySet ? [] : [prefix];\n }\n return valuesEqual(values, initial) ? [] : [prefix];\n};\n\n// Key for the whole-form async validation's ownership token (internal —\n// form-level in-flight state lives in FormState.isValidatingForm).\nconst FORM_SEQ_KEY = \"__form__\";\n\n// Key for submit's ownership token: reset()/adoptValues() clear the token\n// map, so an in-flight submit notices the form was rebased under it even\n// when the values reference is unchanged (a bare reset() on a pristine form\n// restores the same initialValues reference).\nconst SUBMIT_SEQ_KEY = \"__submit__\";\n\nconst stringArraysEqual = (\n a: readonly string[],\n b: readonly string[],\n): boolean => a === b || (a.length === b.length && a.every((v, i) => v === b[i]));\n\n// Preserve the previous array reference for entries whose messages didn't\n// change (and the previous map itself when nothing changed at all), so field\n// subscriptions comparing errors by identity don't re-fire on every pass.\n// Own-key reads (entryAt) throughout: a bare `prev[k]` for k =\n// \"constructor\" on an EMPTY map returned `Object`, which passed the\n// undefined check and crashed stringArraysEqual on `.every` inside\n// setState. Reachable from setError(\"constructor\", ...), addErrors, and a\n// schema that simply declares a field by that name.\nconst reuseErrorRefs = (next: ErrorMap, prev: ErrorMap): ErrorMap => {\n if (next === prev) return prev;\n const entries = Object.entries(next).map(([k, v]) => {\n const old = entryAt(prev, k);\n return [\n k,\n old !== undefined && stringArraysEqual(old, v) ? old : v,\n ] as const;\n });\n const sameShape =\n entries.length === Object.keys(prev).length &&\n entries.every(([k, v]) => entryAt(prev, k) === v);\n return sameShape ? prev : Object.fromEntries(entries);\n};\n\n// Shape a parse result into an error map scoped to `path`: sub-schema results\n// re-key to absolute form paths; full-form results filter to the path's scope,\n// except the root \"\" whose scope is explicitly the whole form.\nconst scopeSettledResult = (\n result: SettledValidationResult<unknown>,\n path: string,\n viaSubschema: boolean,\n): ErrorMap =>\n result.kind !== \"invalid\"\n ? emptyErrors\n : viaSubschema\n ? prefixErrorKeys(result.errors, path)\n : path === \"\"\n ? result.errors\n : pickScope(result.errors, [path]);\n\n// The one merge rule between the two error channels: the schema's message\n// wins at a key (it re-judged the same value the server did), server entries\n// show where the schema is silent. Returns the schema map's identity when\n// the server channel adds nothing.\nconst mergeErrorChannels = (schema: ErrorMap, server: ErrorMap): ErrorMap => {\n // Own-key check, not `schema[k] === undefined`: for a runtime-built key\n // like \"__proto__\" the bare read returns Object.prototype (never\n // undefined), which would silently drop the server entry from the merge.\n const extra = Object.entries(server).filter(\n ([k]) => !Object.hasOwn(schema, k),\n );\n return extra.length === 0\n ? schema\n : { ...schema, ...Object.fromEntries(extra) };\n};\n\ntype ErrorChannels = Readonly<{\n errors: ErrorMap;\n schemaErrors: ErrorMap;\n serverErrors: ErrorMap;\n}>;\n\n// The one way error state is written: patch a channel (or both) and the\n// user-visible `errors` map is re-derived, reusing per-key refs so\n// identity-based subscribers don't re-fire.\nconst errorChannels = (\n state: ErrorChannels,\n patch: Readonly<{ schemaErrors?: ErrorMap; serverErrors?: ErrorMap }>,\n): ErrorChannels => {\n const schemaErrors = patch.schemaErrors ?? state.schemaErrors;\n const serverErrors = patch.serverErrors ?? state.serverErrors;\n // Unchanged channels mean an unchanged merge — skip it, so no-op writes\n // (every keystroke with an empty server channel) don't rescan the map.\n if (\n schemaErrors === state.schemaErrors &&\n serverErrors === state.serverErrors\n ) {\n return { errors: state.errors, schemaErrors, serverErrors };\n }\n return {\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n state.errors,\n ),\n };\n};\n\n// The release contract for a value write at `path`: server entries at the\n// path or below go (that subtree was replaced), entries at ancestors go too\n// (container verdicts are stale), and a runtime \"\" path (the imperative\n// surface is string-typed) releases everything.\nconst releaseSpine = (server: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? emptyErrors\n : releaseAncestorEntries(omitScope(server, [path]), path);\n\n// A bulk values write releases only the verdicts whose value slice actually\n// changed — a server error on an untouched field survives a setValues that\n// rewrites its siblings. The \"\" entry compares the whole values object, so\n// any change releases a form-level verdict.\nconst releaseChangedSlices = (\n server: ErrorMap,\n prevValues: unknown,\n nextValues: unknown,\n): ErrorMap => {\n const entries = Object.entries(server);\n const kept = entries.filter(([k]) =>\n valuesEqual(getAtPath(prevValues, k), getAtPath(nextValues, k)),\n );\n return kept.length === entries.length ? server : Object.fromEntries(kept);\n};\n\n// D infers as a LITERAL from `options.pathDepth` (the `D extends PathDepth`\n// constraint is a union of literals, so inference stays literal); when the\n// option is omitted, D falls back to the default budget of 9. An\n// out-of-range literal (26, -1) or a `number`-typed variable fails the\n// constraint here, at the call site.\n//\n// NoInfer on the RETURNED depth: `options.pathDepth` is D's only inference\n// site on purpose. Without it, `createFormHooks(createForm(schema, opts),\n// name)` inferred the inner D from the outer call's contextual return type,\n// whose own D was still unresolved, so D became the whole PathDepth union\n// and every depth-typed bound hook (useXField, useXFieldArray, useXIsDirty)\n// collapsed its path argument to never. The const-form shape the docs\n// show never hit it; the inline one did.\nexport const createForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, NoInfer<D>> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\n // Every value write shares one schema-derived answer for \"what container\n // does an absent slot get\" (see setAtPath): built once per form, called\n // only when a write has to create a container.\n const kindAt = containerKindAt(schema);\n const initialReValidateMode: ValidationMode =\n options.reValidateMode ?? \"onChange\";\n\n const initial: FormState<Values> = {\n values: options.initialValues,\n initialValues: options.initialValues,\n errors: emptyErrors,\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n touched: emptyBools,\n isSubmitting: false,\n submitCount: 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n mode: initialMode,\n reValidateMode: initialReValidateMode,\n };\n\n // The devtools middleware is opt-in and otherwise absent — a plain store\n // has zero overhead. `enabled` stays true when opted in even in\n // production builds: opting in IS the signal, and without the browser\n // extension the middleware is inert anyway.\n const store =\n options.devtools === undefined || options.devtools === false\n ? createStore<FormState<Values>>(() => initial)\n : createStore<FormState<Values>>()(\n devtools(() => initial, {\n name:\n typeof options.devtools === \"string\"\n ? options.devtools\n : \"formstand\",\n // Non-production only, matching zustand's own devtools default:\n // opting in during development must NOT stream every keystroke to\n // an end user who happens to have the extension installed, where\n // a module-singleton form's unbounded time-travel history is a\n // real memory + serialization cost. Fail-closed gate: a runtime\n // without a readable NODE_ENV (CDN/ESM, Deno, a worker) reads as\n // production here, unlike the console-warning gate.\n enabled: isDevToolsBuild(),\n }),\n );\n\n // A full pass replaces the schema channel wholesale; the server channel is\n // untouched, which is the whole preservation story — a background pass\n // can't wipe a server verdict because it never writes that channel.\n const commitFullPass = (\n state: FormState<Values>,\n next: ErrorMap,\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(next, state.schemaErrors),\n });\n\n const validate = (): ValidationResult<z.output<TSchema>> => {\n if (asyncScopes.has(\"\")) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n try {\n const result = validateSyncLatched(\"\", schema, store.getState().values);\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n }));\n return result;\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n throw e;\n }\n };\n\n const validateFields = (\n paths: readonly string[],\n ): FieldsValidationResult => {\n if (paths.length === 0) return { kind: \"valid\" };\n // A \"\" path means whole-form scope (only reachable past the FieldPath\n // type, e.g. runtime-built path lists): delegate to the full pass so\n // manual errors are preserved, mirroring validateField(\"\").\n if (paths.some((p) => p === \"\")) {\n const result = validate();\n return result.kind === \"pending\"\n ? { kind: \"pending\", promise: result.promise.then(settledFormResult) }\n : settledFormResult(result);\n }\n const values = store.getState().values;\n // Fast path: when every requested path extracts a subschema, parse\n // just those slots instead of the whole form (a wizard step on a\n // 200-field schema stops paying for the other 190 fields per click).\n // This matches the full parse EXACTLY because extraction bailing is\n // what guards cross-field rules: fieldSchemaAtPath returns null when\n // any traversed level carries refinements or wrappers, so an\n // ancestor refine that could key errors into these paths forces the\n // full parse below.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, values),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n // Scopes already latched as async-requiring go straight to the async\n // pass. Skip scopes parse nothing and contribute no latch key — a\n // latched full-form \"\" must not divert a batch whose parses are all\n // sync subschemas (or nothing at all).\n const anyLatched = allViaSubschema\n ? scopes.some(\n ({ path, scope }) =>\n scope.kind === \"parse\" && asyncScopes.has(path),\n )\n : asyncScopes.has(\"\");\n if (anyLatched) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n try {\n if (allViaSubschema) {\n const merged = scopes.reduce<ErrorMap>(\n (acc, { path, scope }) =>\n scope.kind === \"skip\"\n ? acc\n : {\n ...acc,\n ...scopeSettledResult(\n validateSyncLatched(path, scope.schema, scope.value),\n path,\n true,\n ),\n },\n {},\n );\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, merged, paths),\n }));\n return settledFields(merged);\n }\n const result = validateSyncLatched(\"\", schema, values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, requestedErrors, paths),\n }));\n return settledFields(requestedErrors);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n throw e;\n }\n };\n\n // How to validate one field: parse its extracted subschema against the\n // slot's value when the path is reachable through check-free objects/\n // arrays, parse the full form filtered to the path's scope otherwise (so\n // cross-field refinements targeting the path still land), or skip when the\n // path addresses no slot (an out-of-range array index — parsing the\n // subschema against undefined would fabricate an error no full-form parse\n // produces). One \"parse\" variant carries the whole triple so the sync and\n // async passes cannot diverge arm-by-arm.\n type FieldScope =\n | Readonly<{ kind: \"skip\" }>\n | Readonly<{\n kind: \"parse\";\n schema: z.ZodType;\n value: unknown;\n viaSubschema: boolean;\n }>;\n\n // Scopes whose sync parse has hit an async refinement. The schema is fixed\n // for the form's lifetime, so once a scope requires async parsing it always\n // will — remember it and go straight to the async pass instead of paying a\n // doomed sync parse per validation (per keystroke in onChange mode). Keyed\n // like the parses themselves: \"\" for full-form, the path for subschema\n // parses. A sanctioned mutable-ref cache, like subschemaCache below.\n const asyncScopes = new Set<string>();\n\n // validateSync, latching the scope when its parse turns out to need async\n // — the caller still routes the rethrown error to the async pass.\n const validateSyncLatched = <S extends z.ZodType>(\n key: string,\n scopeSchema: S,\n value: z.input<S>,\n ): SettledValidationResult<z.output<S>> => {\n try {\n return validateSync(scopeSchema, value);\n } catch (e) {\n if (isAsyncRequiredError(e)) asyncScopes.add(key);\n throw e;\n }\n };\n\n // The subschema for a path is a pure function of the form's fixed schema —\n // cache it so per-keystroke validation doesn't re-walk the schema.\n const subschemaCache = new Map<string, z.ZodType | null>();\n const subschemaAt = (path: string): z.ZodType | null => {\n const cached = subschemaCache.get(path);\n if (cached !== undefined) return cached;\n const sub = fieldSchemaAtPath(schema, path);\n subschemaCache.set(path, sub);\n return sub;\n };\n\n // Field validation on a path the schema cannot contain silently returns\n // valid — easy to hit through the docs-sanctioned casts for runtime-built\n // paths. Warn once per path per form (a sanctioned mutable-ref cache, like\n // subschemaCache above: checked paths never need re-walking).\n const checkedSchemaPaths = new Set<string>();\n const warnMissingSchemaPath = (fn: string, path: string): void => {\n if (path === \"\" || checkedSchemaPaths.has(path)) return;\n checkedSchemaPaths.add(path);\n if (!schemaHasPath(schema, path)) {\n console.warn(\n `[formstand] ${fn}(\"${path}\"): path does not exist in the schema — result will always be valid.`,\n );\n }\n };\n\n const fieldScopeFor = (path: string, values: Values): FieldScope => {\n const sub = path === \"\" ? null : subschemaAt(path);\n if (sub === null) {\n return { kind: \"parse\", schema, value: values, viaSubschema: false };\n }\n const slot = slotAtPath(values, path);\n return slot.exists\n ? { kind: \"parse\", schema: sub, value: slot.value, viaSubschema: true }\n : { kind: \"skip\" };\n };\n\n const parseScopeAsync = async (\n path: string,\n scope: FieldScope,\n ): Promise<ErrorMap> =>\n scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n\n // Whether the value an async pass judged is no longer the live one. A\n // subschema scope parsed ONLY its slot, so only that slot's identity\n // decides: comparing the whole values reference (the old rule) discarded\n // a \"username taken\" verdict, and cleared its in-flight flag, the moment\n // the user moved on and typed into email while the check was in flight.\n // A full-form scope exists precisely because an ancestor refine may read\n // any field, so the whole reference still decides there. A skip scope\n // parsed nothing against an absent slot; it goes stale only if something\n // has since created that slot.\n const scopeStale = (\n scope: FieldScope,\n path: string,\n valuesAtStart: Values,\n live: Values,\n ): boolean => {\n if (live === valuesAtStart) return false;\n switch (scope.kind) {\n case \"skip\":\n return slotAtPath(live, path).exists;\n case \"parse\":\n return scope.viaSubschema\n ? !Object.is(getAtPath(live, path), scope.value)\n : true;\n }\n };\n\n const fieldResult = (scoped: ErrorMap): SettledFieldValidationResult => {\n const messages = Object.values(scoped).flat();\n return messages.length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: messages };\n };\n\n // The plural counterpart: reports the scoped error MAP (entries under the\n // requested paths) rather than one field's flat message list. Every input\n // derives from flattenIssues, which never emits an empty message list, so\n // key presence alone decides validity.\n const settledFields = (scoped: ErrorMap): SettledFieldsValidationResult =>\n Object.keys(scoped).length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: scoped };\n\n // Whole-form (\"\" path) delegation, shared by the sync and async plural\n // passes so their scoping of a full-pass verdict cannot diverge.\n const settledFormResult = (\n result: SettledValidationResult<z.output<TSchema>>,\n ): SettledFieldsValidationResult =>\n settledFields(result.kind === \"invalid\" ? result.errors : emptyErrors);\n\n // The commit rule for any scoped validation: replace the schema-error\n // slice under `paths` and release the server verdicts there — a\n // validation explicitly targeting a scope supersedes the server's word on\n // it. Shared by the singular and plural, sync and async passes so the\n // supersede rule lives exactly once.\n const commitScopedErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n paths: readonly string[],\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(state.schemaErrors, scoped, paths),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, paths),\n });\n\n // How ONE field validation's scoped errors land. validateField(\"\") is a\n // whole-form pass, so it lands like validate() (server channel untouched).\n const commitFieldErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, scoped)\n : commitScopedErrors(state, scoped, [path]);\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n const scope = fieldScopeFor(path, store.getState().values);\n // Only PARSE scopes consult the latch — a skip scope parses nothing, so\n // it can never require async parsing and settles synchronously (below)\n // even while the full-form \"\" key is latched. The latch key mirrors\n // what the parse would run: the path for a subschema parse, the full\n // form (\"\") for a bailed extraction.\n if (\n scope.kind === \"parse\" &&\n asyncScopes.has(scope.viaSubschema ? path : \"\")\n ) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n try {\n const scoped =\n scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n validateSyncLatched(\n scope.viaSubschema ? path : \"\",\n scope.schema,\n scope.value,\n ),\n path,\n scope.viaSubschema,\n );\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n }));\n return fieldResult(scoped);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n throw e;\n }\n };\n\n const snapshotField = (\n state: FormState<Values>,\n path: string,\n ): FieldSnapshot<unknown> => {\n const value = getAtPath(state.values, path);\n return {\n value,\n error: entryAt(state.errors, path),\n touched: flagAt(state.touched, path),\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: flagAt(state.isValidating, path),\n };\n };\n\n // Ownership tokens for in-flight async passes (a sanctioned mutable-ref\n // cache, like the subscription refs). Tokens are unique by construction —\n // each claim mints a fresh Symbol — so cleared or reissued keys can never\n // collide with a token an in-flight pass still holds.\n const sequences = new Map<string, symbol>();\n\n const claimPass = (key: string): symbol => {\n const pass = Symbol(key);\n sequences.set(key, pass);\n return pass;\n };\n\n const validateAsyncOnForm = async (): Promise<\n SettledValidationResult<z.output<TSchema>>\n > => {\n const pass = claimPass(FORM_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({ ...state, isValidatingForm: true }));\n\n const result = await validateAsync(schema, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(FORM_SEQ_KEY) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({ ...state, isValidatingForm: false }));\n }\n return result;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n isValidatingForm: false,\n }));\n return result;\n };\n\n const validateFieldsAsync = async (\n paths: readonly string[],\n ): Promise<SettledFieldsValidationResult> => {\n if (paths.length === 0) return { kind: \"valid\" };\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n return settledFormResult(await validateAsyncOnForm());\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n // Same fast path as the sync plural (see validateFields): when every\n // requested path extracts a subschema, parse just those slots. The\n // async plural used to parse the whole form regardless, so a wizard\n // step (useFormSteps routes through here) paid for every other step's\n // fields, and an unrelated field's async refine ran on every advance.\n // Extraction bailing still guards cross-field rules: one path whose\n // scope does not extract sends the whole batch to the full parse.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, valuesAtStart),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n store.setState((state) => ({\n ...state,\n isValidating: {\n ...state.isValidating,\n ...Object.fromEntries(paths.map((p) => [p, true] as const)),\n },\n }));\n\n // Whichever parse ran, each path's errors are read back per path: the\n // slot parses (in parallel) by their own key, the full parse scoped to\n // the path. One variant per parse shape, so the two cannot be mixed.\n type BatchParse =\n | Readonly<{ kind: \"slots\"; byPath: ReadonlyMap<string, ErrorMap> }>\n | Readonly<{ kind: \"full\"; errors: ErrorMap }>;\n const parsed: BatchParse = allViaSubschema\n ? {\n kind: \"slots\",\n byPath: new Map(\n await Promise.all(\n scopes.map(\n async ({ path, scope }) =>\n [path, await parseScopeAsync(path, scope)] as const,\n ),\n ),\n ),\n }\n : {\n kind: \"full\",\n errors: await validateAsync(schema, valuesAtStart).then((result) =>\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n };\n const errorsFor = (path: string): ErrorMap => {\n switch (parsed.kind) {\n case \"slots\":\n return parsed.byPath.get(path) ?? emptyErrors;\n case \"full\":\n return pickScope(parsed.errors, [path]);\n }\n };\n const requestedErrors: ErrorMap = Object.fromEntries(\n paths.flatMap((path) => Object.entries(errorsFor(path))),\n );\n const requested = settledFields(requestedErrors);\n\n // Three tiers per path: still OWNED (this pass is the latest for it, so\n // it clears the flag it set), and among those still FRESH (its scope's\n // value is the live one, so its verdict lands). A full-form scope is\n // fresh only while the whole values reference holds; a subschema scope\n // only while its own slot does, so an unrelated field changing in\n // flight no longer discards the batch.\n const live = store.getState();\n const owned = scopes.filter(\n ({ path }) => sequences.get(path) === passes.get(path),\n );\n const fresh = owned\n .filter(\n ({ path, scope }) =>\n !scopeStale(scope, path, valuesAtStart, live.values),\n )\n .map(({ path }) => path);\n const ownedKeys = new Set(owned.map(({ path }) => path));\n if (owned.length === 0) return requested;\n\n store.setState((state) => ({\n ...state,\n ...(fresh.length === 0\n ? {}\n : commitScopedErrors(\n state,\n Object.fromEntries(\n fresh.flatMap((path) => Object.entries(errorsFor(path))),\n ),\n fresh,\n )),\n isValidating: omitKeys(state.isValidating, ownedKeys),\n }));\n\n return requested;\n };\n\n const validateFieldAsync = async (\n path: string,\n ): Promise<SettledFieldValidationResult> => {\n warnMissingSchemaPath(\"validateFieldAsync\", path);\n // The root \"\" is whole-form scope: delegate to the form-level pass so\n // the in-flight flag lands in isValidatingForm — the single slot for\n // whole-form validation — instead of booking an isValidating[\"\"] entry\n // no consumer watches.\n if (path === \"\") {\n const result = await validateAsyncOnForm();\n return fieldResult(\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n );\n }\n const pass = claimPass(path);\n const valuesAtStart = store.getState().values;\n const scope = fieldScopeFor(path, valuesAtStart);\n store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const scoped = await parseScopeAsync(path, scope);\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || scopeStale(scope, path, valuesAtStart, live.values)) {\n if (stillOwns) {\n store.setState((state) => ({\n ...state,\n isValidating: omitKey(state.isValidating, path),\n }));\n }\n return fieldResult(scoped);\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, scoped, path),\n isValidating: omitKey(state.isValidating, path),\n }));\n\n return fieldResult(scoped);\n };\n\n const applyArrayOp = (\n path: string,\n nextArray: (current: readonly unknown[]) => readonly unknown[],\n mapper: IndexMapper,\n // Validated against the current length before anything mutates — a bad\n // index (arrayRemove(path, -1)) would otherwise corrupt both the array\n // and the re-keyed error/touched maps.\n indexInBounds?: (length: number) => boolean,\n ): void => {\n const current = getAtPath(store.getState().values, path);\n // null passes like undefined: it is the canonical empty of a NULLABLE\n // array field (emptyValue), and the op item types are built on\n // NonNullable<FieldValue<...>> precisely so nullable/optional arrays\n // accept ops — refusing null made those calls typecheck and then\n // silently no-op at runtime. Both empties start the op from [].\n if (current !== undefined && current !== null && !Array.isArray(current)) {\n console.warn(\n `[formstand] array op on \"${path}\" but the value at that path is not an array (got ${typeof current}). Operation skipped.`,\n );\n return;\n }\n const length = Array.isArray(current) ? current.length : 0;\n if (indexInBounds !== undefined && !indexInBounds(length)) {\n console.warn(\n `[formstand] array op on \"${path}\" with an out-of-range or non-integer index (length ${length}). Operation skipped.`,\n );\n return;\n }\n const arr: readonly unknown[] = Array.isArray(current) ? current : [];\n const next = nextArray(arr);\n const written = setAtPath(store.getState().values, path, next, kindAt);\n // The op rebuilds every ancestor's array (spine copy) and re-seats its\n // rows' descendant arrays under new indices — those paths' records no\n // longer describe the arrays now living there. The op's OWN path keeps\n // its records: earlier same-batch ops still chain.\n clearArrayOpsUnder(store, path, true);\n // Record BEFORE the write, from the exact references the write uses:\n // zustand notifies subscribers synchronously inside setState, so a\n // reentrant same-path write would otherwise interleave the log order\n // AND make a post-setState getState() read pair this op's mapping with\n // a `to` spanning two writes — a corrupt record that can replay to\n // wrong row ids. The mapping is the inverted IndexMapper — the same\n // mapper that re-keys errors/touched below, one source of truth.\n // Guards: an op on an absent slot (push into an undefined array) has no\n // prior reference to chain from, and a write setAtPath REFUSES (huge\n // index, non-plain ancestor) must not log a transition the store never\n // performed — value reconciliation covers both.\n if (Array.isArray(current) && getAtPath(written, path) === next) {\n recordArrayOp(store, path, {\n from: current,\n to: next,\n mapping: invertMapper(mapper, current.length, next.length),\n });\n }\n store.setState((state) => {\n return {\n ...state,\n values: written,\n ...errorChannels(state, {\n schemaErrors: reKeyByArrayPath(state.schemaErrors, path, mapper),\n // Server entries on rows follow their rows through the index\n // mapping — a verdict on \"items.1.name\" is still vouched for after\n // the op moves it to \"items.0.name\" (that row's value didn't\n // change). Entries at the array itself or an ancestor release: the\n // op changed that value.\n serverErrors: releaseAncestorEntries(\n reKeyByArrayPath(state.serverErrors, path, mapper),\n path,\n ),\n }),\n touched: reKeyByArrayPath(state.touched, path, mapper),\n // Drop (don't re-key) in-flight flags under the array: the op changes\n // `values`, so every pass they belong to fails its values-changed\n // guard and never commits — but each pass's cleanup omits its\n // ORIGINAL key, so a re-keyed entry would be orphaned and stick\n // forever. Dropped, the flag is gone now and the cleanup is a\n // harmless no-op.\n isValidating: omitScope(state.isValidating, [path]),\n };\n });\n };\n\n const inFlight: { count: number; baseline: boolean } = {\n count: 0,\n baseline: false,\n };\n\n const submit = async (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n submitOptions?: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>> => {\n if (inFlight.count > 0 && submitOptions?.force !== true) {\n return { kind: \"skipped\" };\n }\n if (inFlight.count === 0) {\n inFlight.baseline = store.getState().isSubmitting;\n }\n inFlight.count += 1;\n store.setState((state) => ({\n ...state,\n isSubmitting: true,\n submitCount: state.submitCount + 1,\n }));\n\n try {\n const pass = claimPass(SUBMIT_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n const result = await validateAsync(schema, valuesAtStart);\n\n // Stale-commit contract (mirrors validateAsyncOnForm's guard): if the\n // values changed while validation was in flight (setValue/reset/\n // adoptValues), the verdict describes a snapshot the form no longer\n // holds — skip every state write (no error commit, no touched marks;\n // that state belongs to the new values). The ownership token catches\n // what the values reference can't: a bare reset() on a pristine form\n // restores the same values reference but clears the token map, and a\n // concurrent submit({ force: true }) re-claims the token — the LAST\n // submit owns the writes. The handlers still run and the result still\n // reports the snapshot's verdict, so callers decide what it means for\n // them.\n const stale =\n sequences.get(SUBMIT_SEQ_KEY) !== pass ||\n store.getState().values !== valuesAtStart;\n\n if (result.kind === \"invalid\") {\n if (!stale) {\n store.setState((state) => {\n const committed = commitFullPass(state, result.errors);\n return {\n ...state,\n ...committed,\n // Mark every errored field touched so touched-gated error UIs\n // show something after the canonical first failed submit. The\n // \"\" key (schema-level refine) has no field to touch.\n touched: {\n ...state.touched,\n ...Object.fromEntries(\n Object.keys(committed.errors)\n .filter((k) => k !== \"\")\n .map((k) => [k, true]),\n ),\n },\n };\n });\n }\n const merged = stale ? result.errors : store.getState().errors;\n try {\n onInvalid?.(merged);\n } catch (error) {\n // Same contract as a throwing onValid below: a failing caller\n // handler resolves as { kind: \"error\" }, never a rejection out of\n // a DOM event handler.\n return { kind: \"error\", error };\n }\n return { kind: \"invalid\", errors: merged };\n }\n\n if (!stale) {\n store.setState((state) => ({\n ...state,\n ...commitFullPass(state, emptyErrors),\n }));\n }\n try {\n await onValid(result.data);\n } catch (error) {\n // A throwing onValid is the caller's failure, not a validation\n // verdict: resolve with it (so handleSubmit-as-event-handler never\n // leaves an unhandled rejection) and write no error state.\n submitOptions?.onError?.(error);\n return { kind: \"error\", error };\n }\n return { kind: \"valid\", data: result.data };\n } finally {\n inFlight.count -= 1;\n if (inFlight.count === 0) {\n const baseline = inFlight.baseline;\n store.setState((state) => ({ ...state, isSubmitting: baseline }));\n }\n }\n };\n\n if (options.validateOnMount === true) {\n // Async schemas route themselves: validate() returns a \"pending\" result\n // whose background pass writes the error map when it settles.\n validate();\n }\n\n return Object.freeze({\n schema,\n store,\n getState: store.getState,\n subscribe: store.subscribe,\n getField: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n getAtPath(store.getState().values, path) as FieldValue<\n z.input<TSchema>,\n P\n >,\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => {\n const ref: { current: FieldSnapshot<unknown> } = {\n current: snapshotField(store.getState(), path),\n };\n return store.subscribe((state) => {\n const next = snapshotField(state, path);\n if (!shallowFieldEqual(ref.current, next)) {\n ref.current = next;\n listener(next as FieldSnapshot<FieldValue<z.input<TSchema>, P>>);\n }\n });\n },\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => {\n const ref: { current: unknown } = {\n current: getAtPath(store.getState().values, path),\n };\n return store.subscribe((state) => {\n const next = getAtPath(state.values, path);\n if (!Object.is(ref.current, next)) {\n const prev = ref.current;\n ref.current = next;\n listener(\n next as FieldValue<z.input<TSchema>, P>,\n prev as FieldValue<z.input<TSchema>, P>,\n );\n }\n });\n },\n watchValues: (listener) => {\n const ref: { current: Values } = { current: store.getState().values };\n return store.subscribe((state) => {\n if (state.values !== ref.current) {\n const prev = ref.current;\n ref.current = state.values;\n listener(state.values, prev);\n }\n });\n },\n setValue: (path: string, value: unknown) => {\n // Identity guard: writing the value already at the path is a FULL\n // no-op — same state reference, no values rebuild, no dirty/error\n // recompute, no subscriber notifications. Without it, every no-op\n // write rebuilt the values spine, so useFormValues re-rendered and\n // watchValues/onValuesChange fired on nothing — and a two-way sync\n // that echoes values back (form A watches form B and vice versa)\n // recursed until the stack overflowed. Object.is matches the\n // library's other change detectors (watchValue, useStore); note it\n // also skips the server-error release and op-log clearing below —\n // deliberately, since no value changed. One carve-out: an\n // `undefined` write only no-ops when the slot actually EXISTS —\n // writing undefined over an absent key CREATES the key (a real\n // change: key-count dirtiness, the persisted shape), so it must\n // still go through. A non-undefined Object.is match implies the own\n // slot exists (reads are own-key only), so the walk runs for\n // undefined writes alone.\n const currentValues = store.getState().values;\n if (\n Object.is(getAtPath(currentValues, path), value) &&\n (value !== undefined || hasOwnSlot(currentValues, path))\n ) {\n return;\n }\n // A value write outside the array ops breaks every op chain whose\n // array it could rebuild — drop those records at the source so a\n // stale (or recurring, e.g. reset-restored) array reference can never\n // falsely chain against them.\n clearArrayOpsUnder(store, path);\n store.setState((state) => ({\n ...state,\n values: setAtPath(state.values, path, value, kindAt),\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n }));\n },\n setValues: (next) => {\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values: next,\n ...errorChannels(state, {\n serverErrors: releaseChangedSlices(\n state.serverErrors,\n state.values,\n next,\n ),\n }),\n }));\n },\n setTouched: (path: string, touched: boolean = true) =>\n store.setState((state) => ({\n ...state,\n touched: { ...state.touched, [path]: touched },\n })),\n setSubmitting: (value) =>\n store.setState((state) => ({ ...state, isSubmitting: value })),\n setMode: (mode) => store.setState((state) => ({ ...state, mode })),\n setReValidateMode: (reValidateMode) =>\n store.setState((state) => ({ ...state, reValidateMode })),\n setError: (path: string, errors: string | readonly string[]) => {\n const list = typeof errors === \"string\" ? [errors] : errors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors:\n list.length === 0\n ? omitKey(state.serverErrors, path)\n : { ...state.serverErrors, [path]: list },\n }),\n }));\n },\n setErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, { serverErrors: errors }),\n })),\n addErrors: (errors) =>\n store.setState((state) => {\n // Two passes over the incoming map, not a per-entry fold: the old\n // reduce spread (or omitKey-rebuilt) the whole channel once per\n // entry, quadratic in the number of server fields. Object.fromEntries\n // and the spread define computed keys as own properties, so a\n // server field named \"__proto__\" still lands like everywhere else.\n const entries = Object.entries(errors);\n const removed = new Set(\n entries\n .filter(([, list]) => list === undefined || list.length === 0)\n .map(([key]) => key),\n );\n const added = Object.fromEntries(\n entries.filter(([, list]) => list !== undefined && list.length > 0),\n );\n return {\n ...state,\n ...errorChannels(state, {\n serverErrors: {\n ...omitKeys(state.serverErrors, removed),\n ...added,\n },\n }),\n };\n }),\n clearErrors: (path?: string) =>\n store.setState((state) => {\n // Clears both channels (schema errors return on the next validation\n // pass). A field path also clears its descendants (\"items\" covers\n // \"items.0.name\"), consistent with field-scoped validation; the root\n // \"\" is a single key (the schema-level refine slot, symmetric with\n // setError(\"\")); clearing everything is clearErrors() with no\n // argument.\n const scrub = (map: ErrorMap): ErrorMap =>\n path === undefined ? emptyErrors : omitScope(map, [path]);\n return {\n ...state,\n ...errorChannels(state, {\n schemaErrors: scrub(state.schemaErrors),\n serverErrors: scrub(state.serverErrors),\n }),\n };\n }),\n updateState: (updater) => {\n // The updater runs against the current state OUTSIDE setState so the\n // op-log decision below can precede the notification: subscribers\n // derive array row ids synchronously inside setState, and a values\n // patch that reintroduces an earlier array reference (a snapshot of\n // values taken before an op) would otherwise chain the op's stale\n // record against it during that notification, then have the log\n // cleared too late to matter. Same ordering setValues/adoptValues\n // keep. Semantically identical to setState(updater): both read the\n // same synchronous state.\n const state = store.getState();\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return;\n // Spread-style updaters carry `errors` with its current reference —\n // only a genuinely foreign map (a plain-JS write; TS forbids it via\n // the patch type) earns the warning.\n if (patch.errors !== undefined && patch.errors !== state.errors) {\n console.warn(\n \"[formstand] `errors` is derived from schemaErrors/serverErrors — patch those channels instead; the direct `errors` patch is ignored.\",\n );\n }\n // Re-derive against the CURRENT merged map (not the patched one), so\n // an ignored `errors` patch can't leak even its object identity into\n // state and re-fire identity-based subscribers.\n const next = { ...state, ...patch };\n // A values patch is a chain-breaking write like setValues.\n if (next.values !== state.values) {\n clearArrayOpsUnder(store, \"\");\n }\n // A values patch is also a bulk write under the documented release\n // contract (FormState.serverErrors: an entry releases when the value\n // on its spine changes), so it releases exactly what setValues\n // releases: the entries whose slice actually changed. An explicit\n // serverErrors patch in the same call wins as given, which is what\n // setValues followed by setErrors would leave behind: the caller is\n // stating the channel for the new values.\n const serverErrors =\n patch.serverErrors !== undefined\n ? patch.serverErrors\n : next.values !== state.values\n ? releaseChangedSlices(state.serverErrors, state.values, next.values)\n : state.serverErrors;\n store.setState(() => ({\n ...next,\n ...errorChannels(state, {\n schemaErrors: next.schemaErrors,\n serverErrors,\n }),\n }));\n },\n adoptValues: (values) => {\n // Rebasing values invalidates any in-flight async validation (the\n // values-reference guard drops its write), so the per-path ownership\n // tokens can be released too rather than growing without bound.\n sequences.clear();\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values,\n initialValues: values,\n ...errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n }),\n // Clearing `sequences` disowns every in-flight pass, including its\n // flag cleanup (the ownership check fails, so it never writes) —\n // clear the flags here too, mirroring reset(), or they'd stick.\n isValidating: emptyBools,\n isValidatingForm: false,\n }));\n },\n reset: (nextInitial, resetOptions) => {\n sequences.clear();\n // reset can restore the exact initialValues REFERENCE, so stale\n // records must go before an old array reference recurs and falsely\n // chains against them.\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => {\n // Merge only when both sides are plain records; a partial for an\n // array/scalar-rooted schema replaces wholesale (spreading an array\n // into {...} would corrupt the values shape).\n const init: typeof state.initialValues =\n nextInitial === undefined\n ? state.initialValues\n : isPlainObject(state.initialValues) && isPlainObject(nextInitial)\n ? ({\n ...state.initialValues,\n ...nextInitial,\n } as typeof state.initialValues)\n : (nextInitial as typeof state.initialValues);\n return {\n ...state,\n values: init,\n initialValues: init,\n ...(resetOptions?.keepErrors === true\n ? {}\n : errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n })),\n touched:\n resetOptions?.keepTouched === true ? state.touched : emptyBools,\n isSubmitting: false,\n submitCount:\n resetOptions?.keepSubmitCount === true ? state.submitCount : 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n };\n });\n },\n resetField: (path: string) => {\n // slotAtPath, not getAtPath: a path addressing NO slot in\n // initialValues (an out-of-range array index — an appended row past\n // the initial length, or a path through an absent ancestor) must not\n // be \"reset\" by writing undefined into the values tree — that would\n // leave a mid-array hole ([rowA, undefined]) that crashes row renders\n // and fails the schema. The value stays as-is; the field state still\n // clears. A key merely absent on an initial plain record IS an\n // addressable slot: resetting it writes the legitimate empty\n // undefined, exactly as before.\n const initialSlot = slotAtPath(\n store.getState().initialValues,\n path,\n );\n if (!initialSlot.exists) {\n console.warn(\n `[formstand] resetField(\"${path}\"): path has no initial value (e.g. an appended array row); value left unchanged, field state cleared.`,\n );\n }\n if (initialSlot.exists) {\n // A restored initial slice can carry array references the op log\n // has already seen (chain-breaking write, like setValue).\n clearArrayOpsUnder(store, path);\n }\n store.setState((state) => ({\n ...state,\n values: initialSlot.exists\n ? setAtPath(state.values, path, initialSlot.value, kindAt)\n : state.values,\n // A runtime \"\" path scopes the whole form (the imperative surface is\n // string-typed even though FieldPath excludes \"\"). Server entries\n // follow the setValue release contract (releaseSpine).\n ...errorChannels(state, {\n schemaErrors:\n path === \"\" ? emptyErrors : omitScope(state.schemaErrors, [path]),\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n touched:\n path === \"\" ? emptyBools : omitScope(state.touched, [path]),\n isValidating:\n path === \"\" ? emptyBools : omitScope(state.isValidating, [path]),\n }));\n },\n validate,\n validateField,\n validateFields,\n validateAsync: validateAsyncOnForm,\n validateFieldAsync,\n validateFieldsAsync,\n submit,\n arrayPush: (path: string, item: unknown) =>\n applyArrayOp(path, (arr) => [...arr, item], identityMapper),\n arrayRemove: (path: string, index: number) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), ...arr.slice(index + 1)],\n removeAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index < len,\n ),\n arrayInsert: (path: string, index: number, item: unknown) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), item, ...arr.slice(index)],\n insertAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index <= len,\n ),\n arrayMove: (path: string, from: number, to: number) =>\n applyArrayOp(\n path,\n (arr) => {\n const without = [...arr.slice(0, from), ...arr.slice(from + 1)];\n return [...without.slice(0, to), arr[from], ...without.slice(to)];\n },\n moveFromTo(from, to),\n (len) =>\n Number.isInteger(from) &&\n Number.isInteger(to) &&\n from >= 0 &&\n from < len &&\n to >= 0 &&\n to < len,\n ),\n arraySwap: (path: string, a: number, b: number) =>\n applyArrayOp(\n path,\n (arr) => arr.map((v, i) => (i === a ? arr[b] : i === b ? arr[a] : v)),\n swapIndices(a, b),\n (len) =>\n Number.isInteger(a) &&\n Number.isInteger(b) &&\n a >= 0 &&\n a < len &&\n b >= 0 &&\n b < len,\n ),\n handleSubmit:\n (onValid, onInvalid, opts) =>\n async (event) => {\n event?.preventDefault();\n const result = await submit(onValid, onInvalid, opts);\n // The event-handler form is fire-and-forget: nobody reads the\n // resolved result, so a save failure with no onError handler\n // would otherwise vanish COMPLETELY — no state, no rejection, no\n // log — and the button just re-enables. Dev builds say so once\n // per occurrence; production stays silent by design (resolving\n // instead of rejecting is the documented contract).\n if (\n result.kind === \"error\" &&\n opts?.onError === undefined &&\n isDevBuild()\n ) {\n console.warn(\n \"[formstand] submit handler threw and nothing observed it — the form shows no feedback. Pass { onError } to handleSubmit (or setError inside your handler):\",\n result.error,\n );\n }\n return result;\n },\n diff: () => {\n const state = store.getState();\n return Object.fromEntries(\n dirtyPathsOf(state.values, state.initialValues, \"\").map((path) => [\n path,\n getAtPath(state.values, path),\n ]),\n );\n },\n dirtyFields: () => {\n const state = store.getState();\n return dirtyPathsOf(state.values, state.initialValues, \"\");\n },\n snapshot: () => store.getState(),\n restore: (snap) => {\n // A snapshot restores PRIOR array references — exactly the recurring\n // references stale op records could falsely chain against.\n clearArrayOpsUnder(store, \"\");\n store.setState(() => {\n // Snapshots can come from persistence or hand construction: default\n // missing channels (pre-channel shapes) and re-derive the merged map\n // so the errors-is-derived invariant holds at this boundary too —\n // otherwise an inconsistent snapshot renders phantom errors until\n // the next write silently rewrites them (or crashes a channel scan).\n const schemaErrors = snap.schemaErrors ?? emptyErrors;\n const serverErrors = snap.serverErrors ?? emptyErrors;\n return {\n ...snap,\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n snap.errors ?? emptyErrors,\n ),\n // In-flight state is owned by live passes, never by snapshots: a\n // snapshotted flag has no pass left to clear it (the pass that set\n // it cleared its ORIGINAL entry when it settled), so restoring one\n // would stick it forever. isSubmitting follows the same rule — a\n // mid-submit snapshot restored later must not disable submit\n // buttons forever, so it reflects the LIVE submit count instead of\n // the snapshotted flag (a live pass's finally still resets it).\n isValidating: emptyBools,\n isValidatingForm: false,\n isSubmitting: inFlight.count > 0,\n };\n });\n },\n }) as Form<TSchema, D>;\n};\n","export type ValidationMode =\n | \"onChange\"\n | \"onBlur\"\n | \"onSubmit\"\n // Validate on blur always; on change only once the field has been touched.\n | \"onTouched\"\n // Validate on both change and blur.\n | \"all\";\n\nexport type ValidationTrigger = \"change\" | \"blur\";\n\nexport const shouldValidateOn = (\n trigger: ValidationTrigger,\n mode: ValidationMode,\n reValidateMode: ValidationMode,\n submitAttempted: boolean,\n touched: boolean = false,\n): boolean => {\n const effective = submitAttempted ? reValidateMode : mode;\n switch (effective) {\n case \"onChange\":\n return trigger === \"change\";\n case \"onBlur\":\n return trigger === \"blur\";\n case \"onSubmit\":\n return false;\n case \"onTouched\":\n return trigger === \"blur\" || touched;\n case \"all\":\n return true;\n }\n};\n","// A trailing-edge debouncer: `schedule` replaces any pending call, `cancel`\n// drops it. One production for the two timers the library keeps (the\n// persistence draft writer and useField's async-validation debounce), so\n// the cancel-then-reschedule rule lives in one place. Deliberately NOT a\n// `debounce(fn)` wrapper: both callers close over per-call data (the values\n// to write, the value that scheduled a validation) and decide at fire time,\n// so the scheduled thunk is the unit, not a fixed function.\nexport type Debouncer = Readonly<{\n schedule: (run: () => void) => void;\n cancel: () => void;\n // True while a scheduled run has not fired or been cancelled.\n readonly pending: () => boolean;\n}>;\n\n// A delay of 0 runs synchronously — the callers treat 0 as \"no debounce\"\n// and the caller-visible ordering (write happens before schedule returns)\n// is part of their contract.\nexport const createDebouncer = (ms: number): Debouncer => {\n // Sanctioned mutable ref for the timer handle (same shape as the\n // codebase's other timer/subscription refs).\n const timer: { current: ReturnType<typeof setTimeout> | null } = {\n current: null,\n };\n const cancel = (): void => {\n if (timer.current !== null) {\n clearTimeout(timer.current);\n timer.current = null;\n }\n };\n const schedule = (run: () => void): void => {\n cancel();\n if (ms === 0) {\n run();\n return;\n }\n timer.current = setTimeout(() => {\n timer.current = null;\n run();\n }, ms);\n };\n return Object.freeze({\n schedule,\n cancel,\n pending: () => timer.current !== null,\n });\n};\n","import type { z } from \"zod\";\nimport type { Form } from \"./createForm\";\nimport { createDebouncer } from \"./debounce\";\nimport type { DefaultPathDepth, PathDepth } from \"./fieldPath\";\n\n// Draft persistence for a form: watch the values, debounce-write them as JSON\n// under a storage key, and re-apply a found draft on the next visit. This is\n// the autosave recipe (examples/AutosaveForm) promoted to a helper — same\n// caveat as the recipe: drafts round-trip through JSON, so they are for\n// JSON-safe values only (Dates become strings, undefined slots drop; the\n// helper does NOT try to revive them).\n\n// Structural storage contract — window.localStorage and sessionStorage\n// satisfy it, as does any Map-backed stub in tests.\nexport type PersistStorage = Readonly<{\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n}>;\n\n// TSchema is phantom for now (no option carries schema-typed data — drafts\n// are typed at the persistForm call, not here), but the parameter keeps the\n// option bag tied to the form it configures and leaves room for schema-typed\n// options later without a breaking signature change.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type PersistOptions<TSchema extends z.ZodType> = Readonly<{\n // Storage key the draft lives under.\n key: string;\n // Defaults to globalThis.localStorage, guarded: where it is absent or\n // throws on access (SSR, locked-down browsers), persistence is a no-op but\n // the helper still returns working handles.\n storage?: PersistStorage;\n // Trailing-edge debounce for writes. Default 300; 0 writes synchronously\n // on every change.\n debounceMs?: number;\n // Bump when the schema's SHAPE changes and old drafts should be discarded\n // rather than applied. A draft is stored with the version it was written\n // under and ignored when the two disagree, which is the only reliable way\n // to catch a renamed or removed field: an absent key is indistinguishable\n // from an optional the user never filled in, so the automatic guard below\n // cannot tell those apart. Leaving this unset keeps the stored format\n // exactly as it was, so existing drafts survive an upgrade.\n version?: string | number;\n // How a found draft is applied on start, and what load() does later.\n // \"adopt\" (default) uses form.adoptValues: the draft becomes the new\n // baseline, so the form reads CLEAN. \"edit\" uses form.setValues: the\n // draft loads but stays DIRTY against the original initial values.\n // \"manual\" never auto-applies; the caller decides when via the returned\n // load(), which then applies with adopt semantics (a caller-triggered\n // load is a rebase, not an edit; pick \"edit\" for dirty-vs-initials).\n // \"restore\" is the pre-0.22 spelling of \"edit\", kept as an alias: it\n // collided with form.restore(snapshot), which puts back a whole\n // FormState, and with load() (which used to be called restore), three\n // restore-ish words for three behaviors.\n apply?: \"adopt\" | \"edit\" | \"restore\" | \"manual\";\n}>;\n\nexport type PersistHandle = Readonly<{\n // Load + apply the stored draft now (see `apply` for the semantics):\n // returns true if a draft existed, parsed, and applied. Corrupt or absent\n // JSON returns false and never throws. (Named load, not restore: the\n // DEFAULT application is adoptValues — a rebase that reads clean — and\n // \"restore\" promised setValues semantics the method only has when the\n // apply option asks for them.)\n load: () => boolean;\n // Delete the stored draft (e.g. after a successful submit). Also cancels\n // any pending debounced write, so a stale draft isn't re-written right\n // after clearing.\n clear: () => void;\n // Stop watching the form (does not clear storage). Cancels any pending\n // debounced write.\n dispose: () => void;\n}>;\n\n// The JSON kind of a value, as it exists AFTER a storage round trip. The\n// reference side is round-tripped before comparison rather than special-cased,\n// so a Date (which stores as a string) compares against a string and the\n// documented Date-becomes-string limitation is not mistaken for corruption.\nconst kindOf = (value: unknown): string =>\n value === null\n ? \"null\"\n : Array.isArray(value)\n ? \"array\"\n : typeof value;\n\n// Does the draft CONFLICT with the shape the form expects? Only overlapping\n// paths are compared, and only their kinds.\n//\n// Deliberately not a key-set equality check. JSON drops undefined slots, so an\n// optional the user never filled is absent from the reference, and an optional\n// they did fill is present only in the draft. Neither is evidence of a schema\n// change, so treating a key-set difference as corruption would throw away\n// perfectly good drafts on any form with an optional field. What IS\n// unambiguous is a path holding a string on one side and an object on the\n// other: no edit produces that, only a changed schema. Renames and removals\n// are the `version` option's job.\nconst conflictsWith = (draft: unknown, reference: unknown): boolean => {\n // null and undefined carry NO shape information, on either side. null is the\n // canonical empty for a nullable field (see emptyValue), so it can legally\n // appear at any nullable path whatever that path's filled shape is: a\n // nullable object starting null and then filled in, or starting filled and\n // then cleared, are both ordinary edits. Reading either as a kind conflict\n // would discard the drafts of every form with a nullable field.\n if (draft === undefined || draft === null) return false;\n if (reference === undefined || reference === null) return false;\n const draftKind = kindOf(draft);\n const referenceKind = kindOf(reference);\n if (draftKind !== referenceKind) return true;\n if (draftKind === \"array\") {\n const [d] = draft as readonly unknown[];\n const [r] = reference as readonly unknown[];\n // Row counts differ for ordinary reasons; the ROW SHAPE is the signal.\n return conflictsWith(d, r);\n }\n if (draftKind === \"object\") {\n const d = draft as Record<string, unknown>;\n const r = reference as Record<string, unknown>;\n return Object.keys(d).some((key) => conflictsWith(d[key], r[key]));\n }\n return false;\n};\n\n// Resolved lazily inside persistForm — never at module scope — so importing\n// this module is SSR-safe. jsdom provides localStorage; node without DOM may\n// lack it (typeof check) or throw on access (try/catch).\nconst defaultStorage = (): PersistStorage | null => {\n try {\n return typeof globalThis.localStorage === \"undefined\"\n ? null\n : globalThis.localStorage;\n } catch {\n return null;\n }\n};\n\nexport const persistForm = <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const storage = options.storage ?? defaultStorage();\n const debounceMs = options.debounceMs ?? 300;\n const apply = options.apply ?? \"adopt\";\n\n // \"restore\" is a plain values write (dirty vs the original initials);\n // \"adopt\" and \"manual\" rebase via adoptValues so the draft reads clean.\n const applyDraft = (values: z.input<TSchema>): void =>\n apply === \"edit\" || apply === \"restore\"\n ? form.setValues(values)\n : form.adoptValues(values);\n\n // The shape the draft is checked against, in stored form. Round-tripping\n // the reference through JSON puts both sides in the same representation.\n const referenceShape = (): unknown => {\n try {\n return JSON.parse(JSON.stringify(form.getState().initialValues));\n } catch {\n // A non-serializable initial value means we cannot compare; the write\n // path would have failed too, so let the draft through unchecked\n // rather than rejecting every draft for this form.\n return undefined;\n }\n };\n\n const load = (): boolean => {\n // Every storage touch is guarded: private-mode/security errors read as\n // \"no draft\", corrupt JSON parses as \"no draft\" — load never throws.\n try {\n const raw = storage === null ? null : storage.getItem(options.key);\n if (raw === null) return false;\n const parsed: unknown = JSON.parse(raw);\n // Versioned drafts are wrapped; unversioned ones are the bare values,\n // which is the format every existing draft is already in.\n const versioned =\n options.version !== undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"__v\" in parsed;\n if (options.version !== undefined && !versioned) return false;\n // The config-downgrade hole: a draft WRITTEN with a version is the\n // {__v, values} wrapper, and if the app later ships without the\n // version option, nothing above catches it — the wrapper's keys\n // don't overlap the reference shape, so conflictsWith stays quiet\n // and the WRAPPER OBJECT gets adopted as form values (then\n // re-persisted, making the corruption self-sustaining). A versioned\n // draft under a version-less config is a contract the current app\n // no longer declares: discard it, like every other draft the config\n // cannot vouch for.\n if (\n options.version === undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n Object.hasOwn(parsed, \"__v\") &&\n Object.hasOwn(parsed, \"values\")\n ) {\n return false;\n }\n const wrapper = parsed as unknown as {\n readonly __v?: unknown;\n readonly values?: unknown;\n };\n if (versioned && wrapper.__v !== options.version) return false;\n // A wrapper with no payload is not a draft. Only reachable via tampered\n // or foreign storage, but applying it would write undefined over the\n // whole values object.\n if (versioned && wrapper.values === undefined) return false;\n const values = (versioned ? wrapper.values : parsed) as z.input<TSchema>;\n // A null or missing TOP-LEVEL payload is not a draft either (an\n // unversioned \"null\" in storage, or a versioned wrapper holding\n // values: null). conflictsWith deliberately treats null as shapeless\n // because nested nullable fields legally hold it, so the top level is\n // the one place to refuse it: adoptValues(null) would make every path\n // read on the form crash and then re-persist the same null.\n if (values === null || values === undefined) return false;\n // A draft whose shape conflicts with the form's is from another schema.\n // Applying it would rebase the form onto values it cannot validate, and\n // because \"adopt\" clears errors, the form would read CLEAN while holding\n // them. Ignore it instead; the next change overwrites it.\n const reference = referenceShape();\n if (reference !== undefined && conflictsWith(values, reference)) {\n return false;\n }\n applyDraft(values);\n return true;\n } catch {\n return false;\n }\n };\n\n const writeDraft = (values: z.input<TSchema>): void => {\n // Quota/private-mode setItem errors just skip this write. The wrapper is\n // written ONLY when a version is configured, so a form that never opts in\n // keeps the exact bytes it wrote before and its existing drafts still load.\n try {\n storage?.setItem(\n options.key,\n JSON.stringify(\n options.version === undefined\n ? values\n : { __v: options.version, values },\n ),\n );\n } catch {\n /* persistence is best-effort */\n }\n };\n\n // Trailing-edge debounce of draft writes (0 = write synchronously).\n const writes = createDebouncer(debounceMs);\n const cancelPending = (): void => writes.cancel();\n\n // Auto-apply BEFORE subscribing, so applying the draft doesn't immediately\n // schedule a write of the values we just read.\n if (apply !== \"manual\") {\n load();\n }\n\n const unsubscribe = form.watchValues((values) => {\n writes.schedule(() => writeDraft(values));\n });\n\n return Object.freeze({\n load,\n clear: () => {\n // Cancel first: a pending debounced write landing after removeItem\n // would silently resurrect the draft.\n cancelPending();\n try {\n storage?.removeItem(options.key);\n } catch {\n /* persistence is best-effort */\n }\n },\n dispose: () => {\n cancelPending();\n unsubscribe();\n },\n });\n};\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport {\n type PersistHandle,\n type PersistOptions,\n persistForm,\n} from \"../core/persist\";\n\n// The React lifecycle wrapper persistForm was missing: every useForm\n// consumer hand-wrote the mount/dispose effect (plus a ref to reach\n// clear() after submit), and calling persistForm during render\n// double-subscribed under StrictMode. This hook owns that dance:\n//\n// const form = useForm(schema, { initialValues });\n// const draft = usePersistForm(form, { key: \"profile-draft\" });\n// // ... later: draft.clear() after a successful submit.\n//\n// The returned handle is REFERENCE-STABLE across renders and delegates to\n// whichever inner subscription is currently live, so it is safe to close\n// over in submit handlers. Before the mount effect has run (and after\n// unmount) load() reads false and clear() is a no-op — the same\n// guarded no-throw posture persistForm itself has.\n//\n// Options are read when the subscription (re)starts — on mount, and again\n// if `form` or `options.key` changes — not on every render, mirroring\n// useForm's locked-options rule; pass a stable options object or accept\n// that later edits to it are ignored until the key or form changes.\nexport const usePersistForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const inner = useRef<PersistHandle | null>(null);\n const latestOptions = useRef(options);\n // An effect, not a render-time ref write (refs are off-limits during\n // render): it runs before the subscription effect below in the same\n // commit, so a resubscribe always reads the options of the render that\n // triggered it.\n useEffect(() => {\n latestOptions.current = options;\n });\n\n const key = options.key;\n useEffect(() => {\n const handle = persistForm(form, latestOptions.current);\n inner.current = handle;\n return () => {\n inner.current = null;\n handle.dispose();\n };\n // StrictMode's mount-cleanup-mount runs this twice: each pass gets its\n // own subscription and disposes the previous, so no double-writes.\n }, [form, key]);\n\n return useMemo(\n () => ({\n load: () => inner.current?.load() ?? false,\n clear: () => inner.current?.clear(),\n // dispose stops THIS component's watching early; the effect cleanup\n // still runs its own dispose harmlessly (persistForm's dispose is\n // idempotent by construction — it only cancels and unsubscribes).\n dispose: () => inner.current?.dispose(),\n }),\n [],\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport {\n type CreateFormOptions,\n type Form,\n createForm,\n} from \"../core/createForm\";\nimport { valuesEqual } from \"../core/equality\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// Lazy-creates a Form bound to this component instance. Schema and options are\n// locked in on the first render; later changes are ignored (warned once below).\n// D mirrors createForm's inference: a literal from `options.pathDepth`\n// (constrained to PathDepth, 0-25), defaulting to the 9-segment typed-path\n// budget.\nexport const useForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n // NoInfer for the same reason createForm's return has it: an inline\n // `useFieldArray(useForm(schema, opts), \"items\")` would otherwise infer\n // the depth from the outer call's unresolved parameter.\n): Form<TSchema, NoInfer<D>> => {\n const formRef = useRef<Form<TSchema, D> | null>(null);\n if (formRef.current === null) {\n formRef.current = createForm(schema, options);\n }\n // Lazy init of an external store handle — the sanctioned useRef exception\n // (react.dev: \"avoiding recreating the ref contents\"); the rule can't see\n // that this read is guarded by the null-check init above.\n // eslint-disable-next-line react-hooks/refs\n const form = formRef.current;\n\n const mountInitialsRef = useRef(options.initialValues);\n const warnedRef = useRef(false);\n useEffect(() => {\n // Two footguns, one warning: a new schema reference, or initial values\n // whose CONTENT changed after mount (the async-fetch pattern\n // `initialValues: data ?? {}` with a module-hoisted schema — the schema\n // check alone would never see it). Structural compare, so inline object\n // literals that re-create identical options every render stay silent.\n const changedInitials =\n !Object.is(options.initialValues, mountInitialsRef.current) &&\n !valuesEqual(options.initialValues, mountInitialsRef.current);\n if (!warnedRef.current && (form.schema !== schema || changedInitials)) {\n warnedRef.current = true;\n console.warn(\n \"[formstand] useForm received a different schema or initial values \" +\n \"after the first render; schema and options changes are ignored \" +\n \"for the life of the component. If the schema is defined inline \" +\n \"this is harmless (but consider hoisting it to module scope). For \" +\n \"initial values that arrive later (e.g. from a fetch), call \" +\n \"form.adoptValues(values) or form.reset(values) instead.\",\n );\n }\n }, [form, schema, options.initialValues]);\n\n return form;\n};\n","import type { ChangeEvent } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\n\nexport type TextInputProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type NumberInputProps = Readonly<{\n type: \"number\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type DateInputProps = Readonly<{\n type: \"date\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type CheckboxProps = Readonly<{\n type: \"checkbox\";\n name: string;\n checked: boolean;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type SelectProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLSelectElement>) => void;\n onBlur: () => void;\n}>;\n\n// THE predicate for \"does this field currently show an error\" — shared by\n// the aria-invalid mapping here and the field shells in fields.tsx, so the\n// notion of \"showing an error\" cannot drift between bindings.\nexport const hasFieldError = (\n error: readonly string[] | undefined,\n): boolean => error !== undefined && error.length > 0;\n\nconst ariaInvalid = (\n field: Readonly<{ error: readonly string[] | undefined }>,\n): true | undefined => (hasFieldError(field.error) ? true : undefined);\n\n// A cleared input writes back `field.emptyValue` when the schema ACCEPTS it\n// (`field.clearable`: optional, nullable, or defaulted — useField introspects\n// the form's zod schema), so z.number().nullable() round-trips to null and\n// z.string().optional() to undefined instead of a lingering \"\". A required\n// string cleared to \"\" stays \"\": writing undefined there would trade a\n// visible value the schema can judge for a hole it rejects.\n\n// Canonical display text for a numeric field value (\"\" for empty/NaN; null\n// counts as empty so nullable fields don't render the literal text \"null\").\n// Shared with NumberField so the two number bindings can't drift.\nexport const numberToInputText = (value: number | null | undefined): string =>\n value === undefined || value === null || Number.isNaN(value)\n ? \"\"\n : String(value);\n\nexport type ParsedNumberText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"number\"; value: number }>\n // Text that doesn't parse to a finite number — partial entries (\"-\",\n // \"1.\", \"1e\") or Infinity.\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning user-typed text into a numeric field value:\n// whitespace counts as empty (Number(\" \") is 0) and non-finite results are\n// rejected. Shared with NumberField.\nexport const parseNumberText = (text: string): ParsedNumberText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const parsed = Number(text);\n return Number.isFinite(parsed)\n ? { kind: \"number\", value: parsed }\n : { kind: \"invalid\" };\n};\n\nexport const textInputProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): TextInputProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const text = e.target.value;\n // Deleting all text from a clearable field restores its emptyValue\n // (null or undefined), so it isn't left permanently dirty (or invalid)\n // by a visual no-op.\n field.setValue((text === \"\" && field.clearable ? field.emptyValue : text) as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const numberInputProps = <T extends number | null | undefined>(\n field: UseFieldReturn<T>,\n): NumberInputProps => ({\n type: \"number\",\n name: field.path,\n value: numberToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseNumberText(e.target.value);\n // \"invalid\" is a PARTIAL entry (a lone \"-\", \"1e\") — keep the stored\n // value untouched, matching useNumberInput's deliberate semantics,\n // instead of writing emptyValue mid-keystroke (which flashed a\n // required error and flipped dirty while the user was still typing).\n // \"empty\" still clears to emptyValue. Note browsers report \"\" for\n // badInput on type=\"number\", so some partial entries arrive as\n // \"empty\" regardless — useNumberInput (a text input with its own raw\n // state) remains the binding that preserves every keystroke.\n if (parsed.kind === \"invalid\") return;\n field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\n },\n onBlur: field.onBlur,\n});\n\n// Canonical display text for a Date field value — the local calendar date\n// as \"yyyy-MM-dd\" (what <input type=\"date\"> speaks). Local parts, NOT\n// toISOString(): a date picked as June 1 must not render as May 31 for\n// users west of UTC. Invalid Dates count as empty. Shared with DateField.\nexport const dateToInputText = (value: Date | null | undefined): string => {\n if (value === undefined || value === null || Number.isNaN(value.getTime())) {\n return \"\";\n }\n const pad = (part: number): string => String(part).padStart(2, \"0\");\n return `${String(value.getFullYear()).padStart(4, \"0\")}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;\n};\n\nexport type ParsedDateText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"date\"; value: Date }>\n // Not \"yyyy-MM-dd\", or parts that roll over (2026-02-31).\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning \"yyyy-MM-dd\" into a Date field value: LOCAL\n// midnight — a calendar date, not a UTC instant (new Date(\"2026-06-01\")\n// would be UTC midnight and read back as May 31 west of Greenwich).\n// Shared with DateField.\nexport const parseDateText = (text: string): ParsedDateText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n if (match === null) return { kind: \"invalid\" };\n const [, year, month, day] = match;\n const y = Number(year);\n const date = new Date(y, Number(month) - 1, Number(day));\n // The Date constructor maps two-digit years 0–99 to 1900–1999, so a valid\n // \"0099-01-01\" would fail the survival check below; force the literal year\n // back on for years under 100 before checking rollover.\n if (y < 100) date.setFullYear(y);\n // The parts must survive the Date constructor — rollovers are invalid,\n // not silently the 3rd of next month.\n return date.getFullYear() === y &&\n date.getMonth() === Number(month) - 1 &&\n date.getDate() === Number(day)\n ? { kind: \"date\", value: date }\n : { kind: \"invalid\" };\n};\n\nexport const dateInputProps = <T extends Date | null | undefined>(\n field: UseFieldReturn<T>,\n): DateInputProps => ({\n type: \"date\",\n name: field.path,\n value: dateToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseDateText(e.target.value);\n if (parsed.kind !== \"date\") {\n field.setValue(field.emptyValue as T);\n return;\n }\n // Preserve the existing value's time-of-day: <input type=\"date\"> only\n // edits the calendar date, so re-picking the SAME day on a value that\n // carried a time (an initial `new Date()`) must stay a no-op — otherwise\n // the new local-midnight Date differs from the timestamped original and\n // the field reads spuriously dirty. Changing the day keeps that time.\n const current = field.value;\n const next =\n current instanceof Date && !Number.isNaN(current.getTime())\n ? new Date(\n parsed.value.getFullYear(),\n parsed.value.getMonth(),\n parsed.value.getDate(),\n current.getHours(),\n current.getMinutes(),\n current.getSeconds(),\n current.getMilliseconds(),\n )\n : parsed.value;\n field.setValue(next as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const checkboxProps = <T extends boolean | null | undefined>(\n field: UseFieldReturn<T>,\n): CheckboxProps => ({\n type: \"checkbox\",\n name: field.path,\n checked: field.value ?? false,\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => field.setValue(e.target.checked as T),\n onBlur: field.onBlur,\n});\n\n// `?? \"\"` keeps the <select> controlled when the field has no value yet\n// (undefined for optional fields, null for nullable ones); pair it with an\n// <option value=\"\"> (SelectField renders one) so the blank state is a real\n// option instead of silently showing the first entry.\nexport const selectProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): SelectProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const v = e.target.value;\n field.setValue((v === \"\" && field.clearable ? field.emptyValue : v) as T);\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, useState } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\nimport { hasFieldError } from \"./inputProps\";\n\n// The raw-text editing pattern behind NumberField/useNumberInput,\n// generalized to ANY parsed-and-formatted value: phone numbers, currency,\n// percentages, locale-formatted anything. A naive controlled input\n// re-renders the canonical format on every keystroke, which eats the\n// separators and partial entries the user is mid-way through typing. This\n// hook keeps the raw text locally while editing, pushes PARSED values to\n// the form as soon as a keystroke parses, and snaps the display back to\n// the canonical format on blur — so the form always holds a real value\n// while the input stays typeable.\n\nexport type MaskedParse<TValue> =\n // A complete value — pushed to the form immediately.\n | Readonly<{ kind: \"value\"; value: TValue }>\n // Nothing entered — the field's emptyValue is pushed (null/undefined\n // per the schema, same rule as the number and date bindings).\n | Readonly<{ kind: \"empty\" }>\n // A partial or unparseable entry — kept as local text, the form value\n // untouched (matching useNumberInput's deliberate semantics).\n | Readonly<{ kind: \"invalid\" }>;\n\nexport type MaskedInputOptions<TValue> = Readonly<{\n // The single rule for turning user-typed text into a field value.\n parse: (text: string) => MaskedParse<TValue>;\n // Canonical display text for a field value — what blur snaps back to.\n format: (value: TValue) => string;\n}>;\n\nexport type MaskedInputBinding = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype MaskedEditState<TValue> = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a\n // partial entry). When field.value diverges, an external writer\n // (reset/adoptValues/another component) changed it — drop the raw text\n // so the input shows the external value.\n pushed: TValue | null | undefined;\n}>;\n\n// Generic over the field's OWN value type (nullability included), so an\n// optional field binds as naturally as a nullable one: parse/format speak\n// the non-null value, and the nullish side is the emptyValue round trip.\nexport const useMaskedInput = <TValue>(\n field: UseFieldReturn<TValue>,\n options: MaskedInputOptions<NonNullable<TValue>>,\n): MaskedInputBinding => {\n const [edit, setEdit] = useState<MaskedEditState<TValue>>({\n raw: null,\n pushed: undefined,\n });\n // Render-phase derived-state reset, same as useNumberInput: an external\n // value change while editing wins over the local text. Object.is works\n // for reference values too — the hook pushed the very instance it holds.\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit({ raw: null, pushed: undefined });\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value:\n raw ??\n (field.value === undefined || field.value === null\n ? \"\"\n : options.format(field.value as NonNullable<TValue>)),\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = options.parse(text);\n switch (parsed.kind) {\n case \"value\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"empty\": {\n // The same clearing rule as textInputProps: emptyValue only when\n // the schema ACCEPTS it (field.clearable: optional, nullable,\n // defaulted). A REQUIRED string field clears back to \"\", so it\n // reads clean against a \"\" initial and reports the author's\n // message (z.string().min(1, \"required\")) instead of zod's\n // \"expected string, received undefined\". Non-string fields\n // (a masked number or date) have no honest blank besides\n // emptyValue, exactly like numberInputProps, so they keep it;\n // the initial value's runtime type is the signal, since TValue\n // is erased. The cast is the emptyValue contract, not a guess.\n const empty = (\n field.clearable || typeof field.initialValue !== \"string\"\n ? field.emptyValue\n : \"\"\n ) as TValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form\n // value so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n // Snap the display to the canonical format of whatever the form\n // holds, then run the field's ordinary blur (touched + mode gate).\n setEdit({ raw: null, pushed: undefined });\n field.onBlur();\n },\n };\n};\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type FormStateApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n}>;\n\nexport function useFormSelector<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above. Without\n// it, Form<TSchema> would structurally satisfy FormStateApi too and a\n// bad selector could silently widen to FormState<unknown>.\nexport function useFormSelector<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelector<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, selector);\n}\n\nexport function useFormSelectorShallow<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, useShallow(selector));\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { isPathOrChild } from \"../core/validation\";\nimport { useFormSelectorShallow } from \"./useFormSelector\";\n\n// The multi-step (wizard) story: one form, one schema, one values object —\n// and a step index that gates progress on the CURRENT step's fields\n// validating clean. Everything else falls out of what the library already\n// does: next() runs validateFieldsAsync over the step's paths (just those\n// slots when every path extracts a subschema; a refine on an ancestor\n// object sends the batch through the full parse, so cross-field rules\n// inside a step still fire; either way the errors are scoped to the\n// step), a failed advance marks the errored fields touched\n// exactly the way a failed submit does (so touched-gated error UIs show),\n// and going BACK never validates — leaving a half-filled step is normal.\n//\n// The step index is deliberately React state, not form state: it is UI\n// navigation, not form data, and FormState's shape is owned by the\n// library. Render a progress bar elsewhere by lifting the returned value,\n// exactly as you would any other component state.\n//\n// Cross-STEP rules (a schema-level refine over fields in different steps)\n// surface at submit, like every wizard: a step only re-judges its own\n// paths, and the root \"\" key belongs to the whole form.\n\nexport type FormStep<TValues, D extends PathDepth = DefaultPathDepth> = Readonly<{\n // For progress UIs; steps are addressed by index either way.\n name?: string;\n // The paths this step owns — a container path covers its whole subtree.\n fields: readonly FieldPath<TValues, D>[];\n}>;\n\nexport type StepStatus = Readonly<{\n name: string | undefined;\n // The user has been ON this step (the first step starts visited).\n visited: boolean;\n // Any error currently at or under the step's fields — live, so a\n // progress bar can flag a step the user broke after leaving it.\n hasErrors: boolean;\n}>;\n\nexport type UseFormStepsReturn = Readonly<{\n step: number;\n name: string | undefined;\n count: number;\n isFirst: boolean;\n isLast: boolean;\n // Validate the current step; on clean, advance (no-op advance on the\n // last step — submit is the last step's \"next\"). Resolves whether the\n // step validated clean, so `if (await steps.next())` reads naturally on\n // any step, the last included.\n next: () => Promise<boolean>;\n // Never validates: leaving a half-filled step backward is normal.\n back: () => void;\n // Backward jumps are free. A forward jump validates each step from the\n // current one up to (not including) the target and LANDS ON THE FIRST\n // ONE THAT FAILS, errors visible — so a step header can be a plain\n // goTo() without letting anyone skip past an invalid step. Resolves the\n // index actually landed on.\n goTo: (target: number) => Promise<number>;\n // Per-step live status, index-aligned with the definitions.\n steps: readonly StepStatus[];\n}>;\n\nexport const useFormSteps = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n steps: readonly FormStep<z.input<TSchema>, D>[],\n): UseFormStepsReturn => {\n const [step, setStep] = useState(0);\n const [visited, setVisited] = useState<ReadonlySet<number>>(\n () => new Set([0]),\n );\n\n // Latest-ref so next/goTo/back are reference-stable however the caller\n // writes the steps array (the usePersistForm pattern; navigation only\n // fires after mount, so the ref is always populated). The COUNT should\n // stay stable for sensible UX, but nothing here breaks if it doesn't —\n // there are no per-step hooks.\n const latest = useRef(steps);\n useEffect(() => {\n latest.current = steps;\n });\n\n // Validate one step's paths and mirror submit's convention on failure:\n // the errored keys (already scoped to the step by validateFieldsAsync)\n // are marked touched, so touched-gated error UIs show why the advance\n // refused.\n const validateStep = useCallback(\n async (index: number): Promise<boolean> => {\n const definition = latest.current[index];\n if (definition === undefined) return true;\n const result = await form.validateFieldsAsync(definition.fields);\n if (result.kind === \"invalid\") {\n Object.keys(result.errors).forEach((key) => {\n form.setTouched(key as FieldPath<z.input<TSchema>, D>, true);\n });\n return false;\n }\n return true;\n },\n [form],\n );\n\n // The step the user is on RIGHT NOW, readable after an await. next() and\n // goTo() validate asynchronously from the render-time `step` (the one the\n // user acted on), but the user may press back() while that validation is\n // in flight; applying the advance then would land two steps past where\n // they now are. Each transition re-checks that the step is still the one\n // it validated before writing, and otherwise leaves the user's newer\n // navigation alone.\n const currentStep = useRef(step);\n useEffect(() => {\n currentStep.current = step;\n });\n\n const next = useCallback(async (): Promise<boolean> => {\n // Functional reads through state setters would race the async\n // validation; the render-time `step` is the one the user acted on.\n const ok = await validateStep(step);\n if (!ok) return false;\n if (currentStep.current !== step) return false;\n const target = Math.min(step + 1, latest.current.length - 1);\n setStep(target);\n setVisited((prev) => new Set([...prev, target]));\n return true;\n }, [validateStep, step]);\n\n const back = useCallback((): void => {\n setStep((prev) => Math.max(prev - 1, 0));\n }, []);\n\n const goTo = useCallback(\n async (target: number): Promise<number> => {\n const count = latest.current.length;\n const clamped = Math.max(0, Math.min(target, count - 1));\n if (clamped <= step) {\n setStep(clamped);\n return clamped;\n }\n // Walk forward, validating each step on the way; land on the first\n // failure so its errors are on screen.\n const walk = async (from: number): Promise<number> => {\n if (from >= clamped) return clamped;\n return (await validateStep(from)) ? walk(from + 1) : from;\n };\n const landed = await walk(step);\n // The user navigated during the walk (back(), or another goTo that\n // resolved first): their newer position wins, and the caller learns\n // where the form actually is.\n if (currentStep.current !== step) return currentStep.current;\n setStep(landed);\n setVisited(\n (prev) =>\n new Set([\n ...prev,\n ...Array.from({ length: landed - step + 1 }, (_, i) => step + i),\n ]),\n );\n return landed;\n },\n [validateStep, step],\n );\n\n // Live per-step error presence, shallow-compared so renders happen only\n // when some step's flag flips — not on every error-map write.\n const errorFlags = useFormSelectorShallow(form, (state) =>\n steps.map((definition) =>\n definition.fields.some((path) =>\n Object.keys(state.errors).some((key) => isPathOrChild(key, path)),\n ),\n ),\n );\n\n const statuses = useMemo(\n () =>\n steps.map(\n (definition, index): StepStatus => ({\n name: definition.name,\n visited: visited.has(index),\n hasErrors: errorFlags[index] ?? false,\n }),\n ),\n [steps, visited, errorFlags],\n );\n\n return useMemo(\n () => ({\n step,\n name: steps[step]?.name,\n count: steps.length,\n isFirst: step === 0,\n isLast: step === steps.length - 1,\n next,\n back,\n goTo,\n steps: statuses,\n }),\n [step, steps, next, back, goTo, statuses],\n );\n};\n","import { useActionState, useCallback, useEffect, useRef } from \"react\";\nimport { isDevBuild } from \"../core/env\";\nimport type { z } from \"zod\";\nimport type {\n Form,\n InvalidSubmitHandler,\n SubmitResult,\n} from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// The React 19 form-actions bridge: bind a formstand form's validation and\n// submit lifecycle to `<form action={...}>` and useActionState, so the\n// action world gets what onSubmit callers already have — schema\n// validation before the action runs, isSubmitting/submitCount tracking,\n// errors written and their fields marked touched on a failed submit, and\n// the two-channel error model for the action's own verdicts.\n//\n// The handler receives PARSED, TYPED data (z.output of the schema), not\n// FormData: formstand inputs are controlled, so the store is the source of\n// truth and the schema has already judged it. The raw FormData still\n// arrives as the last argument for what only it can carry — uncontrolled\n// inputs in the same <form>, file pickers — and because a server action\n// can take it across the wire (FormData serializes under RSC).\n//\n// Honest scope: this is a CLIENT-side integration. React's no-JS\n// progressive enhancement only works when the server action itself is\n// passed to the form/useActionState, which by definition skips any\n// client-side wrapper — for that path, validate on the server with the\n// same zod schema and keep this bridge for the hydrated experience.\n//\n// Note on React's post-action reset: React 19 resets UNCONTROLLED form\n// fields after an action completes. formstand inputs are controlled, so\n// the form's values survive the action untouched.\n\nexport type FormActionHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n formData: FormData,\n) => void | Promise<void>;\n\n// S is the AWAITED state (what the reducer stores), so the handler's\n// return may be the state or a promise of it — the shape a \"use server\"\n// async function naturally has.\nexport type FormActionStateHandler<TSchema extends z.ZodType, S> = (\n prevState: S,\n data: z.output<TSchema>,\n formData: FormData,\n) => S | Promise<S>;\n\nexport type FormActionOptions = Readonly<{\n // Mirrors handleSubmit's second parameter: runs when validation fails\n // (errors are written and fields marked touched either way).\n onInvalid?: InvalidSubmitHandler;\n // Mirrors SubmitOptions.onError: the save-failure hook for a throwing\n // handler. Without it, dev builds warn when a failure resolves\n // unobserved — the action form is fire-and-forget, like handleSubmit.\n onError?: (error: unknown) => void;\n}>;\n\n// The fire-and-forget dev warning, same contract as handleSubmit's: a\n// throwing handler resolves {kind: \"error\"} writing no state, so with no\n// onError the failure would vanish completely.\nconst warnUnobserved = (\n result: SubmitResult<unknown>,\n options: FormActionOptions | undefined,\n site: string,\n): void => {\n if (\n result.kind === \"error\" &&\n options?.onError === undefined &&\n isDevBuild()\n ) {\n console.warn(\n `[formstand] action handler threw and nothing observed it — the form shows no feedback. Pass { onError } to ${site} (or setError inside your handler):`,\n result.error,\n );\n }\n};\n\n// The plain bridge: an action for `<form action={...}>`. Validation and\n// the submit lifecycle run first; the handler only sees data the schema\n// accepted. The returned function is REFERENCE-STABLE across renders\n// (handler and options are read through refs assigned in an effect —\n// actions only fire after mount, so the refs are always populated), which\n// keeps memoized subtrees quiet however the caller writes the handler.\nexport const useFormAction = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n): ((formData: FormData) => Promise<void>) => {\n const latest = useRef({ onValid, options });\n useEffect(() => {\n latest.current = { onValid, options };\n });\n return useCallback(\n async (formData: FormData) => {\n const { onValid: handler, options: opts } = latest.current;\n const result = await form.submit(\n (data) => handler(data, formData),\n opts?.onInvalid,\n opts?.onError === undefined ? undefined : { onError: opts.onError },\n );\n warnUnobserved(result, opts, \"useFormAction\");\n },\n [form],\n );\n};\n\n// The stateful bridge: useActionState with schema-validated data. The\n// handler's shape mirrors the native (prevState, formData) signature with\n// the parsed data spliced in, so a \"use server\" function slots straight\n// in. A submission that fails validation (or is skipped, or throws)\n// returns the PREVIOUS state unchanged: field errors already live in the\n// form store where the bound components read them, so the action state\n// stays what it is — the last verdict an action actually produced.\nexport const useFormActionState = <\n TSchema extends z.ZodType,\n S,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n): [state: S, formAction: (formData: FormData) => void, isPending: boolean] => {\n const [state, formAction, isPending] = useActionState<S, FormData>(\n async (prevState, formData): Promise<S> => {\n // React hands the reducer Awaited<S>; S is declared as the awaited\n // state, so for any non-thenable state (the only kind a reducer can\n // meaningfully hold) the two are the same type — TS just won't\n // simplify the deferred conditional for an unconstrained S.\n const prev = prevState as S;\n // Sanctioned mutable ref for the handler's return value: submit owns\n // the lifecycle and its onValid returns void, so the next state\n // rides out through the closure (same shape as the codebase's other\n // capture refs).\n const nextRef: { current: S } = { current: prev };\n const result = await form.submit(\n async (data) => {\n nextRef.current = await action(prev, data, formData);\n },\n options?.onInvalid,\n options?.onError === undefined\n ? undefined\n : { onError: options.onError },\n );\n warnUnobserved(result, options, \"useFormActionState\");\n return nextRef.current;\n },\n initialState as Awaited<S>,\n );\n return [state as S, formAction, isPending];\n};\n","import {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\nexport type FormProviderProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n Provider: (props: FormProviderProps<TSchema, D>) => ReactNode;\n useFormContext: () => Form<TSchema, D>;\n}>;\n\n// A form created with a non-default `pathDepth` names it here too:\n// createFormContext<typeof schema, 12>() — the context can't infer it (there\n// is no value argument), and Form<S, 12> is deliberately not Form<S, 9>.\n// The `PathDepth` constraint makes an out-of-range literal (26, -1) or a\n// widened `number` argument a compile error, same as createForm's option.\nexport const createFormContext = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(): FormContextApi<TSchema, D> => {\n const Context = createContext<Form<TSchema, D> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema, D>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema, D> => {\n const ctx = useContext(Context);\n if (ctx === null) {\n throw new Error(\n \"useFormContext must be used inside the matching <Provider>\",\n );\n }\n return ctx;\n };\n\n return { Provider, useFormContext };\n};\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport { type Debouncer, createDebouncer } from \"../core/debounce\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { entryAt, flagAt } from \"../core/maps\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n emptyValueForSchema,\n isClearableSchema,\n fieldSchemaForIntrospection,\n} from \"../core/validation\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose write methods take the narrower\n// FieldPath<...> instead of string — still satisfies this API. Prefer calling\n// these through a typed Form when you have one.\nexport type FieldFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n setValue(path: string, value: unknown): void;\n setTouched(path: string, touched?: boolean): void;\n setError(path: string, errors: string | readonly string[]): void;\n clearErrors(path?: string): void;\n validateField(path: string): FieldValidationResult;\n // Settled by contract: an awaited pass can never resolve \"pending\" —\n // the promise IS the pending state, and a resolved {kind: \"pending\"}\n // would carry a promise that never runs. Custom implementations were\n // always expected to resolve settled; the type now says so.\n validateFieldAsync(path: string): Promise<SettledFieldValidationResult>;\n}>;\n\nexport type FieldPathArg<TValues> =\n | string\n | ((state: FormState<TValues>) => string);\n\nexport type UseFieldOptions = Readonly<{\n debounceMs?: number;\n}>;\n\nexport type UseFieldReturn<TValue> = Readonly<{\n // The resolved field path — useful as an input's `name` attribute (the\n // bound prop builders spread it as `name`).\n path: string;\n value: TValue;\n // The slice of initialValues at this path (what `dirty` compares against).\n initialValue: TValue;\n // What a cleared input writes back: null when the field's schema is\n // nullable (introspected when the form carries its schema — the zod-first\n // source of truth), undefined when it is optional or unknown. Falls back\n // to \"the initial value was null\" for schema-less FieldFormApi forms.\n emptyValue: null | undefined;\n // Whether the schema ACCEPTS that emptyValue (optional / nullable /\n // defaulted — see isClearableSchema). The string-shaped bindings write\n // emptyValue on a cleared input only when this is true; a required\n // string cleared to \"\" stays \"\" so the schema judges a visible value\n // instead of a hole it rejects. Schema-less forms fall back to the same\n // heuristic as emptyValue: a null initial value reads as clearable.\n clearable: boolean;\n error: readonly string[] | undefined;\n // The first error message, or undefined when the channel is empty — the\n // display shorthand every adapter otherwise re-derives by hand (the\n // `error?.[0]`-with-empty-array-guard helper each generated kit adapter\n // used to open with).\n firstError: string | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setValue: (value: TValue) => void;\n setTouched: (touched?: boolean) => void;\n // A single string is shorthand for a one-element array (like form.setError).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n validate: () => FieldValidationResult;\n // Settled: awaited passes never resolve \"pending\" (see FieldFormApi).\n validateAsync: () => Promise<SettledFieldValidationResult>;\n onBlur: () => void;\n}>;\n\ntype FieldSlice<TValue> = Readonly<{\n path: string;\n value: TValue;\n initialValue: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// The readable-error trap-guard for `useField<Values>(typedForm, \"email\")`:\n// any explicit type argument arity-matches ONLY the one-type-parameter\n// overloads, and the structural one's `schema?: undefined` brand then\n// rejects the Form with a baffling \"... not assignable to type 'undefined'\".\n// The error overload below intercepts that shape: its TValue defaults to\n// this unexported sentinel — an INFERRED call can never produce it (TValue\n// has no inference site, so it always falls back to the default), which\n// collapses `path` to `never` and fails the overload silently — while an\n// EXPLICIT TValue (never assignable to the unexported brand) on a\n// schema-carrying form types `path` as a string-literal error message, so\n// the compiler blames the path argument with instructions instead of brand\n// internals.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order is deliberate. When no overload matches, TypeScript reports\n// the LAST candidate's error — so the typed-path overload sits last, and a\n// typo'd path on a Form<TSchema> is blamed on the path argument against the\n// full FieldPath union ('\"naem\"' is not assignable to '\"name\" | \"age\" | ...')\n// instead of on the form argument.\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useField<Schema, \"name\">`) —\n// TS applies explicit type args to every arity-compatible overload, so a\n// second parameter here would check \"name\" against it.\nexport function useField<TSchema extends z.ZodType>(\n form: FieldFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): an explicit type argument on a\n// schema-carrying form binds here and blames the path argument with a\n// readable instruction. Inferred calls can never select it — TValue stays\n// at its sentinel default and `path` collapses to `never`.\nexport function useField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n path: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the value type from the path\",\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// The `schema?: undefined` brand forces TS past this widened overload when a\n// real Form is passed (Form has `schema: TSchema`, not undefined). Without\n// it, a Form<TSchema> with an invalid path would silently bind here and\n// return UseFieldReturn<unknown>.\nexport function useField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker), so a `pathDepth: 12` form checks paths against its widened union.\n// It sits LAST (P's constraint forward-references it — legal in TS) with a\n// default, so pre-existing explicit instantiations like\n// `useField<typeof schema, \"name\">` keep their arity.\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue> {\n const slice = useStore(\n form.store,\n useShallow((state): FieldSlice<TValue> => {\n const p =\n typeof pathArg === \"function\" ? pathArg(state) : pathArg;\n const value = getAtPath(state.values, p);\n const initialValue = getAtPath(state.initialValues, p);\n return {\n path: p,\n value: value as TValue,\n initialValue: initialValue as TValue,\n // Own-key reads: a field named \"constructor\" or \"toString\" would\n // otherwise read Object.prototype's function as its error/flag.\n error: entryAt(state.errors, p),\n touched: flagAt(state.touched, p),\n dirty: isFieldDirty(value, initialValue),\n isValidating: flagAt(state.isValidating, p),\n };\n }),\n );\n const path = slice.path;\n\n // Schema introspection wins over the runtime heuristic when the form\n // carries its schema (Form<TSchema> does; a bare FieldFormApi may not).\n const formSchema = (form as Readonly<{ schema?: z.ZodType }>).schema;\n const initialValue = slice.initialValue;\n const { emptyValue, clearable } = useMemo(() => {\n if (formSchema !== undefined) {\n const sub = fieldSchemaForIntrospection(formSchema, path);\n if (sub !== null) {\n return {\n emptyValue: emptyValueForSchema(sub),\n clearable: isClearableSchema(sub),\n };\n }\n }\n // Schema-less heuristic: a null initial value is the one runtime signal\n // that null round-trips, so it drives both answers.\n return initialValue === null\n ? { emptyValue: null, clearable: true }\n : { emptyValue: undefined, clearable: false };\n }, [formSchema, path, initialValue]);\n\n const debounceMs = options?.debounceMs;\n // One debouncer per (form, path, debounceMs) identity, created lazily on\n // the first debounced trigger and cancelled by the effect cleanup on\n // unmount or identity change — the ref keeps it across renders.\n const debouncerRef = useRef<Debouncer | null>(null);\n\n useEffect(() => {\n return () => {\n debouncerRef.current?.cancel();\n debouncerRef.current = null;\n };\n }, [form, path, debounceMs]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n const debouncer = debouncerRef.current ?? createDebouncer(debounceMs);\n debouncerRef.current = debouncer;\n // The pending timer is invisible to the store, so a reset() /\n // adoptValues() inside the debounce window cannot cancel it the way\n // it invalidates in-flight validation (the ownership tokens): the\n // fire would claim a FRESH token and re-commit errors onto the\n // rebased form. Two fire-time guards close it. A REBASE is detected\n // as \"the values reference moved since scheduling AND now IS\n // initialValues\", which is exactly what reset and adoptValues leave\n // behind and nothing else produces (a keystroke moves the reference\n // away from initialValues, not onto it). The bare \"values is\n // initialValues\" test used before also matched a form nobody has\n // typed in yet, so a blur with debounceMs on an untouched required\n // field never validated. The second guard drops a stale fire: a path\n // whose value changed since scheduling (the write that changed it\n // scheduled its own validation, or was a restore to other values).\n // Scheduling runs after setValue, so the captured value is the\n // keystroke being validated.\n const scheduledValues = form.store.getState().values;\n const scheduled = getAtPath(scheduledValues, path);\n debouncer.schedule(() => {\n const state = form.store.getState();\n const rebased =\n state.values !== scheduledValues &&\n state.values === state.initialValues;\n if (rebased) return;\n if (!Object.is(getAtPath(state.values, path), scheduled)) return;\n void form.validateFieldAsync(path);\n });\n return;\n }\n // The core routes async schemas itself: validateField returns\n // { kind: \"pending\" } having already started the async pass, which\n // commits its errors and isValidating flags to the store — so the\n // result needs no handling here.\n form.validateField(path);\n }, [form, path, debounceMs]);\n\n const setValue = useCallback(\n (value: TValue) => {\n const before = form.store.getState();\n form.setValue(path, value);\n const state = form.store.getState();\n // A no-op write (the identical value — createForm's setValue identity\n // guard leaves the state reference untouched) skips the revalidation\n // gate too: nothing changed, so the current error state already\n // reflects this value. Custom FieldFormApi implementations without\n // the guard produce a fresh state and keep the old behavior.\n if (state === before) return;\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n flagAt(state.touched, path),\n )\n ) {\n triggerValidate();\n }\n },\n [form, path, triggerValidate],\n );\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched(path, touched),\n [form, path],\n );\n\n const setError = useCallback(\n // Normalize the string shorthand HERE, before forwarding: custom\n // FieldFormApi implementations written against the pre-0.4 surface are\n // typed for readonly string[] and must never receive a bare string.\n (errors: string | readonly string[]) =>\n form.setError(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(\n () => form.clearErrors(path),\n [form, path],\n );\n\n const validate = useCallback(() => form.validateField(path), [form, path]);\n\n const validateAsync = useCallback(\n () => form.validateFieldAsync(path),\n [form, path],\n );\n\n const onBlur = useCallback(() => {\n form.setTouched(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n triggerValidate();\n }\n }, [form, path, triggerValidate]);\n\n return useMemo(\n () => ({\n path: slice.path,\n value: slice.value,\n initialValue: slice.initialValue,\n emptyValue,\n clearable,\n error: slice.error,\n // `?.[0]` covers both the undefined channel and an empty array.\n firstError: slice.error?.[0],\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setValue,\n setTouched,\n setError,\n clearError,\n validate,\n validateAsync,\n onBlur,\n }),\n [slice, emptyValue, clearable, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Discriminated-union support. A z.discriminatedUnion field types its value\n// as a union of variant objects, and FieldPath<T> only exposes the keys\n// COMMON to every union member (via `keyof T`) — so the DISCRIMINANT binds\n// with plain useField (it's common), but a variant-specific field\n// (\"payment.cardNumber\", present only in the card branch) resolves to a\n// path FieldPath omits. useVariantField is the typed accessor for those.\n//\n// It binds `${unionPath}.${field}` and types the result as the field's value\n// across every variant that declares it, widened with `| undefined` because\n// the field is absent while a different variant is active:\n//\n// const method = useField(form, \"payment.method\"); // discriminant\n// const cardNumber = useVariantField(form, \"payment\", \"cardNumber\");\n// // -> UseFieldReturn<string | undefined>, rendered when method.value === \"card\"\n//\n// The hook is called unconditionally (React's rules) — every variant's\n// fields bind every render; you render the matching ones based on the\n// discriminant. Runtime behavior is exactly useField on the joined path.\n//\n// Gate WRITES on the discriminant too, not just rendering: the returned\n// setter writes `${unionPath}.${field}` regardless of the active variant, so\n// calling a card field's setValue while the paypal variant is active injects\n// a stray key into the stored object. z.discriminatedUnion strips it on\n// parse (validation looks clean), but dirtyFields()/persistForm see the\n// polluted shape. Render the matching fields only — as the example shows —\n// and their setters fire only for the active variant. formstand-gen's output\n// follows this; hand-written forms must too.\n\n// The value of variant path `TField` across the members of union `V` that\n// resolve it. Distributes over V: each member contributes its FieldValue\n// when TField is one of ITS typed paths, never otherwise; the union of\n// those is the result. `| undefined` is added by the caller (the field is\n// absent while another variant is active). Since 0.20 TField is a PATH,\n// not just a key — \"size.w\" reaches inside a variant-only object — so the\n// resolution rides the same FieldPath/FieldValue machinery as useField\n// (leaf classification, tuple positions, and the depth budget included;\n// the budget applies to the path WITHIN the variant, the union path\n// having already been budget-checked by its own binding).\nexport type VariantFieldValue<V, TField extends string> = V extends unknown\n ? // No FieldPath gate needed: FieldValue resolves a path a member does\n // not declare to `never` (StepValue's miss arm), so non-declaring\n // members drop out of the union by themselves — and the constraint\n // side (VariantFieldPath) already vouches that SOME member declares\n // it.\n FieldValue<V, TField>\n : never;\n\n// The variant-only field keys of union `V`: every member's keys minus the\n// keys shared by all members (the discriminant and any other common field,\n// which bind with plain useField). `keyof V` on a union is ALREADY the\n// common keys (the intersection) — it must NOT distribute, or it would\n// equal AllKeys and leave no variant keys. AllKeys distributes to collect\n// every member's keys.\ntype CommonKeys<V> = keyof V;\ntype AllKeys<V> = V extends unknown ? keyof V : never;\nexport type VariantKeys<V> = Exclude<AllKeys<V>, CommonKeys<V>> & string;\n\n// Every typed path of every member — FieldPath distributes over the union\n// — minus the paths ROOTED at a common key: the discriminant and other\n// common fields (and anything under them) bind with plain useField, so\n// offering them here would just duplicate the plain hook with a widened\n// `| undefined`. What remains is exactly what FieldPath on the union\n// cannot offer: variant-only keys and every path INSIDE them\n// (\"cardNumber\", \"size\", \"size.w\", \"lines.0.qty\").\nexport type VariantFieldPath<\n V,\n D extends PathDepth = DefaultPathDepth,\n> = Exclude<\n V extends unknown ? FieldPath<V, D> : never,\n (CommonKeys<V> & string) | `${CommonKeys<V> & string}.${string}`\n> &\n string;\n\n// The paths in `TValues` whose value is a discriminated union — an object\n// whose members don't all share the same keys. Kept permissive (any\n// top-level or nested key reaching a union of objects); misuse on a\n// non-union path yields `never` field keys, so the call simply won't\n// typecheck a field argument.\nexport type UnionValueAt<TValues, P extends string> = P extends keyof TValues\n ? // NonNullable is essential: for an OPTIONAL/nullable union field the\n // resolved value includes undefined, which collapses `keyof V` to never\n // — VariantKeys would then leak EVERY key (discriminant included) and\n // the whole guard inverts. Strip the nullish part first.\n NonNullable<TValues[P]>\n : TValues extends readonly (infer Item)[]\n ? // Array rows: a numeric segment — a literal \"0\" or the `${number}`\n // a template path like `pavements.${index}` produces — selects the\n // ELEMENT type, so a union that IS the row item resolves the same\n // way a static object path does. (`keyof` above cannot do this:\n // an array's numeric index signature is `number`, and the string\n // segment types never extend it.) Without this branch every\n // row-indexed union path collapsed the field keys to `never`,\n // making unions inside array rows unbindable — the exact wall the\n // generated array-row TODO used to steer people into.\n P extends `${number}`\n ? NonNullable<Item>\n : P extends `${infer Head}.${infer Tail}`\n ? // Tuple positionality first: a tuple's keyof carries its literal\n // indices, so \"wrap.0.pay\" resolves element 0's OWN shape\n // instead of the all-elements union `Item` (whose keyof\n // collapses to common keys and killed the variant-key set). A\n // plain array's keyof has no numeric-string members, so it\n // falls through to the element branch unchanged.\n Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : Head extends `${number}`\n ? UnionValueAt<NonNullable<Item>, Tail>\n : never\n : never\n : P extends `${infer Head}.${infer Tail}`\n ? Head extends keyof TValues\n ? UnionValueAt<NonNullable<TValues[Head]>, Tail>\n : never\n : never;\n\n// The readable-error trap-guard, mirroring useField's/useFieldArray's: an\n// explicit type argument (`useVariantField<string>(typedForm, \"payment\",\n// \"cardNumber\")`) arity-matches ONLY the one-type-parameter overloads, and\n// the structural one's `schema?: undefined` brand then rejects the Form\n// with a baffling \"... not assignable to type 'undefined'\". The error\n// overload below intercepts that shape — TValue defaults to this unexported\n// sentinel, which inferred calls can never escape (TValue has no inference\n// site), collapsing `unionPath` to `never`; an explicit TValue on a\n// schema-carrying form instead types `unionPath` as a string-literal\n// instruction the compiler blames the argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the trap\n// guard sits before the widened structural overload, and the typed overload\n// sits LAST so a bad union path / field name on a Form<TSchema> is blamed\n// on that argument against the real union instead of on the form argument.\nexport function useVariantField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the variant value from the union path and field\",\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// Schema-less forms keep the plain-string, caller-typed shape. The\n// `schema?: undefined` brand forces a real Form past this widened overload\n// (Form has `schema: TSchema`, not undefined).\nexport function useVariantField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n): UseFieldReturn<TValue | undefined>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker). It sits LAST with a default, so pre-existing explicit\n// instantiation expressions like\n// `typeof useVariantField<typeof schema, \"payment\", \"cardNumber\">` keep\n// their arity.\nexport function useVariantField<\n TSchema extends z.ZodType,\n P extends string,\n // The DEFAULT depth budget on purpose, not D: a constraint may not\n // consume a later type parameter before inference resolves it — TS\n // substitutes D's CONSTRAINT (the whole PathDepth union) while checking\n // TField, which collapses the offered paths to never. Variant subtrees\n // are shallow by construction (they sit under an already-budgeted union\n // path), so the fixed default costs nothing real.\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n): UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\nexport function useVariantField(\n form: FieldFormApi,\n unionPath: string,\n field: string,\n): UseFieldReturn<unknown> {\n // Structural string-path bind: the joined path is exactly what a variant\n // field lives at; only its TYPE was unreachable through FieldPath, so the\n // runtime is ordinary useField.\n return useField(\n form as FieldFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n );\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport {\n type ArrayOpRecord,\n arrayOpsFor,\n clearArrayOps,\n} from \"../core/arrayOpLog\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { entryAt, flagAt } from \"../core/maps\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport type { FieldValidationResult } from \"../core/validation\";\nimport type { FieldPathArg } from \"./useField\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose array ops take the narrower\n// FieldPath<...> instead of string — still satisfies this API.\n// NOTE for custom implementations: exact row-id tracking for ops on\n// Object.is-equal rows is a createForm feature (its ops record their index\n// mappings internally) — a hand-rolled implementation of these methods gets\n// value-based id reconciliation only.\nexport type FieldArrayFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n arrayPush(path: string, item: unknown): void;\n arrayRemove(path: string, index: number): void;\n arrayInsert(path: string, index: number, item: unknown): void;\n arrayMove(path: string, from: number, to: number): void;\n arraySwap(path: string, a: number, b: number): void;\n // OPTIONAL, probed before use: when present (createForm always provides\n // it), the hook's op wrappers revalidate the array path after an op under\n // the same change-trigger gate useField.setValue applies — so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. NOTE for custom implementations: a hand-rolled FieldArrayFormApi\n // without this member still works — the ops simply skip revalidation.\n validateField?(path: string): FieldValidationResult;\n // OPTIONAL like validateField, same custom-implementation contract: when\n // present (createForm always provides them), the hook exposes the\n // array-level server-error channel — a \"too many rows\" verdict from the\n // API is set and cleared from the hook that owns the array, the same\n // symmetry useField has had all along. Absent members make the returned\n // setError/clearError no-ops.\n setError?(path: string, errors: string | readonly string[]): void;\n clearErrors?(path?: string): void;\n // OPTIONAL, same contract: `setTouched` backs the hook's touched/onBlur\n // half of its useField parity, `setValue` backs the whole-array writes\n // (replace/update/clear). Absent members make those returned functions\n // no-ops, like setError/clearError above.\n setTouched?(path: string, touched?: boolean): void;\n setValue?(path: string, value: unknown): void;\n}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n // The resolved array path — the same convenience useField exposes.\n path: string;\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\n // The first array-level message, or undefined — same shorthand as\n // useField.firstError (the docs used to hand-roll error[0] here).\n firstError: string | undefined;\n // The array-level server channel, scoped to this path (see the\n // FieldArrayFormApi note: no-ops on custom implementations without the\n // optional members).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n // The array's own flags, read at ITS path like useField reads a leaf's:\n // `touched` is the array path's flag (set by onBlur/setTouched, not by\n // a row's blur), `dirty` compares the whole array against its initial\n // value, `isValidating` is the array path's in-flight flag. A \"touched\n // array\" UI used to drop to selectors for these.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setTouched: (touched?: boolean) => void;\n // Marks the array touched and validates it under the blur gate, the\n // same gate useField.onBlur applies; for a list whose \"control\" is the\n // add row or the group as a whole.\n onBlur: () => void;\n // Array-scoped validation, the same result shape as useField.validate.\n // On a hand-rolled FieldArrayFormApi without validateField it reports\n // valid without running anything (the member is optional, see above).\n validate: () => FieldValidationResult;\n push: (item: TItem) => void;\n remove: (index: number) => void;\n insert: (index: number, item: TItem) => void;\n move: (from: number, to: number) => void;\n swap: (a: number, b: number) => void;\n // The whole-array writes. `replace` and `clear` go through the form's\n // setValue, so ids come from reconciliation: a row REFERENCE that\n // survives keeps its id, a fresh row at the same index keeps that\n // index's id. `update` writes one row in place (the row keeps its id,\n // an edit at the same index), `prepend` is insert(0, item). All four\n // revalidate under the change gate like the index ops.\n replace: (items: readonly TItem[]) => void;\n update: (index: number, item: TItem) => void;\n prepend: (item: TItem) => void;\n clear: () => void;\n}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n // Unique per (form, path) entry, so ids minted for different arrays (or\n // for the same hook after a dynamic path switch) can never collide as\n // React keys.\n prefix: string;\n}>;\n\n// Stable reference for \"path holds no array yet\" — a fresh [] per selector\n// run would defeat useShallow and re-render on every store change.\nconst EMPTY_ITEMS: readonly never[] = [];\n\n// 1-based mint numbers for the positions needing a fresh id, in order.\n// BOTH id-derivation paths (value reconciliation in reconcileIds and the\n// exact op mappings in mappedIdState) number their mints through this one\n// helper, so the collision-free scheme — counter + consecutive 1-based\n// counts, counter advanced by the map's size — cannot diverge between them.\nconst mintNumbers = (\n needsMint: readonly boolean[],\n): ReadonlyMap<number, number> =>\n new Map(\n needsMint\n .flatMap((mint, i) => (mint ? [i] : []))\n .map((position, k) => [position, k + 1] as const),\n );\n\n// Derive a stable id per item by reconciling the live items against the\n// last-seen items. Ids follow items by identity/value, so resets and\n// mutations that bypass the array ops (setValue of a whole array, restore)\n// keep keys glued to their rows — not just length-preserving appends/\n// truncations. A same-index fallback keeps an edited row's id (editing\n// produces a fresh item reference at the same position) without remounting\n// it. This is the FALLBACK path: array ops (hook-issued OR imperative)\n// replay their exact recorded mappings via the core's op log first (see\n// deriveIds), because value matching cannot tell Object.is-equal rows\n// apart.\nconst reconcileIds = (prev: IdState, nextItems: readonly unknown[]): IdState => {\n if (prev.items === nextItems) return prev;\n if (\n prev.items.length === nextItems.length &&\n prev.items.every((item, i) => Object.is(item, nextItems[i]))\n ) {\n // Same rows, fresh array reference (a normalization pass, a server\n // refresh of unchanged data): the ids are unchanged but the anchor\n // MUST move to the live reference — a later op's record chains from\n // it, and a stale anchor would silently break replay back to value\n // matching (the duplicate-row bug all over again).\n return { ...prev, items: nextItems };\n }\n\n // Zeroth pass: a row that is Object.is-equal AT ITS OWN INDEX keeps its\n // own id before any value matching runs. Without this, duplicate\n // primitives steal each other's ids on an edit: with [\"\", \"\"] and a\n // keystroke into row 0 ([\"x\", \"\"]), the value pass below would hand row\n // 0's id to row 1 (the first \"\" bucket slot), row 0 would then mint, and\n // React would remount the input the user is typing in. Reserving\n // same-index identity first keeps row 1 on its own id and leaves row 0's\n // slot for the same-index leftover pass, which is what an edit needs.\n const keptAtIndex: readonly boolean[] = nextItems.map(\n (item, i) => i < prev.items.length && Object.is(item, prev.items[i]),\n );\n\n // Bucket the REMAINING prev positions by item so duplicate primitives\n // match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\n if (keptAtIndex[i] === true) return acc;\n const bucket = acc.get(item);\n if (bucket === undefined) {\n acc.set(item, [i]);\n } else {\n bucket.push(i);\n }\n return acc;\n }, new Map());\n\n // First pass: reuse the id of the matching prev item, consuming that slot so\n // each id is reused at most once (`shift` empties the bucket as we go).\n const matchedIds: readonly (string | null)[] = nextItems.map((item, i) => {\n if (keptAtIndex[i] === true) return prev.ids[i] ?? null;\n const prevIndex = buckets.get(item)?.shift();\n return prevIndex === undefined ? null : (prev.ids[prevIndex] ?? null);\n });\n\n // Second pass: an unmatched item reuses its SAME-INDEX leftover id (an\n // in-place edit keeps its row); any other leftover id belongs to a row\n // that is genuinely gone. Handing those out positionally would let a\n // remove-then-push in one batch key the new row with the deleted row's\n // id — a React reorder that resurrects the dead row's DOM state — so\n // they die and new items mint fresh ids instead. (Trade-off: an edit\n // that also MOVES in the same write remounts; value-identity matching\n // above already covers pure moves.)\n const leftoverAt = new Map(\n [...buckets.values()].flat().flatMap((i) => {\n const id = prev.ids[i];\n return id === undefined ? [] : ([[i, id]] as const);\n }),\n );\n const reused = matchedIds.map((id, i) => id ?? leftoverAt.get(i) ?? null);\n\n const mints = mintNumbers(reused.map((id) => id === null));\n const ids = reused.map(\n (id, i) => id ?? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`,\n );\n\n return {\n items: nextItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// Apply an exact index mapping to the id list: nextIds[i] =\n// prev.ids[mapping[i]], with -1 minting a fresh id (a new row). Returns null\n// — falling back to value reconciliation — unless every carried position's\n// live item is identity-equal to the recorded previous item, so a mapping\n// can never mis-key rows the store changed some other way (a refused\n// out-of-bounds op, an interleaved setValue).\nconst mappedIdState = (\n prev: IdState,\n mapping: readonly number[],\n liveItems: readonly unknown[],\n): IdState | null => {\n if (liveItems.length !== mapping.length) return null;\n const aligned = mapping.every((src, i) =>\n src === -1\n ? true\n : prev.ids[src] !== undefined &&\n Object.is(liveItems[i], prev.items[src]),\n );\n if (!aligned) return null;\n // (In practice an op mapping mints at most one row — push/insert — but\n // the numbering stays general via the shared scheme.)\n const mints = mintNumbers(mapping.map((src) => src === -1));\n const ids = mapping.map((src, i) =>\n src === -1\n ? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`\n : (prev.ids[src] as string),\n );\n return {\n items: liveItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// One id state per (form store, path), shared by EVERY hook instance on\n// that array so sibling hooks always agree on row ids. A sanctioned\n// mutable-ref cache (like the core's subschemaCache): the entry is derived\n// bookkeeping — each commit is a pure function of a REAL store state, so a\n// discarded render leaves a sound (if not identical) state behind: rows may\n// remint where reuse was possible (a cosmetic remount), but a surviving row\n// can never receive another row's id. Entries are access-ordered and capped\n// so a long-lived store with churning dynamic paths (rows.N.tags) can't\n// accumulate snapshots forever; the WeakMap releases the rest with the\n// store.\ntype SharedIdEntry = { state: IdState };\ntype StoreIdEntries = { byPath: Map<string, SharedIdEntry>; seq: number };\n\n// Generous like path.ts's PARSE_CACHE_MAX: eviction of a MOUNTED array's\n// entry remints every row id (a full remount), so the cap is a backstop\n// against unbounded dynamic-path churn, never a working-set limit.\nconst MAX_ID_PATHS = 4096;\nconst sharedIdEntries = new WeakMap<object, StoreIdEntries>();\n\nconst storeIdEntries = (store: object): StoreIdEntries => {\n const existing = sharedIdEntries.get(store);\n const forStore = existing ?? { byPath: new Map(), seq: 1 };\n if (existing === undefined) sharedIdEntries.set(store, forStore);\n return forStore;\n};\n\nconst sharedIdEntry = (\n forStore: StoreIdEntries,\n path: string,\n): SharedIdEntry => {\n const existing = forStore.byPath.get(path);\n if (existing !== undefined) {\n // Re-insert to refresh recency, so eviction takes the longest-unused\n // path, not merely the oldest-created.\n forStore.byPath.delete(path);\n forStore.byPath.set(path, existing);\n return existing;\n }\n // Prefix from a PER-STORE sequence (deterministic per form, unlike a\n // module-global counter whose value depends on app-wide first-touch\n // order), so ids from different arrays — or a hook whose dynamic path\n // switches — can never collide as React keys.\n const created: SharedIdEntry = {\n state: {\n items: EMPTY_ITEMS,\n ids: [],\n counter: 0,\n prefix: `__zfa_${forStore.seq}_`,\n },\n };\n forStore.seq += 1;\n forStore.byPath.set(path, created);\n if (forStore.byPath.size > MAX_ID_PATHS) {\n const oldest = forStore.byPath.keys().next().value;\n if (oldest !== undefined) forStore.byPath.delete(oldest);\n }\n return created;\n};\n\n// Walk EVERY record in order, applying its exact mapping. A gap before a\n// record (a chain-breaking write between ops — though the core now clears\n// records at such writes, so gaps are rare) bridges by value to the\n// record's `from` first, so an op keeps its exactness no matter which side\n// of a whole-array write it fell on. The final hop to the live items — when\n// the last record didn't land there — reconciles by value too.\nconst walkOps = (\n start: IdState,\n items: readonly unknown[],\n ops: readonly ArrayOpRecord[],\n): IdState => {\n const walked = ops.reduce<IdState>((acc, op) => {\n const base = acc.items === op.from ? acc : reconcileIds(acc, op.from);\n return mappedIdState(base, op.mapping, op.to) ?? base;\n }, start);\n return walked.items === items ? walked : reconcileIds(walked, items);\n};\n\n// A row's DESCENDANT arrays have id entries of their own, keyed by path\n// (\"teams.0.members\"), so when the outer array reorders, the entry at\n// \"teams.2.members\" would otherwise meet team A's members with team C's\n// history: value reconciliation finds nothing it knows, the same-index\n// fallback hands the first rows the OTHER team's ids, the rest remint, and\n// React remounts inputs a user may be typing in. Move the entries with their\n// rows instead. The outer walk already decided which row went where (the\n// id that was at index j is now at index i, or is gone), so the re-seat\n// follows the ids, not the op: it is the same for an exact op mapping and\n// for a whole-array write that reconciled by value. A vacated slot's\n// entries are dropped so a later row at that index starts clean rather\n// than inheriting a dead row's ids. Entries at an index the previous state\n// never had (a hook mounted on a not-yet-existing slot) are left where\n// they are. Only an outer hook runs this (it derives before its rows' inner\n// hooks, parent before child); inner-only trees keep today's value\n// fallback.\nconst reseatDescendants = (\n forStore: StoreIdEntries,\n path: string,\n prev: IdState,\n next: IdState,\n): void => {\n if (prev.ids.length === 0) return;\n const newIndexById = new Map(next.ids.map((id, i) => [id, i] as const));\n // old index -> new index; undefined marks a removed row. Decided before\n // the entry map is scanned: a keystroke in any row re-derives the outer\n // ids (new array reference, same rows) and must not pay for the scan.\n const moves = prev.ids.map((id) => newIndexById.get(id));\n if (moves.every((to, from) => to === from)) return;\n const prefix = `${path}.`;\n const descendants = [...forStore.byPath.keys()].filter((key) =>\n key.startsWith(prefix),\n );\n const relocations = descendants.flatMap((key) => {\n const rest = key.slice(prefix.length);\n const dot = rest.indexOf(\".\");\n const segment = dot === -1 ? rest : rest.slice(0, dot);\n const from = Number(segment);\n if (!/^\\d+$/.test(segment) || from >= prev.ids.length) return [];\n const entry = forStore.byPath.get(key);\n if (entry === undefined) return [];\n const to = moves[from];\n const target =\n to === undefined\n ? undefined\n : `${prefix}${to}${dot === -1 ? \"\" : rest.slice(dot)}`;\n return [{ key, target, entry }];\n });\n // Clear every moving source first, then seat the survivors: a swap's two\n // entries trade keys, so interleaving the two passes would overwrite one\n // of them before it was read.\n relocations.forEach(({ key }) => forStore.byPath.delete(key));\n relocations.forEach(({ target, entry }) => {\n if (target !== undefined) forStore.byPath.set(target, entry);\n });\n};\n\nconst deriveIds = (\n store: object,\n path: string,\n items: readonly unknown[],\n): IdState => {\n const forStore = storeIdEntries(store);\n const entry = sharedIdEntry(forStore, path);\n if (entry.state.items === items) return entry.state;\n const ops = arrayOpsFor(store, path);\n // The walk consumes every record, so the log is spent bookkeeping\n // afterwards — clear it, which also keeps ring composition from ever\n // merging a record a consumer is still anchored at. (The one residual:\n // a render discarded between clear and commit re-derives the final hop\n // by value — sound ids, possibly reminted where reuse was possible.)\n if (ops.length > 0) clearArrayOps(store, path);\n const next = walkOps(entry.state, items, ops);\n reseatDescendants(forStore, path, entry.state, next);\n entry.state = next;\n return next;\n};\n\n// The readable-error trap-guard, mirroring useField's: an explicit type\n// argument (`useFieldArray<Item>(typedForm, \"users\")`) arity-matches ONLY\n// the one-type-parameter overloads, and the structural one's brand then\n// rejects the Form with a baffling \"... not assignable to type\n// 'undefined'\". The error overload below intercepts that shape — TItem\n// defaults to this unexported sentinel, which inferred calls can never\n// escape (TItem has no inference site), collapsing `path` to `never`; an\n// explicit TItem on a schema-carrying form instead types `path` as a\n// string-literal instruction the compiler blames the path argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the\n// typed-path overload sits last so a typo'd path on a Form<TSchema> is\n// blamed on the path argument against the full FieldPath union, and the\n// `schema?: undefined` brand forces a real Form past the widened structural\n// overload — without it, `useFieldArray(form, \"users\")` would bind there\n// and return UseFieldArrayReturn<unknown> instead of inferring the item\n// type from the path. Schema-less FieldFormApi forms keep the explicit\n// TItem parameter (there is nothing to infer from).\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useFieldArray<Schema,\n// \"tags\">`) — TS applies explicit type args to every arity-compatible\n// overload, so a second parameter here would check \"tags\" against it.\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: FieldArrayFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): explicit type argument on a\n// schema-carrying form → readable error on the path argument; inferred\n// calls fall through (path collapses to never).\nexport function useFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n path: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the path\",\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem>;\n// D last with a default (P's constraint forward-references it), preserving\n// the arity of explicit instantiations like\n// `useFieldArray<typeof schema, \"tags\">`. P is an ARRAY path (the core's\n// ArrayFieldPath: variable-length arrays only, optional/nullable included):\n// a scalar path used to bind here with a never-typed item (every write an\n// error, the hook itself not), and a tuple path bound with the tuple's\n// element union while the core refused the same push. The item type comes\n// from the core's ArrayItemOf, so the hook and form.arrayPush agree.\n// The `& string` is load-bearing: P's constraint depends on D, which is\n// inferred from the SAME call, so while P is being inferred the constraint\n// is a deferred conditional type and TS cannot see that it is made of\n// string literals. Without a visible primitive constraint the \"users\"\n// candidate widens to `string`, fails the constraint, and P falls back to\n// the whole array-path union (every item type at once). Intersecting with\n// string keeps the literal, exactly as FieldPath's own shape happened to.\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends ArrayFieldPath<z.input<TSchema>, D> & string,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem> {\n const path = useStore(form.store, (state) =>\n typeof pathArg === \"function\" ? pathArg(state) : pathArg,\n );\n const slice = useStore(\n form.store,\n useShallow((state) => {\n const value = getAtPath(state.values, path);\n return {\n items: (Array.isArray(value) ? value : EMPTY_ITEMS) as readonly TItem[],\n // Own-key read, like useField: an array named \"constructor\" must\n // not read Object as its error list.\n error: entryAt(state.errors, path),\n touched: flagAt(state.touched, path),\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: flagAt(state.isValidating, path),\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Ids derive from the shared per-(store, path) entry: the core's op log\n // replays each array op's exact index mapping (hook-issued or imperative\n // — both go through applyArrayOp, which records them), and value\n // reconciliation covers everything else (setValue of a whole array,\n // restore, resets). Deriving during render is safe because the entry is\n // a convergent cache — every commit is a pure function of a real store\n // state — and cheap because it early-exits on the same items reference.\n // All hook instances on the same path read the same entry, so their ids\n // can never disagree.\n const ids = deriveIds(form.store, path, items).ids;\n\n // After every op, revalidate the ARRAY path under the exact change-trigger\n // gate useField.setValue applies (same shouldValidateOn call), so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. The result is deliberately unhandled — the core self-routes async\n // schemas (validateField returns { kind: \"pending\" } having already started\n // the async pass). validateField is probed: a hand-rolled FieldArrayFormApi\n // without it skips revalidation instead of crashing. The IMPERATIVE\n // form.arrayPush/arrayRemove stay non-revalidating on purpose — the same\n // layering as form.setValue (raw write) vs useField.setValue (write + gate).\n const revalidate = useCallback(() => {\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n flagAt(state.touched, path),\n )\n ) {\n form.validateField?.(path);\n }\n }, [form, path]);\n\n const push = useCallback(\n (item: TItem) => {\n form.arrayPush(path, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const remove = useCallback(\n (index: number) => {\n form.arrayRemove(path, index);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => {\n form.arrayInsert(path, index, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const move = useCallback(\n (from: number, to: number) => {\n form.arrayMove(path, from, to);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const swap = useCallback(\n (a: number, b: number) => {\n form.arraySwap(path, a, b);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const fields = useMemo<readonly FieldArrayEntry<TItem>[]>(\n () =>\n items.map((value, index) => ({\n id: ids[index] ?? `__zfa_fallback_${index}`,\n value,\n })),\n [items, ids],\n );\n\n const setError = useCallback(\n // Same string-shorthand normalization as useField.setError, so custom\n // implementations typed for readonly string[] never receive a bare\n // string.\n (errors: string | readonly string[]) =>\n form.setError?.(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(() => form.clearErrors?.(path), [form, path]);\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched?.(path, touched),\n [form, path],\n );\n\n // useField.onBlur without the debounce: array-level rules are cheap\n // (length, uniqueness) and the hook takes no debounceMs option.\n const onBlur = useCallback(() => {\n form.setTouched?.(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n form.validateField?.(path);\n }\n }, [form, path]);\n\n const validate = useCallback(\n (): FieldValidationResult =>\n form.validateField?.(path) ?? { kind: \"valid\" },\n [form, path],\n );\n\n const replace = useCallback(\n (next: readonly TItem[]) => {\n form.setValue?.(path, next);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const update = useCallback(\n (index: number, item: TItem) => {\n form.setValue?.(`${path}.${index}`, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const prepend = useCallback(\n (item: TItem) => {\n form.arrayInsert(path, 0, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const clear = useCallback(() => {\n form.setValue?.(path, []);\n revalidate();\n }, [form, path, revalidate]);\n\n return useMemo(\n () => ({\n path,\n fields,\n items,\n length: items.length,\n error,\n firstError: error?.[0],\n setError,\n clearError,\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setTouched,\n onBlur,\n validate,\n push,\n remove,\n insert,\n move,\n swap,\n replace,\n update,\n prepend,\n clear,\n }),\n [\n path,\n fields,\n items,\n error,\n setError,\n clearError,\n slice.touched,\n slice.dirty,\n slice.isValidating,\n setTouched,\n onBlur,\n validate,\n push,\n remove,\n insert,\n move,\n swap,\n replace,\n update,\n prepend,\n clear,\n ],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport type { UnionValueAt, VariantFieldValue } from \"./useVariantField\";\n\n// The array twin of useVariantField. A z.array that lives in ONE variant of\n// a discriminated union (\"asphalt\" pavements have `lights`, \"grass\" ones do\n// not) sits at a path FieldPath omits, since FieldPath on a union offers\n// only the keys every member shares, so useFieldArray(form, \"top.lights\")\n// is a compile error even though the runtime binding is ordinary. This hook\n// binds `${unionPath}.${field}` and types the rows from the variants that\n// declare the array:\n//\n// const kind = useField(form, \"top.kind\"); // discriminant\n// const lights = useVariantFieldArray(form, \"top\", \"lights\");\n// // -> UseFieldArrayReturn<{ color: string }>, rendered when kind.value === \"asphalt\"\n//\n// Like useVariantField, call it unconditionally and render the matching\n// rows based on the discriminant; its ops write the variant path whatever\n// the active variant is, so gate the UI, not the hook. Runtime behavior is\n// exactly useFieldArray on the joined path, row ids included.\n//\n// The field argument is a variant sub-PATH, not just a key, the same way\n// useVariantField's is: \"lights\", \"spec.lights\" (an array inside a\n// variant-only object), or a row template such as `lights.${index}.bulbs`\n// for an array nested in the rows of another variant array. formstand-gen\n// emits this hook for arrays inside union variants, the one shape that\n// used to degrade to a TODO.\n\n// The variable-length array paths of union `V` that are NOT rooted at a\n// common key. Built from the core's ArrayFieldPath, distributed over the\n// members like VariantFieldPath distributes FieldPath, so optional and\n// nullable arrays and template paths with numeric holes all qualify. A\n// common-key array binds with plain useFieldArray, which types it from the\n// union directly; offering it here would duplicate that hook.\nexport type VariantArrayFieldPath<\n V,\n D extends PathDepth = DefaultPathDepth,\n> = Exclude<\n V extends unknown ? ArrayFieldPath<V, D> : never,\n (keyof V & string) | `${keyof V & string}.${string}`\n> &\n string;\n\n// The trap-guard sentinel, mirroring useVariantField's: an explicit type\n// argument on a schema-typed form lands on the one-type-parameter overload\n// below and reads the instruction instead of a baffling structural error.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useVariantField: the trap guard first, the widened\n// structural overload for schema-less forms next, the typed overload LAST\n// so a bad union path or field on a Form<TSchema> is blamed on that\n// argument against the real union.\nexport function useVariantFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the union path and field\",\n field: string,\n): UseFieldArrayReturn<TItem>;\nexport function useVariantFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n): UseFieldArrayReturn<TItem>;\n// D is recovered from the form argument and sits last with a default, so\n// explicit instantiation expressions keep their arity. TField's constraint\n// uses the DEFAULT depth on purpose, the same reasoning as useVariantField:\n// a constraint may not consume a later type parameter before inference\n// resolves it, and variant subtrees are shallow by construction.\nexport function useVariantFieldArray<\n TSchema extends z.ZodType,\n P extends string,\n TField extends VariantArrayFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n): UseFieldArrayReturn<\n ArrayItemOf<VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField>>\n>;\nexport function useVariantFieldArray(\n form: FieldArrayFormApi,\n unionPath: string,\n field: string,\n): UseFieldArrayReturn<unknown> {\n // Structural string-path bind: the joined path is exactly where the\n // variant's array lives; only its TYPE was unreachable through\n // ArrayFieldPath, so the runtime is ordinary useFieldArray.\n return useFieldArray(\n form as FieldArrayFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n );\n}\n","import { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\nexport const useFormError = (\n form: FormStateApi,\n): readonly string[] | undefined =>\n useStore(\n form.store,\n useShallow((state) => state.errors[\"\"]),\n );\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Whole-values subscription in render — sugar for\n// useFormSelector(form, (s) => s.values), the render-side sibling of\n// form.watchValues. The classic use is derived rendering driven by live\n// form values (a map re-rendering as coordinates are edited).\n//\n// Deliberately NOT shallow-compared: the store replaces the values object\n// immutably on every value change, so reference equality (useStore's\n// default Object.is) is exactly right — one comparison, re-render if and\n// only if some value changed. Unrelated state changes (touched, errors,\n// isSubmitting) leave the values reference alone and cause no re-render.\n\nexport function useFormValues<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>): z.input<TSchema>;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above — same rule as\n// useFormSelector. Structural forms have nothing to infer from and read\n// `unknown`.\nexport function useFormValues(\n form: FormStateApi & { readonly schema?: undefined },\n): unknown;\nexport function useFormValues(form: FormStateApi): unknown {\n return useStore(form.store, (state) => state.values);\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// Composite fields: ONE control backed by SEVERAL schema paths — a\n// coordinate pair behind a single map-driven input, a range's min/max, a\n// date span. Binding each path with its own useField works, but the\n// coordination (a combined error line, one blur, one touched/dirty answer)\n// is the same hand-written boilerplate every time. useFields binds the\n// paths together:\n//\n// const location = useFields(form, [\"latitude\", \"longitude\"]);\n// const [latitude, longitude] = location.fields; // full UseFieldReturns\n// <span>{location.firstError}</span> // combined error line\n//\n// Each element of `fields` is a REAL UseFieldReturn — it spreads into the\n// same prop builders and Bound components a solo binding would — and the\n// wrapper adds the combined view: errors merged in path order (deduped, so\n// a cross-field superRefine that stamps both paths reads once), touched /\n// dirty / isValidating as \"any of them\", and one onBlur that blurs every\n// path (each under the form's own validation mode gate).\n//\n// THE PATHS TUPLE IS PART OF THE HOOK CONTRACT: its length and order must\n// be stable across renders, because it expands to exactly that many hook\n// calls. React enforces this itself — a tuple that changes length throws\n// the \"Rendered fewer/more hooks than expected\" dev error at the very\n// render that broke the contract (pinned by the test suite), so pass a\n// literal or a module-level constant, never a filtered array.\n\nexport type UseFieldsReturn<TFields extends readonly unknown[]> = Readonly<{\n fields: TFields;\n // Every bound path's messages, merged in path order and deduped.\n error: readonly string[] | undefined;\n firstError: string | undefined;\n // \"Any of them\": one answer for the composite control's chrome.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n // Blurs every bound path — each under the form's validation mode gate,\n // so the composite behaves like one control losing focus.\n onBlur: () => void;\n}>;\n\n// Schema-less forms keep the caller-typed shape (the `schema?: undefined`\n// brand forces a real Form past this overload, mirroring useField).\nexport function useFields(\n form: FieldFormApi & { readonly schema?: undefined },\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]>;\n// The typed overload: `paths` is a const-inferred tuple and `fields` maps\n// it position-for-position, so destructuring keeps each path's exact value\n// type. D is recovered from the form (the \"~pathDepth\" marker), like the\n// sibling hooks.\nexport function useFields<\n TSchema extends z.ZodType,\n const P extends readonly FieldPath<z.input<TSchema>, D>[],\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n paths: P,\n): UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\nexport function useFields(\n form: FieldFormApi,\n paths: readonly string[],\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> {\n const fields = paths.map((path) =>\n // eslint-disable-next-line react-hooks/rules-of-hooks -- a fixed hook count by the stable-arity contract above; each element must be a REAL UseFieldReturn so it spreads into the prop builders\n useField(form as FieldFormApi & { readonly schema?: undefined }, path),\n );\n const merged = [...new Set(fields.flatMap((field) => field.error ?? []))];\n return {\n fields,\n error: merged.length > 0 ? merged : undefined,\n firstError: merged[0],\n touched: fields.some((field) => field.touched),\n dirty: fields.some((field) => field.dirty),\n isValidating: fields.some((field) => field.isValidating),\n onBlur: () => {\n fields.forEach((field) => {\n field.onBlur();\n });\n },\n };\n}\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type { DefaultPathDepth, FieldPath, PathDepth } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport { isPathOrChild } from \"../core/validation\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Both flag hooks take an optional path and scope to it with the same\n// prefix semantics as the rest of the library (isPathOrChild): \"shipping\"\n// covers \"shipping.city\". Omitted path = whole form. Overload order mirrors\n// useField: the typed-path overload sits last so a typo'd path on a\n// Form<TSchema> is blamed against the full FieldPath union, and the\n// `schema?: undefined` brand keeps real Forms off the widened string\n// overload. Subscriptions are boolean-only — the component re-renders when\n// the flag flips, not on every keystroke (unlike useField(...).dirty).\n\n// Derived from the values (memoized per values reference), so it always\n// agrees with per-field dirty reads. The scoped form compares just the\n// subtree at `path` — a missing path on both sides reads as clean.\nexport function useIsDirty(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsDirty<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsDirty(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) =>\n path === undefined || path === \"\"\n ? isFieldDirty(state.values, state.initialValues)\n : isFieldDirty(\n getAtPath(state.values, path),\n getAtPath(state.initialValues, path),\n ),\n );\n}\n\n// \"No errors currently in the merged map\" (not a fresh validation pass);\n// the scoped form only looks at errors at or under `path`, including the\n// path's own key (array-level errors like `items` count for path \"items\").\nexport function useIsValid(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValid<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n // A loop rather than Object.entries().some(): this selector re-runs on\n // EVERY store change, and the loop exits at the first error without\n // materializing an entries array for a map that is usually empty.\n for (const k in state.errors) {\n const errs = state.errors[k];\n if (\n errs !== undefined &&\n errs.length > 0 &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return false;\n }\n }\n return true;\n });\n}\n\n// Whether async validation is in flight — form-level (a whole-form pass,\n// or any field's own pass) or scoped to a path subtree, boolean-only like\n// the sibling flags. The form-level read was previously reachable only\n// through a selector, asymmetric with useIsSubmitting.\nexport function useIsValidating(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValidating<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValidating(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n if (path === undefined || path === \"\") {\n if (state.isValidatingForm) return true;\n }\n // Same first-hit loop rationale as useIsValid: this selector re-runs\n // on every store change over a usually-empty map.\n for (const k in state.isValidating) {\n if (\n state.isValidating[k] === true &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return true;\n }\n }\n return false;\n });\n}\n\nexport const useIsSubmitting = (form: FormStateApi): boolean =>\n useStore(form.store, (state) => state.isSubmitting);\n\nexport const useSubmitCount = (form: FormStateApi): number =>\n useStore(form.store, (state) => state.submitCount);\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\nimport {\n type UnionValueAt,\n type VariantFieldValue,\n type VariantFieldPath,\n useVariantField,\n} from \"./useVariantField\";\nimport {\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport {\n type VariantArrayFieldPath,\n useVariantFieldArray,\n} from \"./useVariantFieldArray\";\nimport { useFormError } from \"./useFormError\";\nimport { useFormValues } from \"./useFormValues\";\nimport {\n type FormStep,\n type UseFormStepsReturn,\n useFormSteps,\n} from \"./useFormSteps\";\nimport { type UseFieldsReturn, useFields } from \"./useFields\";\nimport {\n useIsDirty,\n useIsSubmitting,\n useIsValid,\n useIsValidating,\n useSubmitCount,\n} from \"./useFormFlags\";\nimport {\n type FormStateApi,\n useFormSelector,\n useFormSelectorShallow,\n} from \"./useFormSelector\";\n\n// createFormHooks(form, name?) — every hook, pre-wired to one form. The\n// context-free way to share a form: create it at module scope, export the\n// returned hooks, and no component ever passes `form` through props or a\n// provider. The optional name is baked into the hook names (both at the\n// type level and at runtime), so a module reads like a domain API:\n//\n// const form = createForm(invoiceSchema, { initialValues });\n// export const { useInvoiceField, useInvoiceFieldArray, useInvoiceIsDirty } =\n// createFormHooks(form, \"invoice\");\n//\n// Typed paths survive the binding: useInvoiceField(\"customer\") infers the\n// value type from the schema, and a typo'd path is a compile error.\n//\n// Reach for this when the form is a genuine module-level singleton (one\n// instance for the app's lifetime — settings, a global compose box). For a\n// form that mounts per page/dialog with its own lifecycle, use useForm and\n// createFormContext instead: a module singleton never unmounts, so state\n// persists across navigations until you reset() it.\n\n// The bound signatures mirror the unbound hooks minus the form parameter;\n// the typed-path call signature sits last for the same error-blame reason\n// as the originals.\nexport type BoundUseField<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n options?: UseFieldOptions,\n ): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\n};\n\n// The variant-field accessor bound to the form: the type math (variant\n// paths, value across resolving variants) lives in useVariantField; the\n// bound signature just drops the form parameter.\nexport type BoundUseVariantField<TSchema extends z.ZodType> = <\n P extends string,\n // Default depth, matching the unbound hook (see its comment on why the\n // constraint cannot ride the form's D).\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n) => UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\n\n// The variant-array accessor bound to the form, the array twin of\n// BoundUseVariantField: the type math lives in useVariantFieldArray.\nexport type BoundUseVariantFieldArray<TSchema extends z.ZodType> = <\n P extends string,\n TField extends VariantArrayFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n) => UseFieldArrayReturn<\n ArrayItemOf<VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField>>\n>;\n\nexport type BoundUseFieldArray<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n ): UseFieldArrayReturn<unknown>;\n // Array paths only, like the unbound hook's typed overload.\n <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n ): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\n};\n\nexport type BoundUseSelector<TSchema extends z.ZodType> = <U>(\n selector: (state: FormState<z.input<TSchema>>) => U,\n) => U;\n\nexport type BoundUseFlag<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = (\n path?: FieldPath<z.input<TSchema>, D>,\n) => boolean;\n\n// One single-key mapped type per hook, intersected: template-literal keys\n// carry the capitalized name, so the destructured names are typo-checked\n// ({ useInvoceField } fails to compile against createFormHooks(f, \"invoice\")).\nexport type FormHooks<\n TSchema extends z.ZodType,\n N extends string,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<\n { [K in `use${Capitalize<N>}Field`]: BoundUseField<TSchema, D> } & {\n [K in `use${Capitalize<N>}VariantField`]: BoundUseVariantField<TSchema>;\n } & {\n [K in `use${Capitalize<N>}FieldArray`]: BoundUseFieldArray<TSchema, D>;\n } & {\n [K in `use${Capitalize<N>}VariantFieldArray`]: BoundUseVariantFieldArray<TSchema>;\n } & { [K in `use${Capitalize<N>}Selector`]: BoundUseSelector<TSchema> } & {\n [K in `use${Capitalize<N>}SelectorShallow`]: BoundUseSelector<TSchema>;\n } & {\n [K in `use${Capitalize<N>}Error`]: () => readonly string[] | undefined;\n } & { [K in `use${Capitalize<N>}IsDirty`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsValid`]: BoundUseFlag<TSchema, D>;\n } & { [K in `use${Capitalize<N>}IsValidating`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsSubmitting`]: () => boolean;\n } & {\n [K in `use${Capitalize<N>}SubmitCount`]: () => number;\n } & { [K in `use${Capitalize<N>}Values`]: () => z.input<TSchema> } & {\n [K in `use${Capitalize<N>}Fields`]: BoundUseFields<TSchema, D>;\n } & {\n [K in `use${Capitalize<N>}Steps`]: (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ) => UseFormStepsReturn;\n }\n>;\n\n// The bound composite-fields hook: same const-inferred tuple and\n// position-typed fields as the plain useFields.\nexport type BoundUseFields<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = <const P extends readonly FieldPath<z.input<TSchema>, D>[]>(\n paths: P,\n) => UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\n\n// Runtime twin of TypeScript's Capitalize<N> (ASCII names; a leading\n// non-letter passes through unchanged in both).\nconst capitalize = (name: string): string =>\n name.length === 0 ? name : name.charAt(0).toUpperCase() + name.slice(1);\n\n// D (the form's typed-path depth budget) sits LAST so existing explicit\n// instantiations — createFormHooks<Schema, \"invoice\"> — keep compiling; it\n// is inferred from the form argument anyway.\nexport const createFormHooks = <\n TSchema extends z.ZodType,\n N extends string = \"\",\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n name?: N,\n): FormHooks<TSchema, N, D> => {\n // Calling the unbound hooks through a structural view (no `schema`\n // property) binds their widened overloads — the precise typing is\n // re-established by the Bound* signatures above, which the type tests pin.\n const structural: FieldFormApi & FieldArrayFormApi & FormStateApi = form;\n\n const useBoundField = (\n path: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown> => useField(structural, path, options);\n\n const useBoundVariantField = (\n unionPath: string,\n field: string,\n ): UseFieldReturn<unknown> =>\n useVariantField(\n structural as FieldFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n );\n\n const useBoundFieldArray = (\n path: string | ((state: FormState<unknown>) => string),\n ): UseFieldArrayReturn<unknown> => useFieldArray(structural, path);\n\n const useBoundVariantFieldArray = (\n unionPath: string,\n field: string,\n ): UseFieldArrayReturn<unknown> =>\n useVariantFieldArray(\n structural as FieldArrayFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n );\n\n const useBoundSelector = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelector(structural, selector);\n\n const useBoundSelectorShallow = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelectorShallow(structural, selector);\n\n const useBoundError = (): readonly string[] | undefined =>\n useFormError(structural);\n\n const useBoundIsDirty = (path?: string): boolean =>\n useIsDirty(structural, path);\n\n const useBoundIsValid = (path?: string): boolean =>\n useIsValid(structural, path);\n\n const useBoundIsValidating = (path?: string): boolean =>\n useIsValidating(structural, path);\n\n const useBoundIsSubmitting = (): boolean => useIsSubmitting(structural);\n\n const useBoundValues = (): unknown => useFormValues(structural);\n\n const useBoundFields = (\n paths: readonly string[],\n ): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> =>\n useFields(\n structural as FieldFormApi & { readonly schema?: undefined },\n paths,\n );\n\n const useBoundSubmitCount = (): number => useSubmitCount(structural);\n\n const useBoundSteps = (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ): UseFormStepsReturn => useFormSteps(form, steps);\n\n const prefix = capitalize(name ?? \"\");\n // Computed keys erase to an index signature, so the literal is asserted\n // to the mapped FormHooks type — the real contract, verified by type\n // tests on both the key names and the bound signatures.\n return {\n [`use${prefix}Field`]: useBoundField,\n [`use${prefix}VariantField`]: useBoundVariantField,\n [`use${prefix}FieldArray`]: useBoundFieldArray,\n [`use${prefix}VariantFieldArray`]: useBoundVariantFieldArray,\n [`use${prefix}Selector`]: useBoundSelector,\n [`use${prefix}SelectorShallow`]: useBoundSelectorShallow,\n [`use${prefix}Error`]: useBoundError,\n [`use${prefix}IsDirty`]: useBoundIsDirty,\n [`use${prefix}IsValid`]: useBoundIsValid,\n [`use${prefix}IsValidating`]: useBoundIsValidating,\n [`use${prefix}IsSubmitting`]: useBoundIsSubmitting,\n [`use${prefix}SubmitCount`]: useBoundSubmitCount,\n [`use${prefix}Values`]: useBoundValues,\n [`use${prefix}Fields`]: useBoundFields,\n [`use${prefix}Steps`]: useBoundSteps,\n } as FormHooks<TSchema, N, D>;\n};\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n checkboxProps,\n dateInputProps,\n hasFieldError,\n numberToInputText,\n parseNumberText,\n selectProps,\n textInputProps,\n} from \"./inputProps\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// The paths a bound component accepts for a given `form` prop: when the form\n// carries its schema (a real Form<TSchema>), `path` narrows to the schema's\n// FieldPath union — a typo'd path is a compile error, matching useField's\n// typed overloads. Template-literal paths with a numeric hole\n// (`users.${index}.email`) are part of that union, so dynamic array rows\n// still typecheck. A bare structural FieldFormApi keeps plain string paths.\n// The form's own depth budget (createForm's `pathDepth`, default 9) is\n// recovered alongside the schema, so a widened form widens its bound\n// components' paths too.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? FieldPath<z.input<TSchema>, D>\n : string;\n\n// The subset of a form's paths whose VALUE a control can hold: TextField\n// takes string-valued paths, NumberField number-valued ones, and so on.\n// Before this filter `<TextField path=\"age\" />` on a z.number() compiled\n// and stored the string \"42\", failing validation at submit, while the\n// lower-level `textInputProps(useField(form, \"age\"))` had always been a\n// compile error; the beginner API was less safe than the expert one.\n// Distributes over the FieldPath union and keeps the paths whose\n// FieldValue is assignable to V (V always includes null | undefined, so\n// optional and nullable fields qualify). A bare FieldFormApi keeps plain\n// string paths, as PathsOf does.\nexport type PathsAccepting<F extends FieldFormApi, V> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? PathsWhereValue<z.input<TSchema>, FieldPath<z.input<TSchema>, D>, V>\n : string;\n\ntype PathsWhereValue<Values, P extends string, V> = P extends unknown\n ? FieldValue<Values, P> extends V\n ? P\n : never\n : never;\n\n// The form-level spelling of the core's ArrayFieldPath: the paths a\n// `form` prop's array ops and useFieldArray accept (variable-length arrays,\n// optional/nullable included, tuples excluded). For a component that takes\n// a form and an array path, the way PathsOf serves one taking any path. A\n// bare FieldFormApi keeps plain string paths.\nexport type ArrayPathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? ArrayFieldPath<z.input<TSchema>, D>\n : string;\n\n// The string values a select at `path` may hold: the field's own literal\n// union for an enum (so an option outside z.enum([...]) is a compile\n// error at the option), plain string for a free z.string(), and any\n// string for a bare FieldFormApi.\nexport type SelectValueAt<\n F extends FieldFormApi,\n P extends string,\n> = F extends Form<infer TSchema extends z.ZodType, infer D extends PathDepth>\n ? P extends FieldPath<z.input<TSchema>, D>\n ? Extract<NonNullable<FieldValue<z.input<TSchema>, P>>, string>\n : string\n : string;\n\n// Structural stand-in for React.Ref<T>: accepts useRef objects and callback\n// refs (including React 19 cleanup-returning ones — any return type is\n// assignable to a void-returning signature). Declared structurally instead of\n// as React.Ref so it unifies even when the consumer resolves a different\n// @types/react copy than the library.\nexport type FieldRef<T> =\n | ((instance: T | null) => void)\n | Readonly<{ current: T | null }>\n | null;\n\n// The chrome every bound field renders: wrapper, optional label, the\n// control, and the error line. `wrapLabel` puts the control INSIDE the\n// label (the checkbox layout: box, then text) instead of after a preceding\n// sibling label. One component so an a11y change lands everywhere at once.\ntype FieldShellProps = Readonly<{\n id: string;\n errorId: string;\n label: ReactNode | undefined;\n error: readonly string[] | undefined;\n wrapLabel?: boolean;\n children: ReactNode;\n}>;\n\n// Shared id wiring for every bound field: a stable control id, the error\n// line's id derived from it, and the aria-describedby value — set only\n// while an error shows, so assistive tech is never pointed at a node that\n// isn't rendered.\nconst useFieldA11y = (\n error: readonly string[] | undefined,\n): Readonly<{ id: string; errorId: string; describedBy: string | undefined }> => {\n const id = useId();\n const errorId = `${id}-error`;\n return {\n id,\n errorId,\n describedBy: hasFieldError(error) ? errorId : undefined,\n };\n};\n\n// role=\"alert\" announces the message to assistive tech when it appears; the\n// id lets the input point at it via aria-describedby.\nconst ErrorText = ({\n id,\n error,\n}: Readonly<{ id: string; error: readonly string[] | undefined }>) =>\n hasFieldError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nconst FieldShell = ({\n id,\n errorId,\n label,\n error,\n wrapLabel,\n children,\n}: FieldShellProps) => (\n <div className=\"zf-field\">\n {wrapLabel === true ? (\n <label htmlFor={id} className=\"zf-label\">\n {children} {label}\n </label>\n ) : (\n <>\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n {children}\n </>\n )}\n <ErrorText id={errorId} error={error} />\n </div>\n);\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsAccepting<F, string | null | undefined>;\n label?: ReactNode;\n placeholder?: string;\n type?: \"text\" | \"password\" | \"email\" | \"url\" | \"tel\";\n autoComplete?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\nexport const TextField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n type = \"text\",\n autoComplete,\n ref,\n}: TextFieldProps<F>) => {\n const field = useField<string | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type DateFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsAccepting<F, Date | null | undefined>;\n label?: ReactNode;\n min?: string;\n max?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\n// <input type=\"date\"> holds Date-typed state: display and parsing go\n// through the shared dateInputProps rules (local calendar-date semantics —\n// see inputProps.ts), so a nullable date clears back to null and an\n// invalid/partial entry writes the field's emptyValue. No raw-text state:\n// unlike number inputs, the date control has no partial entries to\n// preserve — the browser only fires change with \"\" or a complete date.\nexport const DateField = <F extends FieldFormApi>({\n form,\n path,\n label,\n min,\n max,\n ref,\n}: DateFieldProps<F>) => {\n const field = useField<Date | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...dateInputProps(field)}\n min={min}\n max={max}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsAccepting<F, number | null | undefined>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport type NumberInputBinding = Readonly<{\n name: string;\n value: string;\n inputMode: \"decimal\";\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype NumberEditState = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a partial\n // entry). When field.value diverges, an external writer (reset/adoptValues/\n // another field) changed it — drop the raw text so the input shows it.\n pushed: number | null | undefined;\n}>;\n\nconst IDLE_EDIT: NumberEditState = { raw: null, pushed: undefined };\n\n// Holds the raw text while editing so intermediate, not-yet-valid numbers\n// (\"-\", \"1.\", \"1e\") stay visible instead of being coerced to \"\". Keystrokes\n// that parse to a number (via the shared parseNumberText rules) are pushed to\n// the form; partial input is kept locally. On blur the display snaps back to\n// the form's canonical value, and an external value change while editing wins\n// over the local text (render-phase derived-state reset).\n// Exported for custom number inputs (and the CLI's kit adapters mirror its\n// semantics): spread the binding onto an <input type=\"text\"> — a naive\n// value={String(field.value)} controlled input eats the \".\" of \"85000.50\"\n// and the \"-\" of \"-5\" as they're typed.\nexport const useNumberInput = (\n field: UseFieldReturn<number | null | undefined>,\n): NumberInputBinding => {\n const [edit, setEdit] = useState<NumberEditState>(IDLE_EDIT);\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit(IDLE_EDIT);\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value: raw ?? numberToInputText(field.value),\n inputMode: \"decimal\",\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = parseNumberText(text);\n switch (parsed.kind) {\n case \"empty\": {\n const empty = field.emptyValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"number\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form value\n // so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n setEdit(IDLE_EDIT);\n field.onBlur();\n },\n };\n};\n\nexport const NumberField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n ref,\n}: NumberFieldProps<F>) => {\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsAccepting<F, boolean | null | undefined>;\n label?: ReactNode;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport const CheckboxField = <F extends FieldFormApi>({\n form,\n path,\n label,\n ref,\n}: CheckboxFieldProps<F>) => {\n const field = useField<boolean | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n wrapLabel\n >\n <input\n id={a11y.id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\n// P is the chosen path; the options' values are checked against the\n// field's own string union at that path (SelectValueAt), so an option the\n// schema's z.enum does not list is a compile error where it is written.\nexport type SelectFieldProps<\n F extends FieldFormApi = FieldFormApi,\n P extends PathsAccepting<F, string | null | undefined> = PathsAccepting<\n F,\n string | null | undefined\n >,\n> = Readonly<{\n form: F;\n path: P;\n label?: ReactNode;\n options: readonly SelectFieldOption<SelectValueAt<F, P>>[];\n // Shown as a disabled first option while the field has no value, so the\n // select stays controlled and the blank state is visible instead of\n // silently displaying the first option. Ignored when `options` itself\n // contains a \"\"-valued entry — that explicit, labelled option IS the\n // blank state and renders instead.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <\n F extends FieldFormApi,\n P extends PathsAccepting<F, string | null | undefined>,\n>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<F, P>) => {\n // null included: a nullable enum's \"not chosen yet\" must render the empty\n // option, or the browser shows the first real option while state stays null.\n const field = useField<SelectValueAt<F, P> | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n const select = selectProps(field);\n // A clearable field (nullable, optional, or defaulted) must be clearable\n // BACK to its emptyValue through the UI, so its empty option stays\n // visible after a choice and stays selectable — selectProps writes the\n // emptyValue for it. Everywhere else the empty option is only a\n // placeholder: visible while nothing is chosen, never selectable.\n // The value condition derives from selectProps' own coercion (undefined,\n // null, and \"\" all render as value \"\"), so any blank the select displays\n // has a matching option by construction. When the options list supplies\n // its OWN \"\"-valued entry, that explicit option IS the blank state —\n // rendering the implicit one too would duplicate the value, and the\n // browser would select the first (unlabelled) match instead.\n const clearable = field.clearable;\n const hasExplicitEmptyOption = options.some((opt) => opt.value === \"\");\n const showEmptyOption =\n !hasExplicitEmptyOption &&\n (clearable || select.value === \"\" || placeholder !== undefined);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <select\n id={a11y.id}\n ref={ref}\n {...select}\n aria-describedby={a11y.describedBy}\n >\n {showEmptyOption ? (\n <option value=\"\" disabled={!clearable}>\n {placeholder ?? \"\"}\n </option>\n ) : null}\n {options.map((opt, index) => (\n // Index-qualified: option lists may legitimately repeat a value\n // (e.g. differently-labelled aliases), and bare value keys would\n // collide.\n <option key={`${index}-${opt.value}`} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </FieldShell>\n );\n};\n","import type { ErrorMap } from \"../core/types\";\nimport { isPathOrChild } from \"../core/validation\";\n\n// The shared candidate walk for focusFirstError/focusField: form controls\n// with a `name`, in DOM order. Focusability is a SEPARATE, later filter —\n// matches()/closest() are ancestor walks, so they run on the few\n// name-matched candidates instead of every named control in the document\n// (a failed submit on a page with hundreds of controls shouldn't pay\n// hundreds of DOM traversals to focus one input).\nconst namedControls = (scope: ParentNode): readonly HTMLElement[] => [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n];\n\n// Hidden and disabled controls, and controls inside a closed <dialog>,\n// can't take focus — without the filter, a leading <input type=\"hidden\"\n// name=\"csrf\"> would swallow focusFirstError's root fallback, and a name\n// match inside a not-yet-opened dialog would shadow the visible one.\nconst isFocusCandidate = (el: HTMLElement): boolean =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null;\n\n// Does `el` actually hold focus? Ask the element's OWN root (document or\n// shadow root): document.activeElement retargets to the shadow HOST for a\n// focused control inside a shadow root, so it would read a successfully\n// focused shadow-DOM control as unfocused. A root that is neither (a\n// detached fragment) has no activeElement — fall back to the document,\n// where a detached element can never be the active one.\nconst holdsFocus = (el: HTMLElement): boolean => {\n const rootNode = el.getRootNode();\n const active =\n rootNode instanceof Document || rootNode instanceof ShadowRoot\n ? rootNode.activeElement\n : document.activeElement;\n return active === el;\n};\n\n// focus() can silently no-op (display:none ancestors and other unfocusable\n// states the cheap filters above can't see) — verify it took, and fall\n// through to the next candidate in DOM order. True only when a control\n// actually holds focus.\nconst focusFirstOf = (candidates: readonly HTMLElement[]): boolean =>\n candidates.some((el) => {\n el.focus();\n return holdsFocus(el);\n });\n\nconst nameMatchesAny = (\n el: HTMLElement,\n paths: readonly string[],\n): boolean => {\n const name = el.getAttribute(\"name\");\n return name !== null && paths.some((p) => isPathOrChild(name, p));\n};\n\n// CSS attribute-selector value for an arbitrary path: quoted, with the two\n// characters that are active inside a double-quoted CSS string escaped —\n// so paths with dots (\"address.region\") and hostile names select literally.\n// Control characters (a stray \"\\n\" in a computed path, DEL) are additionally\n// hex-escaped (`\\a `, with CSS's required trailing space): a raw newline\n// inside a quoted CSS string is a parse error, and querySelectorAll on an\n// invalid selector THROWS instead of matching nothing.\nconst cssQuoted = (value: string): string =>\n `\"${value\n .replace(/[\\\\\"]/g, (ch) => `\\\\${ch}`)\n .replace(\n /[\\x00-\\x1f\\x7f]/g,\n (ch) => `\\\\${ch.codePointAt(0)!.toString(16)} `,\n )}\"`;\n\n// The id fallback for composite widgets that render no `name` at all (e.g.\n// antd's Select — no form-posting input exists in it) but DO forward\n// `id={path}` to their real focusable control, the way the CLI's antd\n// adapter emits it. EXACT id match only, by design: descendant semantics\n// (\"address\" covering \"address.city\") belong to the name walk — an id names\n// one element, and inventing prefix matching over ids would guess. Runs\n// through the same focusability filter and post-focus verification as name\n// matches.\nconst idMatches = (\n scope: ParentNode,\n path: string,\n): readonly HTMLElement[] =>\n path === \"\"\n ? []\n : [...scope.querySelectorAll<HTMLElement>(`[id=${cssQuoted(path)}]`)];\n\n// Document order for a merged candidate list (name matches + id fallbacks\n// come from separate queries, but \"first error\" means first in the DOM).\nconst inDomOrder = (\n els: readonly HTMLElement[],\n): readonly HTMLElement[] =>\n [...els].sort((a, b) =>\n a === b\n ? 0\n : (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n ? -1\n : 1,\n );\n\n// The candidate walk shared by focusFirstError and focusField: name-matched\n// form controls for every path, plus — per path that matched NO named\n// control — the element whose `id` is exactly that path. Paths with a named\n// match never consult ids, so the name walk's semantics (descendants\n// included) stay authoritative wherever a `name` exists.\nconst pathCandidates = (\n scope: ParentNode,\n paths: readonly string[],\n): readonly HTMLElement[] => {\n const controls = namedControls(scope);\n const named = controls.filter((el) => nameMatchesAny(el, paths));\n // \"Has a named match\" is judged against focus-CANDIDATE controls only: a\n // hidden name-carrier (react-select's <input type=\"hidden\" name={path}>\n // value input, notably) can never take focus, so letting it claim the\n // path would suppress the id fallback and leave the real, id={path}\n // focusable control unreachable. The `named` list itself stays\n // pre-filter — callers apply isFocusCandidate to the merged result.\n const focusableControls = controls.filter(isFocusCandidate);\n const unnamedPaths = paths.filter(\n (p) => !focusableControls.some((el) => nameMatchesAny(el, [p])),\n );\n const byId = unnamedPaths.flatMap((p) => idMatches(scope, p));\n return inDomOrder([...new Set([...named, ...byId])]);\n};\n\n// Focus the first form control (in DOM order) whose `name` attribute matches\n// an entry in the error map — either exactly, or as a descendant of an\n// errored container path, so array-level errors (\"lineItems\" from\n// z.array().min()) and object-level refines (\"address\") land on their first\n// rendered field. Most specific wins: the root \"\" key (a form-wide refine)\n// falls back to the first control only when no field-keyed error matches\n// anything — otherwise a root error would steal focus from the actually\n// errored field. A path that matches NO named control at all additionally\n// tries the element whose `id` is exactly that path (see pathCandidates) —\n// how composite widgets with no `name` anywhere, like antd's Select with\n// id={path}, still get focused. The bound components and prop builders set\n// name={path}, so this works out of the box:\n//\n// form.handleSubmit(onValid, (errors) => focusFirstError(errors))\n//\n// Pass `root` to scope the search (e.g. the <form> element via a ref) — on a\n// page with several forms this is the way to keep focus inside YOUR form:\n// without it the search spans the whole document, and the root-\"\" fallback\n// refuses to guess between forms (it returns false when the document holds\n// more than one <form>). Returns whether a control actually received focus —\n// candidates that can't take it (disabled, hidden, inside a closed <dialog>,\n// display:none, ...) are passed over for the next match in DOM order. Safe to\n// import during SSR — it only touches the DOM when called.\nexport const focusFirstError = (\n errors: ErrorMap,\n root?: ParentNode,\n): boolean => {\n const scope = root ?? document;\n const erroredPaths = Object.keys(errors).filter(\n (k) => k !== \"\" && (errors[k]?.length ?? 0) > 0,\n );\n const hasRootError = (errors[\"\"]?.length ?? 0) > 0;\n const controls = namedControls(scope);\n const fieldMatches = pathCandidates(scope, erroredPaths).filter(\n isFocusCandidate,\n );\n // The root-\"\" fallback (\"focus the first control\") is only meaningful when\n // \"first control\" is unambiguous. With the default document scope on a\n // page holding several <form>s, the first control could belong to a form\n // that had nothing to do with this submit — refuse to guess and report\n // false; pass the form element as `root` to disambiguate.\n const rootFallbackApplies =\n hasRootError &&\n (root !== undefined || document.querySelectorAll(\"form\").length <= 1);\n const candidates =\n fieldMatches.length > 0\n ? fieldMatches\n : rootFallbackApplies\n ? controls.filter(isFocusCandidate)\n : [];\n return focusFirstOf(candidates);\n};\n\n// Imperative sibling of focusFirstError, keyed by a path instead of an error\n// map: focus the first control (in DOM order) whose `name` is `path` itself\n// or a descendant of it — focusField(\"address\") lands on the first rendered\n// address field. Same candidate walk (unfocusable controls are passed over,\n// focus is verified to have taken, a name-less path falls back to the\n// element whose `id` is exactly the path) and the same `root` scoping.\n// This is the \"setFocus\" of the library — reach for it after opening a\n// dialog or appending an array row:\n//\n// items.push(emptyItem);\n// requestAnimationFrame(() =>\n// focusField(`items.${items.length}.name`, formRef.current ?? undefined),\n// );\n//\n// The root \"\" path is whole-form scope, consistent with the imperative\n// surface (validateField(\"\") / resetField(\"\")): focus the first focusable\n// control in scope. Like focusFirstError's root-\"\" fallback, \"first control\"\n// under the default document scope is a guess when the page holds several\n// <form>s — focusField refuses to guess and returns false; pass the form\n// element as `root` to disambiguate.\n//\n// Returns whether a control actually received focus. Safe to import during\n// SSR — it only touches the DOM when called.\nexport const focusField = (path: string, root?: ParentNode): boolean => {\n const scope = root ?? document;\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(namedControls(scope).filter(isFocusCandidate))\n : focusFirstOf(pathCandidates(scope, [path]).filter(isFocusCandidate));\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/array.ts","../src/core/arrayOpLog.ts","../src/core/equality.ts","../src/core/env.ts","../src/core/maps.ts","../src/core/path.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/mode.ts","../src/core/debounce.ts","../src/core/persist.ts","../src/react/usePersistForm.ts","../src/react/useForm.ts","../src/react/inputProps.ts","../src/react/useMaskedInput.ts","../src/react/useFormSelector.ts","../src/react/useFormSteps.ts","../src/react/useFormAction.ts","../src/react/FormContext.tsx","../src/react/useField.ts","../src/react/useVariantField.ts","../src/react/useFieldArray.ts","../src/react/useVariantFieldArray.ts","../src/react/useFormError.ts","../src/react/useFormValues.ts","../src/react/useFields.ts","../src/react/useFormFlags.ts","../src/react/createFormHooks.ts","../src/react/fields.tsx","../src/react/focusError.ts"],"names":["key","containerKindAt","z","inner","createStore","devtools","useRef","useEffect","useMemo","options","useState","useStore","useShallow","useCallback","useActionState","createContext","jsx","useContext","initialValue","validateAsync","useId","jsxs","Fragment"],"mappings":";;;;;;;;;;;;;AAEO,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI,IAAA,GAAO,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAA;AAE9B,IAAM,QAAA,GACX,CAAC,CAAA,KACD,CAAC,MACC,CAAA,IAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAEd,IAAM,UAAA,GACX,CAAC,IAAA,EAAc,EAAA,KACf,CAAC,CAAA,KAAM;AACL,EAAA,IAAI,CAAA,KAAM,MAAM,OAAO,EAAA;AACvB,EAAA,IAAI,OAAO,EAAA,IAAM,CAAA,GAAI,QAAQ,CAAA,IAAK,EAAA,SAAW,CAAA,GAAI,CAAA;AACjD,EAAA,IAAI,OAAO,EAAA,IAAM,CAAA,IAAK,MAAM,CAAA,GAAI,IAAA,SAAa,CAAA,GAAI,CAAA;AACjD,EAAA,OAAO,CAAA;AACT,CAAA;AAEK,IAAM,WAAA,GACX,CAAC,CAAA,EAAW,CAAA,KACZ,CAAC,CAAA,KACC,CAAA,KAAM,CAAA,GAAI,CAAA,GAAI,CAAA,KAAM,CAAA,GAAI,CAAA,GAAI,CAAA;AAOzB,IAAM,YAAA,GAAe,CAC1B,MAAA,EACA,SAAA,EACA,SAAA,KACsB;AACtB,EAAA,MAAM,WAAW,IAAI,GAAA;AAAA,IACnB,KAAA,CAAM,IAAA,CA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IAAQ,QAAA;AACtB,EAAA,MAAM,YAAA,GAAe,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,MAAA;AAAA,IACvC,CAAC,MAAM,CAAA,KAAM,EAAA,IAAA,CAAO,OAAO,CAAC,CAAA,EAAG,UAAU,CAAA,IAAK;AAAA,GAChD;AACA,EAAA,MAAM,YAAA,GAAA,CAAgB,MAAA,CAAO,EAAE,CAAA,EAAG,UAAU,CAAA,IAAK,CAAA;AACjD,EAAA,MAAM,QAAA,GAAW,cAAc,KAAK,CAAA;AACpC,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,KAAA,EAAO,YAAY,CAAA,CAAE,MAAA;AAAA,IACvD;AAAA,GACF;AAMA,EAAA,MAAM,mBAAA,GACJ,iBACC,IAAA,KAAS,MAAA,IAAa,SAAS,gBAAA,CAAiB,MAAM,EAAE,MAAA,IAAU,CAAA,CAAA;AACrE,EAAA,MAAM,UAAA,GACJ,YAAA,CAAa,MAAA,GAAS,CAAA,GAClB,YAAA,GACA,sBACE,QAAA,CAAS,MAAA,CAAO,gBAAgB,CAAA,GAChC,EAAC;AACT,EAAA,OAAO,aAAa,UAAU,CAAA;AAChC;AAyBO,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,IAAA,KAA+B;AACtE,EAAA,MAAM,QAAQ,IAAA,IAAQ,QAAA;AACtB,EAAA,OAAO,IAAA,KAAS,EAAA,GAAA,CACX,IAAA,KAAS,MAAA,IACR,QAAA,CAAS,gBAAA,CAAiB,MAAM,CAAA,CAAE,MAAA,IAAU,CAAA,KAC5C,YAAA,CAAa,aAAA,CAAc,KAAK,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA,GAC5D,YAAA,CAAa,cAAA,CAAe,KAAA,EAAO,CAAC,IAAI,CAAC,CAAA,CAAE,MAAA,CAAO,gBAAgB,CAAC,CAAA;AACzE","file":"index.cjs","sourcesContent":["export type IndexMapper = (oldIndex: number) => number | null;\n\nexport const removeAt =\n (i: number): IndexMapper =>\n (n) =>\n n === i ? null : n > i ? n - 1 : n;\n\nexport const insertAt =\n (i: number): IndexMapper =>\n (n) =>\n n >= i ? n + 1 : n;\n\nexport const moveFromTo =\n (from: number, to: number): IndexMapper =>\n (n) => {\n if (n === from) return to;\n if (from < to && n > from && n <= to) return n - 1;\n if (from > to && n >= to && n < from) return n + 1;\n return n;\n };\n\nexport const swapIndices =\n (a: number, b: number): IndexMapper =>\n (n) =>\n n === a ? b : n === b ? a : n;\n\n// The new-index → old-index view of an op, materialized as an array (-1\n// marks a position with no old index: a freshly created row). Derived by\n// INVERTING the op's IndexMapper — the same mapper trusted to re-key\n// errors/touched — so the value transform and the id mapping cannot\n// diverge. Consumed by the array-op log for row-id derivation.\nexport const invertMapper = (\n mapper: IndexMapper,\n oldLength: number,\n newLength: number,\n): readonly number[] => {\n const oldByNew = new Map(\n Array.from({ length: oldLength }, (_, oldIndex) => oldIndex).flatMap(\n (oldIndex) => {\n const newIndex = mapper(oldIndex);\n return newIndex === null ? [] : ([[newIndex, oldIndex]] as const);\n },\n ),\n );\n return Array.from(\n { length: newLength },\n (_, newIndex) => oldByNew.get(newIndex) ?? -1,\n );\n};\n\nconst indexAndTail = (\n rest: string,\n): Readonly<{ index: number; tail: string }> | null => {\n const dotIdx = rest.indexOf(\".\");\n const idxStr = dotIdx === -1 ? rest : rest.slice(0, dotIdx);\n const tail = dotIdx === -1 ? \"\" : rest.slice(dotIdx);\n const idx = Number(idxStr);\n if (!Number.isInteger(idx) || idx < 0 || String(idx) !== idxStr) return null;\n return { index: idx, tail };\n};\n\nexport const reKeyByArrayPath = <V>(\n map: Readonly<Record<string, V>>,\n basePath: string,\n mapper: IndexMapper,\n): Readonly<Record<string, V>> => {\n const prefix = basePath === \"\" ? \"\" : `${basePath}.`;\n return Object.fromEntries(\n Object.entries(map).flatMap(([key, value]) => {\n if (key === basePath) return [[key, value]];\n if (!key.startsWith(prefix)) return [[key, value]];\n const parsed = indexAndTail(key.slice(prefix.length));\n if (parsed === null) return [[key, value]];\n const next = mapper(parsed.index);\n if (next === null) return [];\n return [[`${prefix}${next}${parsed.tail}`, value]];\n }),\n );\n};\n","// A per-store, per-path log of recent array ops, recorded by the core's\n// applyArrayOp and replayed by useFieldArray's row-id derivation. The ops\n// carry the EXACT new→old index mapping, so id derivation never has to\n// guess which of two Object.is-equal rows an op removed or moved — the one\n// case value-based reconciliation cannot decide. A sanctioned mutable-ref\n// cache (like the core's subschemaCache): the log is derived bookkeeping,\n// never part of form state, and the WeakMap releases it with the store.\n\nexport type ArrayOpRecord = Readonly<{\n // The array value the op consumed / produced — reference identity is the\n // chain link: a consumer replays from the record whose `from` matches its\n // last-seen array, on through consecutive records, until it reaches the\n // live array (or gives up and falls back to value reconciliation).\n from: readonly unknown[];\n to: readonly unknown[];\n // newIndex → oldIndex; -1 marks a freshly created row.\n mapping: readonly number[];\n}>;\n\n// Bounded two ways, both loss-limited: a path's record COUNT is capped by\n// COMPOSING its two oldest records into one when consecutive (op mappings\n// compose, so an arbitrarily long run of consecutive ops stays fully\n// replayable in OP_LOG_LIMIT records; only a chain already broken by an\n// external write drops its dead head) — and a store accumulating more than\n// MAX_LOG_PATHS distinct array paths (dynamic row paths on a long-lived\n// singleton form) evicts its oldest path's records, degrading that path to\n// value reconciliation.\nconst OP_LOG_LIMIT = 16;\nconst MAX_LOG_PATHS = 256;\n\n// (second ∘ first): newIndex → the FIRST record's old index. A -1 anywhere\n// along the way stays -1 (the row was created inside the composed span).\nconst composeOps = (\n first: ArrayOpRecord,\n second: ArrayOpRecord,\n): ArrayOpRecord => ({\n from: first.from,\n to: second.to,\n mapping: second.mapping.map((mid) =>\n mid === -1 ? -1 : (first.mapping[mid] ?? -1),\n ),\n});\n\nconst logs = new WeakMap<object, Map<string, readonly ArrayOpRecord[]>>();\n\n// Cap a path's record count, composing the two oldest records when they are\n// consecutive (lossless) and dropping the dead head otherwise. The slice\n// work only happens on overflow — the common case appends untouched.\nconst boundOps = (\n ops: readonly ArrayOpRecord[],\n): readonly ArrayOpRecord[] => {\n const [head, second] = ops;\n if (ops.length <= OP_LOG_LIMIT || head === undefined || second === undefined) {\n return ops;\n }\n return head.to === second.from\n ? [composeOps(head, second), ...ops.slice(2)]\n : ops.slice(1);\n};\n\nexport const recordArrayOp = (\n store: object,\n path: string,\n record: ArrayOpRecord,\n): void => {\n const existing = logs.get(store);\n const byPath = existing ?? new Map<string, readonly ArrayOpRecord[]>();\n if (existing === undefined) logs.set(store, byPath);\n const bounded = boundOps([...(byPath.get(path) ?? []), record]);\n byPath.delete(path);\n byPath.set(path, bounded);\n if (byPath.size > MAX_LOG_PATHS) {\n const oldest = byPath.keys().next().value;\n if (oldest !== undefined) byPath.delete(oldest);\n }\n};\n\nexport const arrayOpsFor = (\n store: object,\n path: string,\n): readonly ArrayOpRecord[] => logs.get(store)?.get(path) ?? [];\n\n// Drop a path's records — called by the consumer after a walk consumed them\n// (the log is per-batch bookkeeping, spent once derived).\nexport const clearArrayOps = (store: object, path: string): void => {\n logs.get(store)?.delete(path);\n};\n\n// Drop the records of the written path and its DESCENDANTS — the paths\n// where a value write can reintroduce a previously-seen array reference\n// (the caller supplies the subtree's values; reset/restore reinstate stored\n// ones; an array op re-seats existing descendant arrays under new indices),\n// which stale records could falsely chain against. Ancestor paths are\n// deliberately KEPT: setAtPath always builds fresh spine arrays, so an\n// ancestor reference can never recur — and an ancestor's earlier records\n// are real history the id walk still replays, bridging the gap this write\n// created. \"\" (whole-values writes) clears all. `keepSelf` is for\n// applyArrayOp itself: the op's own path is exactly what it is about to\n// record, and its earlier same-batch records still chain.\nexport const clearArrayOpsUnder = (\n store: object,\n path: string,\n keepSelf = false,\n): void => {\n const byPath = logs.get(store);\n if (byPath === undefined) return;\n if (path === \"\") {\n byPath.clear();\n return;\n }\n const related = [...byPath.keys()].filter(\n (p) => (p === path && !keepSelf) || p.startsWith(`${path}.`),\n );\n related.forEach((p) => byPath.delete(p));\n};\n","export const isPlainObject = (v: unknown): v is Record<string, unknown> => {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n};\n\n// Structural equality used to decide whether a field still matches its initial\n// value. Recurses into arrays and plain objects; Dates compare by timestamp\n// (re-picking the same date must not leave the field permanently dirty);\n// other exotic objects fall back to Object.is so a real change is never\n// mistaken for \"unchanged\".\nexport const valuesEqual = (a: unknown, b: unknown): boolean => {\n if (Object.is(a, b)) return true;\n // Numbers compare with `===` semantics on top of Object.is: Object.is\n // alone keeps NaN equal to itself (wanted) but tells -0 from 0, and a\n // number input renders both as \"0\", so a field holding -0 against an\n // initial 0 read as permanently dirty with nothing visible to undo.\n if (typeof a === \"number\" && typeof b === \"number\") return a === b;\n if (a instanceof Date && b instanceof Date) {\n // Two invalid Dates are equal: their timestamps are both NaN, which\n // `===` denies, so a cleared or half-typed date against an invalid\n // initial read as dirty forever.\n const [ta, tb] = [a.getTime(), b.getTime()];\n return ta === tb || (Number.isNaN(ta) && Number.isNaN(tb));\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => valuesEqual(v, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n // hasOwn matters: equal counts don't imply equal key SETS. Without it,\n // { realname: undefined } vs { nickname: \"Ann\" } passes (1 === 1, and\n // a.realname === missing b.realname === undefined) without b's real key\n // ever being inspected — dirty tracking would read a real change as\n // clean. With hasOwn plus the length check the key sets must match, so\n // the compare is also symmetric.\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((k) => Object.hasOwn(b, k) && valuesEqual(a[k], b[k]))\n );\n }\n return false;\n};\n\n// The deep compare for a container-valued field runs inside store selectors\n// and watch subscriptions, i.e. on every store change — cache verdicts per\n// value object, keyed by the initial-slice reference each was computed for.\n// A small list (not a single slot) so distinct fields/forms sharing one value\n// object (a module-level default, a shared sentinel array) coexist instead of\n// evicting each other; bounded so no entry grows without limit. Form state is\n// immutable, so identical references always mean an identical verdict, and\n// the WeakMap releases everything when the value object dies.\ntype DirtyVerdict = Readonly<{ initial: unknown; dirty: boolean }>;\nconst dirtyCache = new WeakMap<object, readonly DirtyVerdict[]>();\nconst MAX_VERDICTS = 4;\n\n// The single definition of dirtiness: the current value slice differs\n// structurally from its initial-values slice. Derived (rather than tracked by\n// writers) so reads are accurate at any depth.\nexport const isFieldDirty = (value: unknown, initialValue: unknown): boolean => {\n if (Object.is(value, initialValue)) return false;\n if (typeof value !== \"object\" || value === null) {\n return !valuesEqual(value, initialValue);\n }\n const cached = dirtyCache.get(value) ?? [];\n const hit = cached.find((v) => Object.is(v.initial, initialValue));\n if (hit !== undefined) return hit.dirty;\n const dirty = !valuesEqual(value, initialValue);\n dirtyCache.set(\n value,\n [{ initial: initialValue, dirty }, ...cached].slice(0, MAX_VERDICTS),\n );\n return dirty;\n};\n","// The dev-build test the library consults before emitting a console\n// warning. Bundlers that define NODE_ENV fold it to a constant and drop the\n// dev-only branches; the `typeof process` guard keeps the SAME expression\n// from throwing in a runtime that defines no `process` at all (a CDN/ESM\n// consumer, a test runner without the define). That last case matters most\n// on the submit path: handleSubmit promises never to reject, and the\n// warning that fires only when a save failed was the one line that could\n// break the promise exactly on the failure path. It FAILS OPEN on purpose:\n// an unknowable environment gets the warnings, which cost nothing but a\n// console line.\nexport const isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\n\n// The gate for the two sites that EXPOSE form state: the FormstandDevtools\n// panel (renders every value and error into the page) and the zustand\n// devtools middleware (streams every write to the Redux extension). These\n// must FAIL CLOSED: isDevBuild's \"no process means dev\" reading let a\n// CDN/ESM, Deno, or worker production build mount the panel and keep the\n// middleware live for any end user with the extension installed. Only a\n// readable NODE_ENV that is a string other than \"production\" counts as\n// development; no process, no env, or an unset NODE_ENV all read as\n// production here.\nexport const isDevToolsBuild = (): boolean => {\n if (typeof process === \"undefined\") return false;\n const env = process.env?.[\"NODE_ENV\"];\n return typeof env === \"string\" && env !== \"production\";\n};\n","import type { BoolMap } from \"./types\";\n\n// Own-key reads for the path-keyed maps (errors, touched, isValidating).\n// Their keys are user-controlled strings: a schema may declare a field\n// named `constructor`, a server response may name `toString`, and\n// JSON.parse yields own `__proto__` keys. A bare `map[key]` on a plain\n// object walks the prototype chain for those, so an EMPTY error map read\n// `Object` as the error list at \"constructor\" (and `stringArraysEqual`\n// then threw inside setState on `.every`), while `touched[\"toString\"]` was\n// a truthy function. Every read of these maps by a runtime key goes\n// through here; writes are already safe (computed keys and\n// Object.fromEntries define own properties).\nexport const entryAt = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): V | undefined => (Object.hasOwn(map, key) ? map[key] : undefined);\n\nexport const flagAt = (map: BoolMap, key: string): boolean =>\n Object.hasOwn(map, key) && map[key] === true;\n","import { isPlainObject } from \"./equality\";\n\nexport type PathSegment = string | number;\n\n// What setAtPath creates at an ABSENT slot. The segment type alone cannot\n// tell a z.record keyed by numeric strings from an array (both read\n// \"lookup.0\"), so a caller that knows the schema hands in a resolver; it\n// answers for the dotted prefix being created and returns null where it\n// has no opinion, which falls back to the segment-type rule.\nexport type ContainerKind = \"array\" | \"record\";\nexport type ContainerKindAt = (prefix: string) => ContainerKind | null;\n\n// Segment keys containing \".\" are not addressable (paths are split on dots);\n// use nested objects or index-free keys instead.\n\n// Writes above this index are refused — a typo'd path like \"items.4294967296\"\n// must not allocate a multi-gigabyte array.\nconst MAX_ARRAY_INDEX = 100_000;\n\nconst isIndexSegment = (s: string): boolean => {\n const n = Number(s);\n return Number.isInteger(n) && n >= 0 && String(n) === s;\n};\n\n// Hot path: every field subscription re-resolves its path on every store\n// notification (getAtPath in selectors), so parsing is memoized — a form's\n// paths are a small fixed set. Bounded as an LRU over Map insertion order:\n// a hit re-inserts its key (moving it to the back) and an overflow evicts\n// the front, so an app whose LIVE path set exceeds the cap keeps its hot\n// paths cached instead of re-parsing every one of them after each reset\n// (the old wholesale clear). Eviction only costs re-parsing, never\n// correctness. Same delete-then-set recency idiom as useFieldArray's\n// per-path id cache.\nconst PARSE_CACHE_MAX = 4096;\nconst parseCache = new Map<string, readonly PathSegment[]>();\n\nexport const parsePath = (path: string): readonly PathSegment[] => {\n const cached = parseCache.get(path);\n if (cached !== undefined) {\n parseCache.delete(path);\n parseCache.set(path, cached);\n return cached;\n }\n // Frozen because the array is now SHARED across every caller (and cached):\n // parsePath is a public export, and pre-cache each call returned a private\n // array that was safe to mutate. Freezing enforces the `readonly` type at\n // runtime so an external `.sort()`/`.reverse()`/`.push()` throws instead of\n // silently corrupting the cache for every later lookup of this path.\n const segments = Object.freeze(\n path === \"\"\n ? []\n : path.split(\".\").map((s) => (isIndexSegment(s) ? Number(s) : s)),\n );\n if (parseCache.size >= PARSE_CACHE_MAX) {\n const oldest = parseCache.keys().next().value;\n if (oldest !== undefined) parseCache.delete(oldest);\n }\n parseCache.set(path, segments);\n return segments;\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n// The existing container decides how a segment is interpreted: arrays take\n// numeric segments as indices, records take any segment as a string key (so a\n// z.record keyed \"0\" reads/writes the record key, not an array index). Only\n// when the container is absent does the segment type pick what gets created.\nconst readSegment = (obj: unknown, segment: PathSegment): unknown => {\n if (obj == null) return undefined;\n if (Array.isArray(obj)) {\n return typeof segment === \"number\" ? obj[segment] : undefined;\n }\n // Own properties only: a runtime-built path like \"lookup.constructor\" on a\n // z.record must read as absent, not leak Object.prototype members as field\n // values.\n return isPlainRecord(obj) && Object.hasOwn(obj, String(segment))\n ? obj[String(segment)]\n : undefined;\n};\n\nexport const getAtPath = (obj: unknown, path: string): unknown =>\n parsePath(path).reduce<unknown>(readSegment, obj);\n\nexport type SlotAtPath =\n | Readonly<{ exists: true; value: unknown }>\n | Readonly<{ exists: false }>;\n\n// Resolve `path` while checking that every segment is read from a real\n// container: an in-range array index, or a key on a plain record (containers\n// decide, mirroring readSegment). A segment into an absent or non-container\n// value addresses no slot at all — a full-form parse would key that error at\n// the missing ANCESTOR, not here, so field-scoped validation must skip it\n// rather than parse the leaf's subschema against undefined (which would\n// fabricate a spurious \"required\" error the full pass never produces). Note\n// this checks the CONTAINER, not the value: a leaf that is undefined at the\n// FINAL step through a real record is still an addressable (legitimately\n// empty) slot. Returns the resolved value so callers don't walk twice.\nexport const slotAtPath = (obj: unknown, path: string): SlotAtPath => {\n const walked = parsePath(path).reduce<\n Readonly<{ ok: boolean; current: unknown }>\n >(\n (acc, segment) => {\n const container = acc.current;\n const addressable =\n typeof segment === \"number\"\n ? Array.isArray(container)\n ? segment < container.length\n : isPlainRecord(container)\n : isPlainRecord(container);\n return !acc.ok || !addressable\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n );\n return walked.ok ? { exists: true, value: walked.current } : { exists: false };\n};\n\n// Whether the path addresses an OWN slot: every step reads a real\n// container's own key / in-range array index, the final segment included.\n// This is stricter than slotAtPath, which treats a MISSING final key on a\n// real record as an addressable (legitimately empty) slot — here it reads\n// false. The consumer is setValue's identity guard: writing `undefined`\n// over an ABSENT key is NOT a no-op (it creates the key, a real state\n// change — key-count dirtiness, persisted shape), while writing it over a\n// key that exists holding undefined is.\nexport const hasOwnSlot = (obj: unknown, path: string): boolean =>\n parsePath(path).reduce<Readonly<{ ok: boolean; current: unknown }>>(\n (acc, segment) => {\n const container = acc.current;\n const owns = Array.isArray(container)\n ? typeof segment === \"number\" && segment < container.length\n : isPlainRecord(container) && Object.hasOwn(container, String(segment));\n return !acc.ok || !owns\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n ).ok;\n\nconst writeIntoArray = (\n arr: readonly unknown[],\n index: number,\n rest: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): readonly unknown[] => {\n const length = Math.max(arr.length, index + 1);\n const child = writeSegments(arr[index], rest, value, kindAt, [\n ...prefix,\n index,\n ]);\n // A refused write deeper down hands the same slot back; the array is\n // then unchanged too, so callers see the same reference (see setValue).\n if (index < arr.length && child === arr[index]) return arr;\n return Array.from({ length }, (_, i) => (i === index ? child : arr[i]));\n};\n\nconst refusesHugeIndex = (index: number): boolean => {\n if (index > MAX_ARRAY_INDEX) {\n console.warn(\n `[formstand] refusing to write array index ${index} (max ${MAX_ARRAY_INDEX}); value left unchanged.`,\n );\n return true;\n }\n return false;\n};\n\nconst writeSegments = (\n obj: unknown,\n segments: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): unknown => {\n const [head, ...rest] = segments;\n if (head === undefined) return value;\n\n if (Array.isArray(obj)) {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray(obj, head, rest, value, kindAt, prefix);\n }\n\n // Records take any segment as a string key (mirroring readSegment), so a\n // z.record keyed by a large numeric id is writable — the array-index cap\n // only applies where an array actually exists or would be created.\n if (isPlainRecord(obj)) {\n // Spreading is only safe for PLAIN objects: spreading a Date/Map/Set or\n // class instance keeps own enumerable props but drops the prototype (and\n // for Map/Set, every entry) — the original would be silently destroyed.\n // Refuse, like the other unwritable shapes above.\n if (!isPlainObject(obj)) {\n console.warn(\n `[formstand] cannot write key \"${String(head)}\" through a non-plain object (Date/Map/Set/class instance); value left unchanged.`,\n );\n return obj;\n }\n const key = String(head);\n const child = writeSegments(obj[key], rest, value, kindAt, [\n ...prefix,\n key,\n ]);\n // Same reference back from a refused write below: keep this object\n // too, so a refused write rebuilds no spine (watchers used to fire,\n // the op log was cleared and spine server verdicts released although\n // \"value left unchanged\" had just been warned). An undefined written\n // over an ABSENT key is a real change (it creates the key), so the\n // own-key check keeps that write.\n if (child === obj[key] && Object.hasOwn(obj, key)) return obj;\n return { ...obj, [key]: child };\n }\n\n // Absent (or non-container) value: create a container. The schema's\n // answer for this slot wins when the caller supplied one (a z.record\n // keyed \"0\" must not become an array, and a z.array must not become a\n // record); otherwise the segment type decides, as the docs state.\n const kind =\n kindAt?.(prefix.map(String).join(\".\")) ??\n (typeof head === \"number\" ? \"array\" : \"record\");\n if (kind === \"array\") {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray([], head, rest, value, kindAt, prefix);\n }\n const key = String(head);\n return { [key]: writeSegments(undefined, rest, value, kindAt, [...prefix, key]) };\n};\n\n// `containerKindAt` is optional so the bare utility keeps its segment-type\n// rule; createForm passes the schema-derived resolver from validation.ts.\nexport const setAtPath = <T>(\n obj: T,\n path: string,\n value: unknown,\n containerKindAt?: ContainerKindAt,\n): T => writeSegments(obj, parsePath(path), value, containerKindAt, []) as T;\n","import { z } from \"zod\";\nimport {\n type ContainerKind,\n type ContainerKindAt,\n type PathSegment,\n getAtPath,\n parsePath,\n} from \"./path\";\nimport type { ErrorMap } from \"./types\";\n\nexport type SettledValidationResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type ValidationResult<TOutput> =\n | SettledValidationResult<TOutput>\n // Returned by the sync `validate()` when the schema needs async parsing:\n // the async pass has already been started and `promise` resolves with its\n // outcome.\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledValidationResult<TOutput>>;\n }>;\n\nexport type SettledFieldValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: readonly string[] }>;\n\nexport type FieldValidationResult =\n | SettledFieldValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldValidationResult>;\n }>;\n\n// The plural (validateFields) mirrors the singular's discriminated shape\n// instead of returning boolean | Promise<boolean>: a returned Promise is\n// truthy, so the old union let `if (form.validateFields(paths))` silently\n// pass a gate the moment the schema gained an async refinement. `errors`\n// carries only the entries within the requested paths' scope.\nexport type SettledFieldsValidationResult =\n | Readonly<{ kind: \"valid\" }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>;\n\nexport type FieldsValidationResult =\n | SettledFieldsValidationResult\n | Readonly<{\n kind: \"pending\";\n promise: Promise<SettledFieldsValidationResult>;\n }>;\n\nconst issuePathToFormPath = (path: readonly PropertyKey[]): string =>\n path\n .filter((segment): segment is string | number => typeof segment !== \"symbol\")\n .join(\".\");\n\ntype FlatIssue = Readonly<{ path: string; message: string }>;\n\n// A failing plain `z.union` produces a single `invalid_union` issue whose real\n// per-branch issues live in `issue.errors` with paths relative to the union's\n// position. Recurse into them (prefixed with the union's own path) so users\n// get field-level messages instead of one generic \"Invalid input\"; keep the\n// union's own message only when no branch supplies anything more specific.\nconst expandIssue = (\n issue: z.core.$ZodIssue,\n prefix: readonly PropertyKey[],\n): readonly FlatIssue[] => {\n const at = [...prefix, ...issue.path];\n if (issue.code === \"invalid_union\") {\n const nested = issue.errors.flatMap((branch) =>\n branch.flatMap((sub) => expandIssue(sub, at)),\n );\n if (nested.length > 0) return nested;\n }\n return [{ path: issuePathToFormPath(at), message: issue.message }];\n};\n\n// Grouped through a Map the reduce itself creates, then materialized once.\n// The previous shape rebuilt the accumulator with `{ ...acc, [path]: ... }`\n// per issue, which is quadratic in the issue count: 3000 empty rows under\n// z.array(z.object({ name: z.string().min(1) })) spent 1.3 s here against\n// zod's 7 ms parse. Mutating the Map (and the per-key message list) is the\n// sanctioned reduce-accumulator exception, and a Map also sidesteps the\n// prototype trap outright: a key of \"__proto__\" or \"constructor\" is just a\n// key. Object.fromEntries defines every key as an own data property, so the\n// returned record carries those keys as own properties too.\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n Object.fromEntries(\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Map<string, string[]>>((acc, { path, message }) => {\n const existing = acc.get(path);\n if (existing === undefined) {\n acc.set(path, [message]);\n } else if (!existing.includes(message)) {\n // Union branches often repeat the same complaint; drop exact\n // duplicates.\n existing.push(message);\n }\n return acc;\n }, new Map()),\n );\n\nexport const validateSync = <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): SettledValidationResult<z.output<TSchema>> => {\n const result = schema.safeParse(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\nexport const validateAsync = async <TSchema extends z.ZodType>(\n schema: TSchema,\n values: z.input<TSchema>,\n): Promise<SettledValidationResult<z.output<TSchema>>> => {\n const result = await schema.safeParseAsync(values);\n return result.success\n ? { kind: \"valid\", data: result.data }\n : { kind: \"invalid\", errors: flattenIssues(result.error.issues) };\n};\n\n// The message fallback covers the dual-package hazard: with two zod copies\n// loaded, the thrown error is not an instance of *this* copy's class.\nexport const isAsyncRequiredError = (e: unknown): boolean =>\n e instanceof z.core.$ZodAsyncError ||\n (e instanceof Error &&\n /Encountered Promise during synchronous parse/i.test(e.message));\n\n// For the fire-and-forget entry points (createForm's validateOnMount,\n// useField's change and blur triggers): they drop the pending promise, so\n// a rejecting pass (an async refine whose fetch failed) would surface as an\n// unhandled rejection with no pointer back to the form. The pass has\n// already released its in-flight flags by the time this runs; what is\n// left is to say where the error came from.\nexport const reportBackgroundFailure = (error: unknown): void => {\n console.error(\n \"[formstand] a background validation pass threw (an async refinement rejected). Its in-flight flags were released. The error:\",\n error,\n );\n};\n\n// True when `key` is `path` itself or a descendant (\"a.b\" under \"a\"). The\n// root \"\" matches only the \"\" key — whole-form scope is never implicit;\n// call sites that want it (validateField(\"\"), focusFirstError's fallback)\n// handle the root explicitly instead of inheriting a wildcard.\nexport const isPathOrChild = (key: string, path: string): boolean =>\n key === path || key.startsWith(`${path}.`);\n\n// Re-key an error map produced by parsing a field's subschema so its keys are\n// absolute form paths (\"\" becomes the field path itself).\nexport const prefixErrorKeys = (errors: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? errors\n : Object.fromEntries(\n Object.entries(errors).map(([k, v]) => [\n k === \"\" ? path : `${path}.${k}`,\n v,\n ]),\n );\n\n// The empty representation a field's schema accepts: undefined when the\n// field is optional (or the wrappers are unrecognized — undefined is the\n// library-wide default empty), null when it is nullable but not optional.\n// Lets a cleared input round-trip to a valid blank based on what the schema\n// states rather than guessing from runtime values.\nexport const emptyValueForSchema = (schema: z.ZodType): null | undefined => {\n const walk = (s: z.ZodType, sawNullable: boolean): null | undefined => {\n if (s instanceof z.ZodOptional) return undefined;\n if (s instanceof z.ZodNullable) {\n return walk(s.unwrap() as z.ZodType, true);\n }\n return sawNullable ? null : undefined;\n };\n return walk(schema, false);\n};\n\n// Whether the schema ACCEPTS its own emptyValue as input — the judgment the\n// string-shaped bindings need before writing it on a cleared input. An\n// optional field takes undefined, a nullable one takes null, and a\n// defaulted/prefaulted one takes undefined too (the default fills it at\n// parse, so clearing reads as \"back to the default\"). A bare required field\n// does NOT: its emptyValue is undefined only as the library-wide fallback,\n// and writing that would trade a visible \"\" the schema can at least judge\n// for a hole it rejects — which is why text and select bindings keep \"\" for\n// non-clearable fields. The check is deliberately as shallow as\n// emptyValueForSchema's walk: a wrapper that hides the optionality from\n// emptyValue (readonly, catch, pipe) hides it here too, so the pair can\n// never disagree about whether the emptyValue is legal.\nexport const isClearableSchema = (schema: z.ZodType): boolean =>\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodNullable ||\n schema instanceof z.ZodDefault ||\n schema instanceof z.ZodPrefault;\n\n// One unwrap step for the lax structural walk below: wrappers that are\n// transparent to a path (optional/nullable/default/readonly/catch/pipe/...)\n// yield their inner schema; anything else returns null and is judged as-is.\nconst unwrapForWalk = (s: z.ZodType): z.ZodType | null => {\n if (s instanceof z.ZodOptional || s instanceof z.ZodNullable) {\n return s.unwrap() as z.ZodType;\n }\n if (\n s instanceof z.ZodDefault ||\n s instanceof z.ZodPrefault ||\n s instanceof z.ZodCatch ||\n s instanceof z.ZodReadonly ||\n s instanceof z.ZodNonOptional\n ) {\n return s.def.innerType as z.ZodType;\n }\n // Form values are z.input, so a pipe is traversed through its input side.\n // A preprocess pipe's input side is a transform with no children, so its\n // output side is the only place the keys live.\n if (s instanceof z.ZodPipe) {\n const input = s.def.in as z.ZodType;\n return input instanceof z.ZodTransform ? (s.def.out as z.ZodType) : input;\n }\n // A lazy schema's children live behind its getter. The budgeted walks\n // cannot loop on a recursive schema; the path-bounded ones stop at the\n // path's end.\n if (s instanceof z.ZodLazy) return s.def.getter() as z.ZodType;\n return null;\n};\n\n// Leaves that provably have no children: remaining path segments under one of\n// these cannot exist in the schema.\nconst isLeafSchema = (s: z.ZodType): boolean =>\n s instanceof z.ZodString ||\n s instanceof z.ZodNumber ||\n s instanceof z.ZodBoolean ||\n s instanceof z.ZodBigInt ||\n s instanceof z.ZodDate ||\n s instanceof z.ZodEnum ||\n s instanceof z.ZodLiteral ||\n s instanceof z.ZodNull ||\n s instanceof z.ZodUndefined ||\n s instanceof z.ZodVoid ||\n s instanceof z.ZodNaN ||\n s instanceof z.ZodSymbol;\n\n// Every unwrap and every consumed segment costs one step — generous for any\n// real path, but it bounds pathological wrapper towers.\nconst SCHEMA_WALK_BUDGET = 64;\n\n// Lax structural check: can `path` possibly exist under `schema`? Used to\n// warn when validateField targets a path the schema cannot contain (which\n// would otherwise silently validate as always-valid). Deliberately biased\n// toward \"yes\": objects answer from their shape (a catchall/loose object\n// accepts any key), arrays accept any numeric index into their element, and\n// everything too dynamic to judge — records, maps, tuples, unions,\n// intersections, lazies, any/unknown, unrecognized nodes — answers true so\n// the warning can never be a false positive. Only a provable miss (a key\n// absent from a closed object shape, a string segment into an array, or\n// segments remaining under a scalar leaf) answers false.\nexport const schemaHasPath = (schema: z.ZodType, path: string): boolean => {\n const walk = (\n s: z.ZodType,\n segments: readonly PathSegment[],\n budget: number,\n ): boolean => {\n if (budget <= 0) return true;\n const inner = unwrapForWalk(s);\n if (inner !== null) return walk(inner, segments, budget - 1);\n const [head, ...rest] = segments;\n if (head === undefined) return true;\n if (s instanceof z.ZodObject) {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n // Own-key read: a bare index would walk the prototype chain, so\n // \"constructor\" would resolve to Object's constructor and read as a\n // declared key of the shape.\n const child = Object.hasOwn(shape, String(head))\n ? shape[String(head)]\n : undefined;\n if (child !== undefined) return walk(child, rest, budget - 1);\n // A loose/catchall object accepts keys beyond the shape (a ZodNever\n // catchall — strictObject — rejects them like a closed shape does).\n const catchall = s.def.catchall;\n return catchall !== undefined && !(catchall instanceof z.ZodNever);\n }\n if (s instanceof z.ZodArray) {\n return typeof head === \"number\"\n ? walk(s.element as z.ZodType, rest, budget - 1)\n : false;\n }\n return !isLeafSchema(s);\n };\n return walk(schema, parsePath(path), SCHEMA_WALK_BUDGET);\n};\n\n// Can the schema legitimately hold values of DIFFERENT JSON kinds at\n// `path`? persistForm's shape guard compares a stored draft against the\n// initial values kind by kind and reads a mismatch as a schema change. A\n// coerced scalar (z.coerce.number() behind a \"\" initial, 42 stored), a\n// pipe, a union whose variants shape the key differently, and anything\n// too dynamic to judge (any, unknown, lazy, catch) all make a mismatch\n// legitimate. Biased toward \"yes\" like schemaHasPath: only a path that\n// walks through closed objects, arrays, tuples and records to a plain leaf\n// answers false, so the guard can refuse a draft only where the schema\n// provably has one shape.\nexport const schemaAllowsKindChangeAt = (\n schema: z.ZodType,\n path: string,\n): boolean => {\n const flexible = (s: z.ZodType): boolean =>\n s instanceof z.ZodUnion ||\n s instanceof z.ZodDiscriminatedUnion ||\n s instanceof z.ZodPipe ||\n s instanceof z.ZodAny ||\n s instanceof z.ZodUnknown ||\n s instanceof z.ZodLazy ||\n s instanceof z.ZodCatch ||\n (s.def as Readonly<{ coerce?: boolean }>).coerce === true;\n // Optional/nullable/default/readonly/nonoptional are transparent to the\n // kind question; a pipe or catch is itself an answer, so it stays.\n const strip = (s: z.ZodType): z.ZodType => {\n if (s instanceof z.ZodOptional || s instanceof z.ZodNullable) {\n return strip(s.unwrap() as z.ZodType);\n }\n if (\n s instanceof z.ZodDefault ||\n s instanceof z.ZodPrefault ||\n s instanceof z.ZodReadonly ||\n s instanceof z.ZodNonOptional\n ) {\n return strip(s.def.innerType as z.ZodType);\n }\n return s;\n };\n const walk = (\n s: z.ZodType,\n segments: readonly PathSegment[],\n budget: number,\n ): boolean => {\n if (budget <= 0) return true;\n const node = strip(s);\n if (flexible(node)) return true;\n const [head, ...rest] = segments;\n if (head === undefined) return false;\n if (node instanceof z.ZodObject) {\n const shape: Readonly<Record<string, z.ZodType | undefined>> =\n node.shape;\n const child = Object.hasOwn(shape, String(head))\n ? shape[String(head)]\n : undefined;\n return child === undefined ? true : walk(child, rest, budget - 1);\n }\n if (node instanceof z.ZodArray) {\n return typeof head === \"number\"\n ? walk(node.element as z.ZodType, rest, budget - 1)\n : true;\n }\n if (node instanceof z.ZodTuple && typeof head === \"number\") {\n const item = node.def.items[head] as z.ZodType | undefined;\n return item === undefined ? true : walk(item, rest, budget - 1);\n }\n if (node instanceof z.ZodRecord) {\n return walk(node.valueType as z.ZodType, rest, budget - 1);\n }\n // A container kind the walk does not model: it cannot judge.\n return true;\n };\n return walk(schema, parsePath(path), SCHEMA_WALK_BUDGET);\n};\n\nconst hasChecks = (s: z.ZodType): boolean => {\n const checks = (s.def as Readonly<{ checks?: readonly unknown[] }>).checks;\n return checks !== undefined && checks.length > 0;\n};\n\n// Walk the schema along a dot path so field-level validation can parse just\n// that field instead of the whole form. Returns null (meaning: fall back to a\n// full-form parse) unless every *traversed* level is a plain ZodObject or\n// ZodArray with no checks — a refinement on a traversed level could target\n// this field's path, so extraction would miss or fail to clear its errors.\n// Wrappers (optional/nullable/default/pipe/union/record/...) also bail: their\n// error keying differs from a direct parse of the inner value. The leaf itself\n// may carry any checks — they belong to the field.\n// The subschema at `path` for INTROSPECTION (useField's emptyValue and\n// clearable): what blank does the schema accept here, and may a cleared\n// control write it. Unlike fieldSchemaAtPath (validateField's fast path,\n// which must refuse anything a scoped parse could get wrong), this walk\n// looks THROUGH wrappers at container levels (an optional profile object\n// still has a profile.name) and INTO discriminated unions and unions (a\n// variant's field is read from the first member that declares the key;\n// members rarely disagree on a shared key's wrapper, and the heuristic\n// fallback is what a miss costs). The last segment's own wrapper is kept:\n// it is exactly what the two introspection helpers read.\n// Does this union option claim the discriminant value the live object\n// holds? Read from the option's own shape (a literal or an enum at the\n// discriminator key), so no zod internals are relied on.\nconst optionClaims = (\n option: z.ZodType,\n discriminator: string,\n tag: unknown,\n): boolean => {\n const strip = (s: z.ZodType): z.ZodType => {\n const inner = unwrapForWalk(s);\n return inner === null ? s : strip(inner);\n };\n const node = strip(option);\n if (!(node instanceof z.ZodObject)) return false;\n const shape: Readonly<Record<string, z.ZodType | undefined>> = node.shape;\n const at = Object.hasOwn(shape, discriminator)\n ? shape[discriminator]\n : undefined;\n if (at === undefined) return false;\n const leaf = strip(at);\n if (leaf instanceof z.ZodLiteral) {\n return (leaf.def.values as readonly unknown[]).includes(tag);\n }\n if (leaf instanceof z.ZodEnum) {\n return Object.values(leaf.def.entries as Record<string, unknown>).includes(\n tag,\n );\n }\n return false;\n};\n\n// `values`, when given, resolves a discriminated union against the variant\n// the live value holds: a key SHARED by several variants (amount on a card\n// and on a cash variant, nullable on one of them) used to read the first\n// variant's wrapper whatever was active, so clearing the field on the\n// other variant wrote the wrong empty. Without values (or when no variant\n// claims the live tag) the first declaring member still answers.\nexport const fieldSchemaForIntrospection = (\n schema: z.ZodType,\n path: string,\n values?: unknown,\n): z.ZodType | null => {\n const childOf = (\n s: z.ZodType,\n segment: PathSegment,\n holder: unknown,\n ): z.ZodType | null => {\n const inner = unwrapForWalk(s);\n if (inner !== null) return childOf(inner, segment, holder);\n if (s instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = s.shape;\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (s instanceof z.ZodArray && typeof segment === \"number\") {\n return s.element as z.ZodType;\n }\n if (s instanceof z.ZodTuple && typeof segment === \"number\") {\n return (s.def.items[segment] as z.ZodType | undefined) ?? null;\n }\n // Every record key shares one value schema, and the walk reads keys\n // as strings, so a numeric segment is a key here too (z.record(\n // z.number(), ...) parses \"5\" as a key at runtime).\n if (s instanceof z.ZodRecord) {\n return s.valueType as z.ZodType;\n }\n // An intersection's keys live on either side; the left side answers\n // first, the way zod merges them.\n if (s instanceof z.ZodIntersection) {\n return (\n childOf(s.def.left as z.ZodType, segment, holder) ??\n childOf(s.def.right as z.ZodType, segment, holder)\n );\n }\n if (s instanceof z.ZodDiscriminatedUnion || s instanceof z.ZodUnion) {\n const options = s.def.options as readonly z.ZodType[];\n const discriminator =\n s instanceof z.ZodDiscriminatedUnion ? s.def.discriminator : null;\n const tag =\n discriminator !== null && typeof holder === \"object\" && holder !== null\n ? (holder as Record<string, unknown>)[discriminator]\n : undefined;\n const live =\n discriminator === null || tag === undefined\n ? undefined\n : options.find((option) => optionClaims(option, discriminator, tag));\n const candidates = live === undefined ? options : [live];\n return candidates.reduce<z.ZodType | null>(\n (found, option) => found ?? childOf(option, segment, holder),\n null,\n );\n }\n return null;\n };\n const segments = parsePath(path);\n return segments.reduce<Readonly<{ s: z.ZodType | null; prefix: string }>>(\n (acc, segment) =>\n acc.s === null\n ? acc\n : {\n s: childOf(\n acc.s,\n segment,\n values === undefined ? undefined : getAtPath(values, acc.prefix),\n ),\n prefix:\n acc.prefix === \"\"\n ? String(segment)\n : `${acc.prefix}.${String(segment)}`,\n },\n { s: schema, prefix: \"\" },\n ).s;\n};\n\n// Does the schema accept undefined at this field: optional, defaulted or\n// prefaulted, looked for through a nullable wrapper (.nullable().optional()\n// and .optional().nullable() both take it). persistForm's gap fill asks\n// this rather than isClearableSchema: a nullable-but-required key does not\n// accept the hole JSON leaves behind, so an absent one must be filled.\nexport const schemaAcceptsUndefined = (schema: z.ZodType): boolean =>\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodDefault ||\n schema instanceof z.ZodPrefault ||\n (schema instanceof z.ZodNullable &&\n schemaAcceptsUndefined(schema.unwrap() as z.ZodType));\n\n// Whether a gap fill may walk the keys of the value at `path`: false only\n// where the schema PROVABLY shapes the keys some other way. A union's keys\n// belong to whichever variant a value holds, a record's, map's or set's\n// keys are data, an array's or tuple's slots are rows, and a scalar leaf\n// has no keys. Everything else answers true: a plain object, an\n// intersection of objects, a lazy or preprocessed object, and a path the\n// walk cannot place, the same safer-guess bias the fill applies to a key\n// it cannot place. (An earlier spelling asked \"is this a ZodObject\" and\n// stopped filling under lazy, intersection and preprocess roots.)\nexport const isObjectSchemaAt = (schema: z.ZodType, path: string): boolean => {\n const sub = fieldSchemaForIntrospection(schema, path);\n if (sub === null) return true;\n const strip = (s: z.ZodType): z.ZodType => {\n const inner = unwrapForWalk(s);\n return inner === null ? s : strip(inner);\n };\n const node = strip(sub);\n return !(\n node instanceof z.ZodUnion ||\n node instanceof z.ZodDiscriminatedUnion ||\n node instanceof z.ZodRecord ||\n node instanceof z.ZodMap ||\n node instanceof z.ZodSet ||\n node instanceof z.ZodArray ||\n node instanceof z.ZodTuple ||\n isLeafSchema(node)\n );\n};\n\n// setAtPath's absent-slot resolver, from the schema: the container the\n// schema declares at `prefix` (wrappers looked through, like the\n// introspection walk above), or null where it declares a leaf, a union,\n// or nothing, which leaves setAtPath on its segment-type rule. A write of\n// \"lookup.0\" into an absent optional z.record used to create an array\n// here, which the record schema then rejected (\"expected record,\n// received array\"); the schema knew the answer all along.\n//\n// This walk is NOT fieldSchemaForIntrospection's: that one reads a union's\n// key from the first member that declares it, which is the right guess for\n// emptyValue/clearable (members rarely disagree on a shared key's wrapper)\n// and the wrong one here, where two variants can declare the same key as\n// an object and as an array (a reviewer's reproduction: `details` as\n// `z.object` in one variant and `z.array` in another made every write\n// create the first variant's record, and the array variant then failed\n// validation). A union anywhere on the path, or at its end, means the\n// schema has no single answer, so the segment-type rule decides, which is\n// also what the typed-paths guide says.\nexport const containerKindAt =\n (schema: z.ZodType): ContainerKindAt =>\n (prefix: string): ContainerKind | null => {\n const unwrapAll = (s: z.ZodType): z.ZodType => {\n const inner = unwrapForWalk(s);\n return inner === null ? s : unwrapAll(inner);\n };\n const step = (s: z.ZodType, segment: PathSegment): z.ZodType | null => {\n const inner = unwrapAll(s);\n if (inner instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> = inner.shape;\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (inner instanceof z.ZodArray && typeof segment === \"number\") {\n return inner.element as z.ZodType;\n }\n if (inner instanceof z.ZodTuple && typeof segment === \"number\") {\n return (inner.def.items[segment] as z.ZodType | undefined) ?? null;\n }\n if (inner instanceof z.ZodRecord) {\n return inner.valueType as z.ZodType;\n }\n return null;\n };\n const sub = parsePath(prefix).reduce<z.ZodType | null>(\n (current, segment) => (current === null ? null : step(current, segment)),\n schema,\n );\n if (sub === null) return null;\n const inner = unwrapAll(sub);\n if (inner instanceof z.ZodArray || inner instanceof z.ZodTuple) {\n return \"array\";\n }\n if (inner instanceof z.ZodObject || inner instanceof z.ZodRecord) {\n return \"record\";\n }\n return null;\n };\n\nexport const fieldSchemaAtPath = (\n schema: z.ZodType,\n path: string,\n): z.ZodType | null =>\n parsePath(path).reduce<z.ZodType | null>((current, segment: PathSegment) => {\n if (current === null || hasChecks(current)) return null;\n if (current instanceof z.ZodObject && typeof segment === \"string\") {\n const shape: Readonly<Record<string, z.ZodType | undefined>> =\n current.shape;\n // Own-key read, like every other walk in the library: a bare index\n // resolves \"constructor\"/\"__proto__\" through the prototype chain to\n // a non-schema value, which then CRASHES the reduce (def.checks on a\n // function; safeParse on Object.prototype) — and the subschema cache\n // would keep the poisoned entry. Runtime-built paths (server error\n // fields mapped onto validateField) are the realistic entry point.\n return Object.hasOwn(shape, segment) ? (shape[segment] ?? null) : null;\n }\n if (current instanceof z.ZodArray && typeof segment === \"number\") {\n return current.element as z.ZodType;\n }\n return null;\n }, schema);\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { createStore } from \"zustand/vanilla\";\nimport { devtools } from \"zustand/middleware\";\nimport {\n type IndexMapper,\n insertAt,\n invertMapper,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { clearArrayOpsUnder, recordArrayOp } from \"./arrayOpLog\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport { isDevBuild, isDevToolsBuild } from \"./env\";\nimport { entryAt, flagAt } from \"./maps\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n IsUnion,\n PathDepth,\n} from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, hasOwnSlot, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type FieldsValidationResult,\n type SettledFieldValidationResult,\n type SettledFieldsValidationResult,\n type SettledValidationResult,\n type ValidationResult,\n containerKindAt,\n fieldSchemaAtPath,\n isAsyncRequiredError,\n isPathOrChild,\n prefixErrorKeys,\n reportBackgroundFailure,\n schemaHasPath,\n validateAsync,\n validateSync,\n} from \"./validation\";\n\nexport type ReadonlyStoreApi<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type CreateFormOptions<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n initialValues: z.input<TSchema>;\n // TYPE-LEVEL ONLY: the typed-path depth budget for this form, in SEGMENTS\n // (default 9). The runtime ignores it entirely — every path API already\n // walks any depth — it only widens (or narrows) the FieldPath union the\n // form's typed surface is checked against. Raising it is a deliberate\n // TypeScript compile-time trade: the union's size grows with every level\n // the type recurses into, and every path-taking call pays for it in the\n // editor. Reach for it when one deep store backs many forms (a global\n // store whose leaves sit past 9 segments); must be a number LITERAL\n // (e.g. `pathDepth: 12`) so the budget stays a compile-time constant.\n // The `PathDepth` constraint (0-25, the Prev table's range) makes an\n // out-of-range literal or a widened `number` variable a compile error at\n // the call site. The intersection additionally rejects a UNION depth\n // (`cond ? 12 : 9` infers D = 9 | 12, a budget assignable to neither\n // Form<S, 9> nor Form<S, 12>): for a single literal the extra operand is\n // `unknown` and the type stays `D`, keeping literal inference intact; for\n // a union it becomes `never`, so the value can't satisfy the property and\n // the call errors instead of minting an unusable Form type.\n pathDepth?: D & (IsUnion<D> extends true ? never : unknown);\n mode?: ValidationMode;\n reValidateMode?: ValidationMode;\n // Run a full validation pass at creation so the error map (and flags derived\n // from it, like `useIsValid`) reflect the initial values immediately rather\n // than reading as error-free until the first blur/change/submit. Async\n // schemas validate in the background. Note this surfaces errors for untouched\n // fields right away — gate error display on `touched` if that's not wanted.\n validateOnMount?: boolean;\n // Connect the form's store to the Redux DevTools extension (zustand's\n // devtools middleware), named so multiple forms are distinguishable:\n // `devtools: \"checkout\"` shows a \"checkout\" instance with every state\n // write inspectable and time-travelable. `true` uses \"formstand\". Off by\n // default; when the extension isn't installed the middleware is inert.\n devtools?: boolean | string;\n}>;\n\nexport type SubmitHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n) => void | Promise<void>;\n\nexport type InvalidSubmitHandler = (errors: ErrorMap) => void;\n\nexport type SubmitOptions = Readonly<{\n force?: boolean;\n // The options-object spelling of submit's second argument, the shape\n // useFormAction's FormActionOptions always had, so the two surfaces\n // read the same. In the positional shape a positional onInvalid wins.\n onInvalid?: InvalidSubmitHandler;\n // Called when onValid throws or rejects (the \"error\" SubmitResult) — the\n // save-failure hook, mirroring onInvalid for the validation side. The\n // result still resolves {kind: \"error\"}, so imperative submit() callers\n // can keep switching on it instead.\n onError?: (error: unknown) => void;\n}>;\n\n// \"valid\": validation passed and onValid ran to completion. \"invalid\":\n// validation failed (onInvalid ran; errors written and their fields marked\n// touched, unless the values changed while validation was in flight — see\n// submit). \"skipped\": another submit was already in flight and force wasn't\n// set. \"error\": onValid threw or rejected — submit resolves with the thrown\n// value instead of rejecting, so handleSubmit used as an event handler never\n// produces an unhandled rejection. No error state is written for this kind;\n// surface the failure yourself (e.g. via setError).\nexport type SubmitResult<TOutput> =\n | Readonly<{ kind: \"valid\"; data: TOutput }>\n | Readonly<{ kind: \"invalid\"; errors: ErrorMap }>\n | Readonly<{ kind: \"skipped\" }>\n | Readonly<{ kind: \"error\"; error: unknown }>;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key. Exported for\n// wrappers that forward setError / clearErrors / validateField calls and\n// had to re-derive `FieldPath | \"\"` by hand.\nexport type ErrorPath<TValues, D extends PathDepth = DefaultPathDepth> =\n | FieldPath<TValues, D>\n | \"\";\n\n// No keepDirty: per-field dirtiness is derived from values vs initialValues,\n// and reset makes those equal by definition — a kept dirty map would say\n// \"dirty\" while every field-level read says \"clean\".\nexport type ResetOptions = Readonly<{\n keepErrors?: boolean;\n keepTouched?: boolean;\n keepSubmitCount?: boolean;\n}>;\n\n// The same slice useField renders, so an imperative reader (getFieldState,\n// a watchField listener) and a bound component agree field for field.\nexport type FieldSnapshot<TValue> = Readonly<{\n value: TValue;\n // The slice of initialValues at the path (what `dirty` compares against).\n initialValue: TValue;\n error: readonly string[] | undefined;\n // The first message, or undefined: the display shorthand useField has.\n firstError: string | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// firstError derives from `error`, so the identity compare on `error`\n// covers it.\nconst shallowFieldEqual = <TValue>(\n a: FieldSnapshot<TValue>,\n b: FieldSnapshot<TValue>,\n): boolean =>\n Object.is(a.value, b.value) &&\n Object.is(a.initialValue, b.initialValue) &&\n a.error === b.error &&\n a.touched === b.touched &&\n a.dirty === b.dirty &&\n a.isValidating === b.isValidating;\n\nexport type Form<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n // Type-level marker only — never present at runtime. It carries the form's\n // typed-path depth budget (createForm's `pathDepth`, default 9) in a\n // directly-inferable position so the React hooks' `Form<TSchema, D>`\n // parameters recover D from the form argument (inferring it out of the\n // FieldPath instantiations in the method types below is not something TS\n // can do). It also makes the budget part of the form's identity:\n // Form<S, 12> is deliberately not assignable to Form<S, 9>.\n \"~pathDepth\"?: D;\n schema: TSchema;\n store: ReadonlyStoreApi<FormState<z.input<TSchema>>>;\n getState: () => FormState<z.input<TSchema>>;\n subscribe: (\n listener: (\n state: FormState<z.input<TSchema>>,\n prev: FormState<z.input<TSchema>>,\n ) => void,\n ) => () => void;\n getField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n // The listener gets the previous snapshot too, the way watchValue\n // passes the previous value, so \"did the error just appear\" and \"did\n // the field just become dirty\" need no ref in the caller.\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n previous: FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n ) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => () => void;\n // Watches THE WHOLE values object — the name is watchValue + \"s\" as in\n // \"all the values\", not \"watchValue over many paths\". Fires whenever any\n // value changes (reference-compared). A multi-path watcher, if one ever\n // ships, would be a new API rather than a change to this one.\n watchValues: (\n listener: (\n values: z.input<TSchema>,\n previous: z.input<TSchema>,\n ) => void,\n ) => () => void;\n setValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n value: FieldValue<z.input<TSchema>, P>,\n ) => void;\n setValues: (next: z.input<TSchema>) => void;\n setTouched: (path: FieldPath<z.input<TSchema>, D>, touched?: boolean) => void;\n setSubmitting: (value: boolean) => void;\n setMode: (mode: ValidationMode) => void;\n setReValidateMode: (mode: ValidationMode) => void;\n setError: (\n path: ErrorPath<z.input<TSchema>, D>,\n errors: string | readonly string[],\n ) => void;\n // Replaces the whole server channel. An empty list is the absence of an\n // error, never an entry, the same rule setError and addErrors apply.\n setErrors: (errors: ErrorMap) => void;\n // The merge-many sibling of setError: server responses arrive as a MAP\n // of runtime-keyed field errors, and mapping them one setError at a time\n // forced a typed-path cast per call (the docs' own examples did), while\n // setErrors REPLACES the whole channel and cannot be used incrementally.\n // The server channel is inherently runtime-keyed, so this takes the map\n // as-is; an empty array removes its key, like setError.\n addErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>, D>) => void;\n // The patch type omits `errors`: the merged map is derived from\n // schemaErrors/serverErrors, so writing it directly is unrepresentable for\n // TS callers (plain-JS writes are ignored with a warning).\n updateState: (\n updater: (\n state: FormState<z.input<TSchema>>,\n ) => Partial<Omit<FormState<z.input<TSchema>>, \"errors\">>,\n ) => void;\n reset: (\n nextInitial?: Partial<z.input<TSchema>>,\n options?: ResetOptions,\n ) => void;\n // Reset one field to its initial value, clearing its (and its descendants')\n // dirty/touched/error state.\n resetField: (path: FieldPath<z.input<TSchema>, D>) => void;\n adoptValues: (values: z.input<TSchema>) => void;\n // One-shot read of a field's full slice (value/error/touched/dirty/\n // isValidating) — the imperative sibling of useField's state.\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>, D>) => FieldValidationResult;\n // Mirrors validateField's discriminated result — \"pending\" (carrying the\n // already-started async pass's promise) when the schema needs async\n // parsing. A bare boolean | Promise<boolean> union would let a truthy\n // in-flight Promise silently pass `if (form.validateFields(...))` gates.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => FieldsValidationResult;\n // Settled result types, deliberately: an AWAITED async pass can never\n // resolve \"pending\" (the promise IS the pending state), and the wider\n // union forced every exhaustive switch to carry a dead case — against\n // this codebase's own no-default-arm ethos. validateFieldsAsync below\n // was always typed this way; these two now match.\n validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>, D>,\n ) => Promise<SettledFieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>, D>[],\n ) => Promise<SettledFieldsValidationResult>;\n // Two call shapes, one body: the positional (onValid, onInvalid?,\n // options?) and the options object (onValid, { onInvalid, onError,\n // force }), which is the shape useFormAction's FormActionOptions always\n // had. Before the second shape, options without an invalid handler\n // meant `submit(onValid, undefined, { force: true })`.\n submit: {\n (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>>;\n (\n onValid: SubmitHandler<TSchema>,\n options: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>>;\n };\n // Every array op takes an ARRAY path (ArrayFieldPath: variable-length\n // arrays, optional/nullable included, tuples and scalars excluded), so a\n // misaddressed op is blamed on the path argument. The index-only ops\n // used to take any FieldPath and compile against a z.string(), then warn\n // and skip at runtime.\n arrayPush: <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>,\n ) => void;\n arrayRemove: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n index: number,\n ) => void;\n arrayInsert: <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n index: number,\n item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>,\n ) => void;\n arrayMove: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (\n path: ArrayFieldPath<z.input<TSchema>, D>,\n a: number,\n b: number,\n ) => void;\n // Same two shapes as submit.\n handleSubmit: {\n (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ): (event?: {\n preventDefault: () => void;\n }) => Promise<SubmitResult<z.output<TSchema>>>;\n (\n onValid: SubmitHandler<TSchema>,\n options: SubmitOptions,\n ): (event?: {\n preventDefault: () => void;\n }) => Promise<SubmitResult<z.output<TSchema>>>;\n };\n diff: () => Readonly<Record<string, unknown>>;\n dirtyFields: () => readonly string[];\n snapshot: () => FormState<z.input<TSchema>>;\n restore: (snapshot: FormState<z.input<TSchema>>) => void;\n}>;\n\nconst emptyErrors = {} as ErrorMap;\nconst emptyBools = {} as BoolMap;\n\nconst identityMapper: IndexMapper = (n) => n;\n\nconst omitKey = <V>(\n map: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> =>\n Object.fromEntries(Object.entries(map).filter(([k]) => k !== key));\n\n// The many-keys sibling, one pass over the map. Folding omitKey per key\n// (reduce with omitKey) rebuilt the whole map once per key, quadratic in\n// the number of paths a plural pass carries.\nconst omitKeys = <V>(\n map: Readonly<Record<string, V>>,\n keys: ReadonlySet<string>,\n): Readonly<Record<string, V>> => {\n if (keys.size === 0) return map;\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !keys.has(k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst inScopeOfAny = (key: string, paths: readonly string[]): boolean =>\n paths.some((p) => isPathOrChild(key, p));\n\n// Drop every entry keyed at or under any of `paths` (\"items\" covers\n// \"items.0.name\") — the shared scope filter for the path-keyed maps. Returns\n// the input map unchanged when nothing is in scope, so identity-based\n// subscribers don't re-fire.\nconst omitScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => !inScopeOfAny(k, paths));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\nconst pickScope = <V>(\n map: Readonly<Record<string, V>>,\n paths: readonly string[],\n): Readonly<Record<string, V>> =>\n Object.fromEntries(\n Object.entries(map).filter(([k]) => inScopeOfAny(k, paths)),\n );\n\n// Replace the slice of `prev` at or under `paths` with `scoped` (whose keys\n// must already be within scope).\nconst mergeScopedErrors = (\n prev: ErrorMap,\n scoped: ErrorMap,\n paths: readonly string[],\n): ErrorMap => ({ ...omitScope(prev, paths), ...scoped });\n\n// Drop entries at `path` itself or an ancestor of it (\"a\" over \"a.b\"). The\n// root \"\" entry is an ancestor of every path, so any value write releases it\n// — a value write below a container stales the container-level server\n// verdict too, per the documented release contract.\nconst releaseAncestorEntries = <V>(\n map: Readonly<Record<string, V>>,\n path: string,\n): Readonly<Record<string, V>> => {\n const entries = Object.entries(map);\n const kept = entries.filter(([k]) => k !== \"\" && !isPathOrChild(path, k));\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\n// Minimal divergent paths between values and initialValues: recurse through\n// plain objects, report anything else (scalars, arrays, type mismatches) at\n// its own path — arrays report their base path, and a divergent non-record\n// root reports \"\". This is the derived source for diff()/dirtyFields(); the\n// boolean per-field question is isFieldDirty.\nconst dirtyPathsOf = (\n values: unknown,\n initial: unknown,\n prefix: string,\n): readonly string[] => {\n if (Object.is(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\n // One structural recursion: the deep compare runs only at leaf/array\n // boundaries below, never per ancestor level — otherwise every node is\n // re-deep-compared once per level above it (O(n × depth) for diff()).\n const keys = new Set([...Object.keys(values), ...Object.keys(initial)]);\n const childPaths = [...keys].flatMap((k) =>\n dirtyPathsOf(\n values[k],\n initial[k],\n prefix === \"\" ? k : `${prefix}.${k}`,\n ),\n );\n if (childPaths.length > 0) return childPaths;\n // Every shared key compared equal, so the key SETS decide: a mismatch\n // where the extra key holds undefined ({} vs { nickname: undefined })\n // reports the object itself, keeping diff()/dirtyFields() non-empty\n // whenever isFieldDirty/useIsDirty say dirty (valuesEqual's own rule).\n const sameKeySet =\n Object.keys(values).length === Object.keys(initial).length &&\n Object.keys(values).every((k) => Object.hasOwn(initial, k));\n return sameKeySet ? [] : [prefix];\n }\n return valuesEqual(values, initial) ? [] : [prefix];\n};\n\n// Key for the whole-form async validation's ownership token (internal —\n// form-level in-flight state lives in FormState.isValidatingForm).\nconst FORM_SEQ_KEY = \"__form__\";\n\n// Key for submit's ownership token: reset()/adoptValues() clear the token\n// map, so an in-flight submit notices the form was rebased under it even\n// when the values reference is unchanged (a bare reset() on a pristine form\n// restores the same initialValues reference).\nconst SUBMIT_SEQ_KEY = \"__submit__\";\n\nconst stringArraysEqual = (\n a: readonly string[],\n b: readonly string[],\n): boolean => a === b || (a.length === b.length && a.every((v, i) => v === b[i]));\n\n// Preserve the previous array reference for entries whose messages didn't\n// change (and the previous map itself when nothing changed at all), so field\n// subscriptions comparing errors by identity don't re-fire on every pass.\n// Own-key reads (entryAt) throughout: a bare `prev[k]` for k =\n// \"constructor\" on an EMPTY map returned `Object`, which passed the\n// undefined check and crashed stringArraysEqual on `.every` inside\n// setState. Reachable from setError(\"constructor\", ...), addErrors, and a\n// schema that simply declares a field by that name.\nconst reuseErrorRefs = (next: ErrorMap, prev: ErrorMap): ErrorMap => {\n if (next === prev) return prev;\n const entries = Object.entries(next).map(([k, v]) => {\n const old = entryAt(prev, k);\n return [\n k,\n old !== undefined && stringArraysEqual(old, v) ? old : v,\n ] as const;\n });\n const sameShape =\n entries.length === Object.keys(prev).length &&\n entries.every(([k, v]) => entryAt(prev, k) === v);\n return sameShape ? prev : Object.fromEntries(entries);\n};\n\n// What one scope's parse yields: the error map scoped to `path` (sub-schema\n// results re-key to absolute form paths; full-form results filter to the\n// path's scope, except the root \"\" whose scope is explicitly the whole\n// form), plus the WHOLE map when the parse was full-form. A full parse\n// judged every key against the live values, so it is also the truth about\n// keys outside the scope; a subschema parse judged only its slot and\n// carries null. See pruneUnreported for what the commit does with it.\ntype ScopeParse = Readonly<{ scoped: ErrorMap; full: ErrorMap | null }>;\n\nconst noScopeErrors: ScopeParse = { scoped: emptyErrors, full: null };\n\nconst scopeParse = (\n result: SettledValidationResult<unknown>,\n path: string,\n viaSubschema: boolean,\n): ScopeParse => {\n const errors = result.kind === \"invalid\" ? result.errors : emptyErrors;\n return viaSubschema\n ? { scoped: prefixErrorKeys(errors, path), full: null }\n : {\n scoped: path === \"\" ? errors : pickScope(errors, [path]),\n full: errors,\n };\n};\n\n// Drop every entry of `prev` that a full-form parse did not report. The\n// parse is the truth for the live values, so an entry it is silent on is\n// stale however it got there. The canonical case is a discriminated union\n// whose discriminant changes under a field-scoped pass (the select's own\n// change validation): that pass replaces only the keys under the\n// discriminant, so the OLD variant's errors (payment.cardNumber after the\n// switch to paypal) survived until a full validate() happened to run, and\n// useIsValid read false for a form the schema accepted. Pruning never ADDS\n// an entry outside the scope: a full parse run on behalf of one field still\n// surfaces nothing for fields the user has not reached.\n// A key present in both maps takes the parse's CURRENT list: a cross-field\n// rule that keys a dynamic message onto another field (\"must equal 2\"\n// after a changed to 2) used to keep the old message there, since only\n// absence was read from the full map. reuseErrorRefs keeps list identity\n// when the messages are equal.\nconst pruneUnreported = (prev: ErrorMap, full: ErrorMap): ErrorMap => {\n const entries = Object.entries(prev);\n const kept = entries.filter(([k]) => Object.hasOwn(full, k));\n const unchanged =\n kept.length === entries.length &&\n kept.every(([k, list]) => full[k] === list);\n return unchanged\n ? prev\n : Object.fromEntries(kept.map(([k, list]) => [k, full[k] ?? list]));\n};\n\n// The one rule for a list-valued error map handed in by the app: an empty\n// (or missing) list is the ABSENCE of an error, never an entry. setError and\n// addErrors always dropped those; setErrors, updateState's channel patches\n// and restore() kept them, so the same state read valid to useIsValid\n// (which skips empty lists), errored to useFormSteps (key presence) and\n// `[]` from useField.\nconst dropEmptyLists = (map: ErrorMap): ErrorMap => {\n const entries = Object.entries(map);\n const kept = entries.filter(\n ([, list]) => list !== undefined && list.length > 0,\n );\n return kept.length === entries.length ? map : Object.fromEntries(kept);\n};\n\n// The one merge rule between the two error channels: the schema's message\n// wins at a key (it re-judged the same value the server did), server entries\n// show where the schema is silent. Returns the schema map's identity when\n// the server channel adds nothing.\nconst mergeErrorChannels = (schema: ErrorMap, server: ErrorMap): ErrorMap => {\n // Own-key check, not `schema[k] === undefined`: for a runtime-built key\n // like \"__proto__\" the bare read returns Object.prototype (never\n // undefined), which would silently drop the server entry from the merge.\n const extra = Object.entries(server).filter(\n ([k]) => !Object.hasOwn(schema, k),\n );\n return extra.length === 0\n ? schema\n : { ...schema, ...Object.fromEntries(extra) };\n};\n\ntype ErrorChannels = Readonly<{\n errors: ErrorMap;\n schemaErrors: ErrorMap;\n serverErrors: ErrorMap;\n}>;\n\n// The one way error state is written: patch a channel (or both) and the\n// user-visible `errors` map is re-derived, reusing per-key refs so\n// identity-based subscribers don't re-fire.\nconst errorChannels = (\n state: ErrorChannels,\n patch: Readonly<{ schemaErrors?: ErrorMap; serverErrors?: ErrorMap }>,\n): ErrorChannels => {\n const schemaErrors = patch.schemaErrors ?? state.schemaErrors;\n const serverErrors = patch.serverErrors ?? state.serverErrors;\n // Unchanged channels mean an unchanged merge — skip it, so no-op writes\n // (every keystroke with an empty server channel) don't rescan the map.\n if (\n schemaErrors === state.schemaErrors &&\n serverErrors === state.serverErrors\n ) {\n return { errors: state.errors, schemaErrors, serverErrors };\n }\n return {\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n state.errors,\n ),\n };\n};\n\n// The release contract for a value write at `path`: server entries at the\n// path or below go (that subtree was replaced), entries at ancestors go too\n// (container verdicts are stale), and a runtime \"\" path (the imperative\n// surface is string-typed) releases everything.\nconst releaseSpine = (server: ErrorMap, path: string): ErrorMap =>\n path === \"\"\n ? emptyErrors\n : releaseAncestorEntries(omitScope(server, [path]), path);\n\n// A bulk values write releases only the verdicts whose value slice actually\n// changed — a server error on an untouched field survives a setValues that\n// rewrites its siblings. The \"\" entry compares the whole values object, so\n// any change releases a form-level verdict.\nconst releaseChangedSlices = (\n server: ErrorMap,\n prevValues: unknown,\n nextValues: unknown,\n): ErrorMap => {\n const entries = Object.entries(server);\n const kept = entries.filter(([k]) =>\n valuesEqual(getAtPath(prevValues, k), getAtPath(nextValues, k)),\n );\n return kept.length === entries.length ? server : Object.fromEntries(kept);\n};\n\n// D infers as a LITERAL from `options.pathDepth` (the `D extends PathDepth`\n// constraint is a union of literals, so inference stays literal); when the\n// option is omitted, D falls back to the default budget of 9. An\n// out-of-range literal (26, -1) or a `number`-typed variable fails the\n// constraint here, at the call site.\n//\n// NoInfer on the RETURNED depth: `options.pathDepth` is D's only inference\n// site on purpose. Without it, `createFormHooks(createForm(schema, opts),\n// name)` inferred the inner D from the outer call's contextual return type,\n// whose own D was still unresolved, so D became the whole PathDepth union\n// and every depth-typed bound hook (useXField, useXFieldArray, useXIsDirty)\n// collapsed its path argument to never. The const-form shape the docs\n// show never hit it; the inline one did.\nexport const createForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n): Form<TSchema, NoInfer<D>> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\n // Every value write shares one schema-derived answer for \"what container\n // does an absent slot get\" (see setAtPath): built once per form, called\n // only when a write has to create a container.\n const kindAt = containerKindAt(schema);\n const initialReValidateMode: ValidationMode =\n options.reValidateMode ?? \"onChange\";\n\n const initial: FormState<Values> = {\n values: options.initialValues,\n initialValues: options.initialValues,\n errors: emptyErrors,\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n touched: emptyBools,\n isSubmitting: false,\n submitCount: 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n mode: initialMode,\n reValidateMode: initialReValidateMode,\n };\n\n // The devtools middleware is opt-in and otherwise absent — a plain store\n // has zero overhead. `enabled` stays true when opted in even in\n // production builds: opting in IS the signal, and without the browser\n // extension the middleware is inert anyway.\n const store =\n options.devtools === undefined || options.devtools === false\n ? createStore<FormState<Values>>(() => initial)\n : createStore<FormState<Values>>()(\n devtools(() => initial, {\n name:\n typeof options.devtools === \"string\"\n ? options.devtools\n : \"formstand\",\n // Non-production only, matching zustand's own devtools default:\n // opting in during development must NOT stream every keystroke to\n // an end user who happens to have the extension installed, where\n // a module-singleton form's unbounded time-travel history is a\n // real memory + serialization cost. Fail-closed gate: a runtime\n // without a readable NODE_ENV (CDN/ESM, Deno, a worker) reads as\n // production here, unlike the console-warning gate.\n enabled: isDevToolsBuild(),\n }),\n );\n\n // A full pass replaces the schema channel wholesale; the server channel is\n // untouched, which is the whole preservation story — a background pass\n // can't wipe a server verdict because it never writes that channel.\n const commitFullPass = (\n state: FormState<Values>,\n next: ErrorMap,\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(next, state.schemaErrors),\n });\n\n const validate = (): ValidationResult<z.output<TSchema>> => {\n if (asyncScopes.has(\"\")) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n try {\n const result = validateSyncLatched(\"\", schema, store.getState().values);\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n }));\n return result;\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateAsyncOnForm() };\n }\n throw e;\n }\n };\n\n const validateFields = (\n paths: readonly string[],\n ): FieldsValidationResult => {\n if (paths.length === 0) return { kind: \"valid\" };\n // A \"\" path means whole-form scope (only reachable past the FieldPath\n // type, e.g. runtime-built path lists): delegate to the full pass so\n // manual errors are preserved, mirroring validateField(\"\").\n if (paths.some((p) => p === \"\")) {\n const result = validate();\n return result.kind === \"pending\"\n ? { kind: \"pending\", promise: result.promise.then(settledFormResult) }\n : settledFormResult(result);\n }\n const values = store.getState().values;\n // Fast path: when every requested path extracts a subschema, parse\n // just those slots instead of the whole form (a wizard step on a\n // 200-field schema stops paying for the other 190 fields per click).\n // This matches the full parse EXACTLY because extraction bailing is\n // what guards cross-field rules: fieldSchemaAtPath returns null when\n // any traversed level carries refinements or wrappers, so an\n // ancestor refine that could key errors into these paths forces the\n // full parse below.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, values),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n // Scopes already latched as async-requiring go straight to the async\n // pass. Skip scopes parse nothing and contribute no latch key — a\n // latched full-form \"\" must not divert a batch whose parses are all\n // sync subschemas (or nothing at all).\n const anyLatched = allViaSubschema\n ? scopes.some(\n ({ path, scope }) =>\n scope.kind === \"parse\" && asyncScopes.has(path),\n )\n : asyncScopes.has(\"\");\n if (anyLatched) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n try {\n if (allViaSubschema) {\n const merged = scopes.reduce<ErrorMap>(\n (acc, { path, scope }) =>\n scope.kind === \"skip\"\n ? acc\n : {\n ...acc,\n ...scopeParse(\n validateSyncLatched(path, scope.schema, scope.value),\n path,\n true,\n ).scoped,\n },\n {},\n );\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, merged, paths, null),\n }));\n return settledFields(merged);\n }\n const result = validateSyncLatched(\"\", schema, values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedErrors = pickScope(fullErrors, paths);\n store.setState((state) => ({\n ...state,\n ...commitScopedErrors(state, requestedErrors, paths, fullErrors),\n }));\n return settledFields(requestedErrors);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldsAsync(paths) };\n }\n throw e;\n }\n };\n\n // How to validate one field: parse its extracted subschema against the\n // slot's value when the path is reachable through check-free objects/\n // arrays, parse the full form filtered to the path's scope otherwise (so\n // cross-field refinements targeting the path still land), or skip when the\n // path addresses no slot (an out-of-range array index — parsing the\n // subschema against undefined would fabricate an error no full-form parse\n // produces). One \"parse\" variant carries the whole triple so the sync and\n // async passes cannot diverge arm-by-arm.\n type FieldScope =\n | Readonly<{ kind: \"skip\" }>\n | Readonly<{\n kind: \"parse\";\n schema: z.ZodType;\n value: unknown;\n viaSubschema: boolean;\n }>;\n\n // Scopes whose sync parse has hit an async refinement. The schema is fixed\n // for the form's lifetime, so once a scope requires async parsing it always\n // will — remember it and go straight to the async pass instead of paying a\n // doomed sync parse per validation (per keystroke in onChange mode). Keyed\n // like the parses themselves: \"\" for full-form, the path for subschema\n // parses. A sanctioned mutable-ref cache, like subschemaCache below.\n const asyncScopes = new Set<string>();\n\n // validateSync, latching the scope when its parse turns out to need async\n // — the caller still routes the rethrown error to the async pass.\n const validateSyncLatched = <S extends z.ZodType>(\n key: string,\n scopeSchema: S,\n value: z.input<S>,\n ): SettledValidationResult<z.output<S>> => {\n try {\n return validateSync(scopeSchema, value);\n } catch (e) {\n if (isAsyncRequiredError(e)) asyncScopes.add(key);\n throw e;\n }\n };\n\n // The subschema for a path is a pure function of the form's fixed schema —\n // cache it so per-keystroke validation doesn't re-walk the schema.\n const subschemaCache = new Map<string, z.ZodType | null>();\n const subschemaAt = (path: string): z.ZodType | null => {\n const cached = subschemaCache.get(path);\n if (cached !== undefined) return cached;\n const sub = fieldSchemaAtPath(schema, path);\n subschemaCache.set(path, sub);\n return sub;\n };\n\n // Field validation on a path the schema cannot contain silently returns\n // valid — easy to hit through the docs-sanctioned casts for runtime-built\n // paths. Warn once per path per form (a sanctioned mutable-ref cache, like\n // subschemaCache above: checked paths never need re-walking).\n const checkedSchemaPaths = new Set<string>();\n const warnMissingSchemaPath = (fn: string, path: string): void => {\n if (path === \"\" || checkedSchemaPaths.has(path)) return;\n checkedSchemaPaths.add(path);\n if (!schemaHasPath(schema, path)) {\n console.warn(\n `[formstand] ${fn}(\"${path}\"): path does not exist in the schema — result will always be valid.`,\n );\n }\n };\n\n const fieldScopeFor = (path: string, values: Values): FieldScope => {\n const sub = path === \"\" ? null : subschemaAt(path);\n if (sub === null) {\n return { kind: \"parse\", schema, value: values, viaSubschema: false };\n }\n const slot = slotAtPath(values, path);\n return slot.exists\n ? { kind: \"parse\", schema: sub, value: slot.value, viaSubschema: true }\n : { kind: \"skip\" };\n };\n\n const parseScopeAsync = async (\n path: string,\n scope: FieldScope,\n ): Promise<ScopeParse> =>\n scope.kind === \"skip\"\n ? noScopeErrors\n : scopeParse(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n\n // Whether the value an async pass judged is no longer the live one. A\n // subschema scope parsed ONLY its slot, so only that slot's identity\n // decides: comparing the whole values reference (the old rule) discarded\n // a \"username taken\" verdict, and cleared its in-flight flag, the moment\n // the user moved on and typed into email while the check was in flight.\n // A full-form scope exists precisely because an ancestor refine may read\n // any field, so the whole reference still decides there. A skip scope\n // parsed nothing against an absent slot; it goes stale only if something\n // has since created that slot.\n const scopeStale = (\n scope: FieldScope,\n path: string,\n valuesAtStart: Values,\n live: Values,\n ): boolean => {\n if (live === valuesAtStart) return false;\n switch (scope.kind) {\n case \"skip\":\n return slotAtPath(live, path).exists;\n case \"parse\":\n return scope.viaSubschema\n ? !Object.is(getAtPath(live, path), scope.value)\n : true;\n }\n };\n\n const fieldResult = (scoped: ErrorMap): SettledFieldValidationResult => {\n const messages = Object.values(scoped).flat();\n return messages.length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: messages };\n };\n\n // The plural counterpart: reports the scoped error MAP (entries under the\n // requested paths) rather than one field's flat message list. Every input\n // derives from flattenIssues, which never emits an empty message list, so\n // key presence alone decides validity.\n const settledFields = (scoped: ErrorMap): SettledFieldsValidationResult =>\n Object.keys(scoped).length === 0\n ? { kind: \"valid\" }\n : { kind: \"invalid\", errors: scoped };\n\n // Whole-form (\"\" path) delegation, shared by the sync and async plural\n // passes so their scoping of a full-pass verdict cannot diverge.\n const settledFormResult = (\n result: SettledValidationResult<z.output<TSchema>>,\n ): SettledFieldsValidationResult =>\n settledFields(result.kind === \"invalid\" ? result.errors : emptyErrors);\n\n // The commit rule for any scoped validation: replace the schema-error\n // slice under `paths` and release the server verdicts there — a\n // validation explicitly targeting a scope supersedes the server's word on\n // it. Shared by the singular and plural, sync and async passes so the\n // supersede rule lives exactly once. When the pass ran a FULL parse,\n // `full` carries the whole map and the stale entries outside the scope\n // go with it (pruneUnreported); a subschema pass passes null.\n const commitScopedErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n paths: readonly string[],\n full: ErrorMap | null,\n ): ErrorChannels =>\n errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(\n full === null\n ? state.schemaErrors\n : pruneUnreported(state.schemaErrors, full),\n scoped,\n paths,\n ),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, paths),\n });\n\n // How ONE field validation's scoped errors land. validateField(\"\") is a\n // whole-form pass, so it lands like validate() (server channel untouched).\n const commitFieldErrors = (\n state: FormState<Values>,\n parse: ScopeParse,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, parse.scoped)\n : commitScopedErrors(state, parse.scoped, [path], parse.full);\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n const scope = fieldScopeFor(path, store.getState().values);\n // Only PARSE scopes consult the latch — a skip scope parses nothing, so\n // it can never require async parsing and settles synchronously (below)\n // even while the full-form \"\" key is latched. The latch key mirrors\n // what the parse would run: the path for a subschema parse, the full\n // form (\"\") for a bailed extraction.\n if (\n scope.kind === \"parse\" &&\n asyncScopes.has(scope.viaSubschema ? path : \"\")\n ) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n try {\n const parse =\n scope.kind === \"skip\"\n ? noScopeErrors\n : scopeParse(\n validateSyncLatched(\n scope.viaSubschema ? path : \"\",\n scope.schema,\n scope.value,\n ),\n path,\n scope.viaSubschema,\n );\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, parse, path),\n }));\n return fieldResult(parse.scoped);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n return { kind: \"pending\", promise: validateFieldAsync(path) };\n }\n throw e;\n }\n };\n\n const snapshotField = (\n state: FormState<Values>,\n path: string,\n ): FieldSnapshot<unknown> => {\n const value = getAtPath(state.values, path);\n const initialValue = getAtPath(state.initialValues, path);\n const error = entryAt(state.errors, path);\n return {\n value,\n initialValue,\n error,\n firstError: error?.[0],\n touched: flagAt(state.touched, path),\n dirty: isFieldDirty(value, initialValue),\n isValidating: flagAt(state.isValidating, path),\n };\n };\n\n // Ownership tokens for in-flight async passes (a sanctioned mutable-ref\n // cache, like the subscription refs). Tokens are unique by construction —\n // each claim mints a fresh Symbol — so cleared or reissued keys can never\n // collide with a token an in-flight pass still holds.\n const sequences = new Map<string, symbol>();\n\n const claimPass = (key: string): symbol => {\n const pass = Symbol(key);\n sequences.set(key, pass);\n return pass;\n };\n\n const validateAsyncOnForm = async (): Promise<\n SettledValidationResult<z.output<TSchema>>\n > => {\n const pass = claimPass(FORM_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({ ...state, isValidatingForm: true }));\n\n const result = await validateAsync(schema, valuesAtStart).catch(\n (error: unknown) => {\n // A throwing refinement (a rejected fetch inside an async refine)\n // rejects the parse itself, and the rejection travels on to the\n // caller as it always did. The flag this pass set is still its\n // own, though: releasing it here is what keeps isValidatingForm\n // from reading true forever after one network failure.\n if (sequences.get(FORM_SEQ_KEY) === pass) {\n store.setState((state) => ({ ...state, isValidatingForm: false }));\n }\n throw error;\n },\n );\n\n const live = store.getState();\n const stillOwns = sequences.get(FORM_SEQ_KEY) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\n if (stillOwns) {\n store.setState((state) => ({ ...state, isValidatingForm: false }));\n }\n return result;\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFullPass(\n state,\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n isValidatingForm: false,\n }));\n return result;\n };\n\n const validateFieldsAsync = async (\n paths: readonly string[],\n ): Promise<SettledFieldsValidationResult> => {\n if (paths.length === 0) return { kind: \"valid\" };\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n return settledFormResult(await validateAsyncOnForm());\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n // Same fast path as the sync plural (see validateFields): when every\n // requested path extracts a subschema, parse just those slots. The\n // async plural used to parse the whole form regardless, so a wizard\n // step (useFormSteps routes through here) paid for every other step's\n // fields, and an unrelated field's async refine ran on every advance.\n // Extraction bailing still guards cross-field rules: one path whose\n // scope does not extract sends the whole batch to the full parse.\n const scopes = paths.map((path) => ({\n path,\n scope: fieldScopeFor(path, valuesAtStart),\n }));\n const allViaSubschema = scopes.every(\n ({ scope }) =>\n scope.kind === \"skip\" ||\n (scope.kind === \"parse\" && scope.viaSubschema),\n );\n store.setState((state) => ({\n ...state,\n isValidating: {\n ...state.isValidating,\n ...Object.fromEntries(paths.map((p) => [p, true] as const)),\n },\n }));\n\n // Whichever parse ran, each path's errors are read back per path: the\n // slot parses (in parallel) by their own key, the full parse scoped to\n // the path. One variant per parse shape, so the two cannot be mixed.\n type BatchParse =\n | Readonly<{ kind: \"slots\"; byPath: ReadonlyMap<string, ErrorMap> }>\n | Readonly<{ kind: \"full\"; errors: ErrorMap }>;\n const parseBatch = async (): Promise<BatchParse> =>\n allViaSubschema\n ? {\n kind: \"slots\",\n byPath: new Map(\n await Promise.all(\n scopes.map(\n async ({ path, scope }) =>\n [\n path,\n (await parseScopeAsync(path, scope)).scoped,\n ] as const,\n ),\n ),\n ),\n }\n : {\n kind: \"full\",\n errors: await validateAsync(schema, valuesAtStart).then(\n (result) =>\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n ),\n };\n const parsed = await parseBatch().catch((error: unknown) => {\n // Same release-on-rejection rule as the form-level pass: every path\n // this pass still owns gets its flag back before the rejection\n // travels on, so one rejected refine cannot strand a whole step's\n // in-flight flags.\n const stillOwned = new Set(\n paths.filter((p) => sequences.get(p) === passes.get(p)),\n );\n if (stillOwned.size > 0) {\n store.setState((state) => ({\n ...state,\n isValidating: omitKeys(state.isValidating, stillOwned),\n }));\n }\n throw error;\n });\n const errorsFor = (path: string): ErrorMap => {\n switch (parsed.kind) {\n case \"slots\":\n return parsed.byPath.get(path) ?? emptyErrors;\n case \"full\":\n return pickScope(parsed.errors, [path]);\n }\n };\n const requestedErrors: ErrorMap = Object.fromEntries(\n paths.flatMap((path) => Object.entries(errorsFor(path))),\n );\n const requested = settledFields(requestedErrors);\n\n // Three tiers per path: still OWNED (this pass is the latest for it, so\n // it clears the flag it set), and among those still FRESH (its scope's\n // value is the live one, so its verdict lands). A full-form scope is\n // fresh only while the whole values reference holds; a subschema scope\n // only while its own slot does, so an unrelated field changing in\n // flight no longer discards the batch.\n const live = store.getState();\n const owned = scopes.filter(\n ({ path }) => sequences.get(path) === passes.get(path),\n );\n const fresh = owned\n .filter(\n ({ path, scope }) =>\n !scopeStale(scope, path, valuesAtStart, live.values),\n )\n .map(({ path }) => path);\n const ownedKeys = new Set(owned.map(({ path }) => path));\n if (owned.length === 0) return requested;\n\n store.setState((state) => ({\n ...state,\n ...(fresh.length === 0\n ? {}\n : commitScopedErrors(\n state,\n Object.fromEntries(\n fresh.flatMap((path) => Object.entries(errorsFor(path))),\n ),\n fresh,\n // The prune map describes the values the batch STARTED with.\n // A skip scope (an index into an empty array) still reads as\n // fresh after an unrelated change, so a batch can commit under\n // changed values; pruning with the stale map then dropped\n // errors committed elsewhere in flight (an email error landing\n // while a wizard step with such a path validated). The prune\n // rides only while the whole values reference held.\n parsed.kind === \"full\" && live.values === valuesAtStart\n ? parsed.errors\n : null,\n )),\n isValidating: omitKeys(state.isValidating, ownedKeys),\n }));\n\n return requested;\n };\n\n const validateFieldAsync = async (\n path: string,\n ): Promise<SettledFieldValidationResult> => {\n warnMissingSchemaPath(\"validateFieldAsync\", path);\n // The root \"\" is whole-form scope: delegate to the form-level pass so\n // the in-flight flag lands in isValidatingForm — the single slot for\n // whole-form validation — instead of booking an isValidating[\"\"] entry\n // no consumer watches.\n if (path === \"\") {\n const result = await validateAsyncOnForm();\n return fieldResult(\n result.kind === \"invalid\" ? result.errors : emptyErrors,\n );\n }\n const pass = claimPass(path);\n const valuesAtStart = store.getState().values;\n const scope = fieldScopeFor(path, valuesAtStart);\n store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const releaseOwnFlag = (): void => {\n if (sequences.get(path) === pass) {\n store.setState((state) => ({\n ...state,\n isValidating: omitKey(state.isValidating, path),\n }));\n }\n };\n const parse = await parseScopeAsync(path, scope).catch(\n (error: unknown) => {\n // Release-on-rejection, as in the form-level pass: the \"checking\"\n // flag a throwing refine would otherwise leave behind is the one\n // every spinner and submit gate on this field reads.\n releaseOwnFlag();\n throw error;\n },\n );\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || scopeStale(scope, path, valuesAtStart, live.values)) {\n releaseOwnFlag();\n return fieldResult(parse.scoped);\n }\n\n store.setState((state) => ({\n ...state,\n ...commitFieldErrors(state, parse, path),\n isValidating: omitKey(state.isValidating, path),\n }));\n\n return fieldResult(parse.scoped);\n };\n\n const applyArrayOp = (\n path: string,\n nextArray: (current: readonly unknown[]) => readonly unknown[],\n mapper: IndexMapper,\n // Validated against the current length before anything mutates — a bad\n // index (arrayRemove(path, -1)) would otherwise corrupt both the array\n // and the re-keyed error/touched maps.\n indexInBounds?: (length: number) => boolean,\n ): void => {\n const current = getAtPath(store.getState().values, path);\n // null passes like undefined: it is the canonical empty of a NULLABLE\n // array field (emptyValue), and the op item types are built on\n // NonNullable<FieldValue<...>> precisely so nullable/optional arrays\n // accept ops — refusing null made those calls typecheck and then\n // silently no-op at runtime. Both empties start the op from [].\n if (current !== undefined && current !== null && !Array.isArray(current)) {\n console.warn(\n `[formstand] array op on \"${path}\" but the value at that path is not an array (got ${typeof current}). Operation skipped.`,\n );\n return;\n }\n const length = Array.isArray(current) ? current.length : 0;\n if (indexInBounds !== undefined && !indexInBounds(length)) {\n console.warn(\n `[formstand] array op on \"${path}\" with an out-of-range or non-integer index (length ${length}). Operation skipped.`,\n );\n return;\n }\n const arr: readonly unknown[] = Array.isArray(current) ? current : [];\n const next = nextArray(arr);\n const written = setAtPath(store.getState().values, path, next, kindAt);\n // The op rebuilds every ancestor's array (spine copy) and re-seats its\n // rows' descendant arrays under new indices — those paths' records no\n // longer describe the arrays now living there. The op's OWN path keeps\n // its records: earlier same-batch ops still chain.\n clearArrayOpsUnder(store, path, true);\n // Record BEFORE the write, from the exact references the write uses:\n // zustand notifies subscribers synchronously inside setState, so a\n // reentrant same-path write would otherwise interleave the log order\n // AND make a post-setState getState() read pair this op's mapping with\n // a `to` spanning two writes — a corrupt record that can replay to\n // wrong row ids. The mapping is the inverted IndexMapper — the same\n // mapper that re-keys errors/touched below, one source of truth.\n // Guards: an op on an absent slot (push into an undefined array) has no\n // prior reference to chain from, and a write setAtPath REFUSES (huge\n // index, non-plain ancestor) must not log a transition the store never\n // performed — value reconciliation covers both.\n if (Array.isArray(current) && getAtPath(written, path) === next) {\n recordArrayOp(store, path, {\n from: current,\n to: next,\n mapping: invertMapper(mapper, current.length, next.length),\n });\n }\n store.setState((state) => {\n return {\n ...state,\n values: written,\n ...errorChannels(state, {\n schemaErrors: reKeyByArrayPath(state.schemaErrors, path, mapper),\n // Server entries on rows follow their rows through the index\n // mapping — a verdict on \"items.1.name\" is still vouched for after\n // the op moves it to \"items.0.name\" (that row's value didn't\n // change). Entries at the array itself or an ancestor release: the\n // op changed that value.\n serverErrors: releaseAncestorEntries(\n reKeyByArrayPath(state.serverErrors, path, mapper),\n path,\n ),\n }),\n touched: reKeyByArrayPath(state.touched, path, mapper),\n // Drop (don't re-key) in-flight flags under the array: the op changes\n // `values`, so every pass they belong to fails its values-changed\n // guard and never commits — but each pass's cleanup omits its\n // ORIGINAL key, so a re-keyed entry would be orphaned and stick\n // forever. Dropped, the flag is gone now and the cleanup is a\n // harmless no-op.\n isValidating: omitScope(state.isValidating, [path]),\n };\n });\n };\n\n const inFlight: { count: number; baseline: boolean } = {\n count: 0,\n baseline: false,\n };\n\n const submit = async (\n onValid: SubmitHandler<TSchema>,\n onInvalidOrOptions?: InvalidSubmitHandler | SubmitOptions,\n positionalOptions?: SubmitOptions,\n ): Promise<SubmitResult<z.output<TSchema>>> => {\n // Both call shapes normalize here (see the Form type): an object in\n // the second slot is the options bag carrying onInvalid; a function\n // (or an omitted slot, `submit(onValid, undefined, { force })`) is\n // the positional shape, whose options sit in the third.\n const submitOptions =\n typeof onInvalidOrOptions === \"object\"\n ? onInvalidOrOptions\n : positionalOptions;\n const onInvalid =\n typeof onInvalidOrOptions === \"function\"\n ? onInvalidOrOptions\n : submitOptions?.onInvalid;\n if (inFlight.count > 0 && submitOptions?.force !== true) {\n return { kind: \"skipped\" };\n }\n if (inFlight.count === 0) {\n inFlight.baseline = store.getState().isSubmitting;\n }\n inFlight.count += 1;\n store.setState((state) => ({\n ...state,\n isSubmitting: true,\n submitCount: state.submitCount + 1,\n }));\n\n try {\n const pass = claimPass(SUBMIT_SEQ_KEY);\n const valuesAtStart = store.getState().values;\n const result = await validateAsync(schema, valuesAtStart);\n\n // Stale-commit contract (mirrors validateAsyncOnForm's guard): if the\n // values changed while validation was in flight (setValue/reset/\n // adoptValues), the verdict describes a snapshot the form no longer\n // holds — skip every state write (no error commit, no touched marks;\n // that state belongs to the new values). The ownership token catches\n // what the values reference can't: a bare reset() on a pristine form\n // restores the same values reference but clears the token map, and a\n // concurrent submit({ force: true }) re-claims the token — the LAST\n // submit owns the writes. The handlers still run and the result still\n // reports the snapshot's verdict, so callers decide what it means for\n // them.\n const stale =\n sequences.get(SUBMIT_SEQ_KEY) !== pass ||\n store.getState().values !== valuesAtStart;\n\n if (result.kind === \"invalid\") {\n if (!stale) {\n store.setState((state) => {\n const committed = commitFullPass(state, result.errors);\n return {\n ...state,\n ...committed,\n // Mark every errored field touched so touched-gated error UIs\n // show something after the canonical first failed submit. The\n // \"\" key (schema-level refine) has no field to touch.\n touched: {\n ...state.touched,\n ...Object.fromEntries(\n Object.keys(committed.errors)\n .filter((k) => k !== \"\")\n .map((k) => [k, true]),\n ),\n },\n };\n });\n }\n const merged = stale ? result.errors : store.getState().errors;\n try {\n onInvalid?.(merged);\n } catch (error) {\n // Same contract as a throwing onValid below: a failing caller\n // handler resolves as { kind: \"error\" }, never a rejection out of\n // a DOM event handler, and onError observes it the same way (it\n // is the hook for \"a handler of mine failed\", whichever one).\n submitOptions?.onError?.(error);\n return { kind: \"error\", error };\n }\n return { kind: \"invalid\", errors: merged };\n }\n\n if (!stale) {\n store.setState((state) => ({\n ...state,\n ...commitFullPass(state, emptyErrors),\n }));\n }\n try {\n await onValid(result.data);\n } catch (error) {\n // A throwing onValid is the caller's failure, not a validation\n // verdict: resolve with it (so handleSubmit-as-event-handler never\n // leaves an unhandled rejection) and write no error state.\n submitOptions?.onError?.(error);\n return { kind: \"error\", error };\n }\n return { kind: \"valid\", data: result.data };\n } finally {\n inFlight.count -= 1;\n if (inFlight.count === 0) {\n const baseline = inFlight.baseline;\n store.setState((state) => ({ ...state, isSubmitting: baseline }));\n }\n }\n };\n\n // The validateOnMount pass, run at creation and again whenever the form\n // takes a NEW BASELINE (reset(), adoptValues()). The option exists so a\n // validity gate reflects the values the form holds; a rebase replaces\n // those values and clears the errors the creation pass wrote, so a\n // persisted draft adopted over the initial values used to open a\n // useIsValid gate for an invalid draft. Async schemas route themselves:\n // validate() returns a \"pending\" result whose background pass writes the\n // error map when it settles. Nobody awaits that promise, so a rejecting\n // pass is reported here instead of surfacing as an unhandled rejection\n // with no pointer to the form.\n const judgeBaseline = (): void => {\n if (options.validateOnMount !== true) return;\n const result = validate();\n if (result.kind === \"pending\") {\n void result.promise.catch(reportBackgroundFailure);\n }\n };\n judgeBaseline();\n\n return Object.freeze({\n schema,\n store,\n getState: store.getState,\n subscribe: store.subscribe,\n getField: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n getAtPath(store.getState().values, path) as FieldValue<\n z.input<TSchema>,\n P\n >,\n getFieldState: <P extends FieldPath<z.input<TSchema>, D>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n previous: FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n ) => void,\n ) => {\n const ref: { current: FieldSnapshot<unknown> } = {\n current: snapshotField(store.getState(), path),\n };\n return store.subscribe((state) => {\n const next = snapshotField(state, path);\n if (!shallowFieldEqual(ref.current, next)) {\n const prev = ref.current;\n ref.current = next;\n listener(\n next as FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n prev as FieldSnapshot<FieldValue<z.input<TSchema>, P>>,\n );\n }\n });\n },\n watchValue: <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n listener: (\n value: FieldValue<z.input<TSchema>, P>,\n previous: FieldValue<z.input<TSchema>, P>,\n ) => void,\n ) => {\n const ref: { current: unknown } = {\n current: getAtPath(store.getState().values, path),\n };\n return store.subscribe((state) => {\n const next = getAtPath(state.values, path);\n if (!Object.is(ref.current, next)) {\n const prev = ref.current;\n ref.current = next;\n listener(\n next as FieldValue<z.input<TSchema>, P>,\n prev as FieldValue<z.input<TSchema>, P>,\n );\n }\n });\n },\n watchValues: (listener) => {\n const ref: { current: Values } = { current: store.getState().values };\n return store.subscribe((state) => {\n if (state.values !== ref.current) {\n const prev = ref.current;\n ref.current = state.values;\n listener(state.values, prev);\n }\n });\n },\n setValue: (path: string, value: unknown) => {\n // Identity guard: writing the value already at the path is a FULL\n // no-op — same state reference, no values rebuild, no dirty/error\n // recompute, no subscriber notifications. Without it, every no-op\n // write rebuilt the values spine, so useFormValues re-rendered and\n // watchValues/onValuesChange fired on nothing — and a two-way sync\n // that echoes values back (form A watches form B and vice versa)\n // recursed until the stack overflowed. Object.is matches the\n // library's other change detectors (watchValue, useStore); note it\n // also skips the server-error release and op-log clearing below —\n // deliberately, since no value changed. One carve-out: an\n // `undefined` write only no-ops when the slot actually EXISTS —\n // writing undefined over an absent key CREATES the key (a real\n // change: key-count dirtiness, the persisted shape), so it must\n // still go through. A non-undefined Object.is match implies the own\n // slot exists (reads are own-key only), so the walk runs for\n // undefined writes alone.\n const currentValues = store.getState().values;\n if (\n Object.is(getAtPath(currentValues, path), value) &&\n (value !== undefined || hasOwnSlot(currentValues, path))\n ) {\n return;\n }\n // A write the path walker REFUSES (a string key into an array, a key\n // through a Date) hands the same values back; treat it as the no-op\n // its warning announces, like the identity guard above.\n const next = setAtPath(currentValues, path, value, kindAt);\n if (next === currentValues) return;\n // A value write outside the array ops breaks every op chain whose\n // array it could rebuild — drop those records at the source so a\n // stale (or recurring, e.g. reset-restored) array reference can never\n // falsely chain against them.\n clearArrayOpsUnder(store, path);\n store.setState((state) => ({\n ...state,\n values: next,\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n }));\n },\n setValues: (next) => {\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values: next,\n ...errorChannels(state, {\n serverErrors: releaseChangedSlices(\n state.serverErrors,\n state.values,\n next,\n ),\n }),\n }));\n },\n setTouched: (path: string, touched: boolean = true) =>\n store.setState((state) => ({\n ...state,\n touched: { ...state.touched, [path]: touched },\n })),\n setSubmitting: (value) =>\n store.setState((state) => ({ ...state, isSubmitting: value })),\n setMode: (mode) => store.setState((state) => ({ ...state, mode })),\n setReValidateMode: (reValidateMode) =>\n store.setState((state) => ({ ...state, reValidateMode })),\n setError: (path: string, errors: string | readonly string[]) => {\n const list = typeof errors === \"string\" ? [errors] : errors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n serverErrors:\n list.length === 0\n ? omitKey(state.serverErrors, path)\n : { ...state.serverErrors, [path]: list },\n }),\n }));\n },\n setErrors: (errors) =>\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, { serverErrors: dropEmptyLists(errors) }),\n })),\n addErrors: (errors) =>\n store.setState((state) => {\n // Two passes over the incoming map, not a per-entry fold: the old\n // reduce spread (or omitKey-rebuilt) the whole channel once per\n // entry, quadratic in the number of server fields. Object.fromEntries\n // and the spread define computed keys as own properties, so a\n // server field named \"__proto__\" still lands like everywhere else.\n const entries = Object.entries(errors);\n const removed = new Set(\n entries\n .filter(([, list]) => list === undefined || list.length === 0)\n .map(([key]) => key),\n );\n const added = Object.fromEntries(\n entries.filter(([, list]) => list !== undefined && list.length > 0),\n );\n return {\n ...state,\n ...errorChannels(state, {\n serverErrors: {\n ...omitKeys(state.serverErrors, removed),\n ...added,\n },\n }),\n };\n }),\n clearErrors: (path?: string) =>\n store.setState((state) => {\n // Clears both channels (schema errors return on the next validation\n // pass). A field path also clears its descendants (\"items\" covers\n // \"items.0.name\"), consistent with field-scoped validation; the root\n // \"\" is a single key (the schema-level refine slot, symmetric with\n // setError(\"\")); clearing everything is clearErrors() with no\n // argument.\n const scrub = (map: ErrorMap): ErrorMap =>\n path === undefined ? emptyErrors : omitScope(map, [path]);\n return {\n ...state,\n ...errorChannels(state, {\n schemaErrors: scrub(state.schemaErrors),\n serverErrors: scrub(state.serverErrors),\n }),\n };\n }),\n updateState: (updater) => {\n // The updater runs against the current state OUTSIDE setState so the\n // op-log decision below can precede the notification: subscribers\n // derive array row ids synchronously inside setState, and a values\n // patch that reintroduces an earlier array reference (a snapshot of\n // values taken before an op) would otherwise chain the op's stale\n // record against it during that notification, then have the log\n // cleared too late to matter. Same ordering setValues/adoptValues\n // keep. Semantically identical to setState(updater): both read the\n // same synchronous state.\n const state = store.getState();\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return;\n // Spread-style updaters carry `errors` with its current reference —\n // only a genuinely foreign map (a plain-JS write; TS forbids it via\n // the patch type) earns the warning.\n if (patch.errors !== undefined && patch.errors !== state.errors) {\n console.warn(\n \"[formstand] `errors` is derived from schemaErrors/serverErrors — patch those channels instead; the direct `errors` patch is ignored.\",\n );\n }\n // Re-derive against the CURRENT merged map (not the patched one), so\n // an ignored `errors` patch can't leak even its object identity into\n // state and re-fire identity-based subscribers.\n const next = { ...state, ...patch };\n // A values patch is a chain-breaking write like setValues.\n if (next.values !== state.values) {\n clearArrayOpsUnder(store, \"\");\n }\n // A values patch is also a bulk write under the documented release\n // contract (FormState.serverErrors: an entry releases when the value\n // on its spine changes), so it releases exactly what setValues\n // releases: the entries whose slice actually changed. An explicit\n // serverErrors patch in the same call wins as given, which is what\n // setValues followed by setErrors would leave behind: the caller is\n // stating the channel for the new values.\n const serverErrors =\n patch.serverErrors !== undefined\n ? dropEmptyLists(patch.serverErrors)\n : next.values !== state.values\n ? releaseChangedSlices(state.serverErrors, state.values, next.values)\n : state.serverErrors;\n store.setState(() => ({\n ...next,\n ...errorChannels(state, {\n schemaErrors:\n patch.schemaErrors === undefined\n ? state.schemaErrors\n : dropEmptyLists(patch.schemaErrors),\n serverErrors,\n }),\n }));\n },\n adoptValues: (values) => {\n // Rebasing values invalidates any in-flight async validation (the\n // values-reference guard drops its write), so the per-path ownership\n // tokens can be released too rather than growing without bound.\n sequences.clear();\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => ({\n ...state,\n values,\n initialValues: values,\n ...errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n }),\n // Clearing `sequences` disowns every in-flight pass, including its\n // flag cleanup (the ownership check fails, so it never writes) —\n // clear the flags here too, mirroring reset(), or they'd stick.\n isValidating: emptyBools,\n isValidatingForm: false,\n }));\n judgeBaseline();\n },\n reset: (nextInitial, resetOptions) => {\n sequences.clear();\n // reset can restore the exact initialValues REFERENCE, so stale\n // records must go before an old array reference recurs and falsely\n // chains against them.\n clearArrayOpsUnder(store, \"\");\n store.setState((state) => {\n // Merge only when both sides are plain records; a partial for an\n // array/scalar-rooted schema replaces wholesale (spreading an array\n // into {...} would corrupt the values shape).\n const init: typeof state.initialValues =\n nextInitial === undefined\n ? state.initialValues\n : isPlainObject(state.initialValues) && isPlainObject(nextInitial)\n ? ({\n ...state.initialValues,\n ...nextInitial,\n } as typeof state.initialValues)\n : (nextInitial as typeof state.initialValues);\n return {\n ...state,\n values: init,\n initialValues: init,\n ...(resetOptions?.keepErrors === true\n ? {}\n : errorChannels(state, {\n schemaErrors: emptyErrors,\n serverErrors: emptyErrors,\n })),\n touched:\n resetOptions?.keepTouched === true ? state.touched : emptyBools,\n isSubmitting: false,\n submitCount:\n resetOptions?.keepSubmitCount === true ? state.submitCount : 0,\n isValidating: emptyBools,\n isValidatingForm: false,\n };\n });\n // keepErrors asks for the error map as it was; the baseline pass\n // would overwrite it with the initial values' verdict.\n if (resetOptions?.keepErrors !== true) judgeBaseline();\n },\n resetField: (path: string) => {\n // slotAtPath, not getAtPath: a path addressing NO slot in\n // initialValues (an out-of-range array index — an appended row past\n // the initial length, or a path through an absent ancestor) must not\n // be \"reset\" by writing undefined into the values tree — that would\n // leave a mid-array hole ([rowA, undefined]) that crashes row renders\n // and fails the schema. The value stays as-is; the field state still\n // clears. A key merely absent on an initial plain record IS an\n // addressable slot: resetting it writes the legitimate empty\n // undefined, exactly as before.\n const initialSlot = slotAtPath(\n store.getState().initialValues,\n path,\n );\n if (!initialSlot.exists) {\n console.warn(\n `[formstand] resetField(\"${path}\"): path has no initial value (e.g. an appended array row); value left unchanged, field state cleared.`,\n );\n }\n if (initialSlot.exists) {\n // A restored initial slice can carry array references the op log\n // has already seen (chain-breaking write, like setValue).\n clearArrayOpsUnder(store, path);\n }\n store.setState((state) => ({\n ...state,\n values: initialSlot.exists\n ? setAtPath(state.values, path, initialSlot.value, kindAt)\n : state.values,\n // A runtime \"\" path scopes the whole form (the imperative surface is\n // string-typed even though FieldPath excludes \"\"). Server entries\n // follow the setValue release contract (releaseSpine).\n ...errorChannels(state, {\n schemaErrors:\n path === \"\" ? emptyErrors : omitScope(state.schemaErrors, [path]),\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n touched:\n path === \"\" ? emptyBools : omitScope(state.touched, [path]),\n isValidating:\n path === \"\" ? emptyBools : omitScope(state.isValidating, [path]),\n }));\n },\n validate,\n validateField,\n validateFields,\n validateAsync: validateAsyncOnForm,\n validateFieldAsync,\n validateFieldsAsync,\n submit,\n arrayPush: (path: string, item: unknown) =>\n applyArrayOp(path, (arr) => [...arr, item], identityMapper),\n arrayRemove: (path: string, index: number) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), ...arr.slice(index + 1)],\n removeAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index < len,\n ),\n arrayInsert: (path: string, index: number, item: unknown) =>\n applyArrayOp(\n path,\n (arr) => [...arr.slice(0, index), item, ...arr.slice(index)],\n insertAt(index),\n (len) => Number.isInteger(index) && index >= 0 && index <= len,\n ),\n arrayMove: (path: string, from: number, to: number) =>\n applyArrayOp(\n path,\n (arr) => {\n const without = [...arr.slice(0, from), ...arr.slice(from + 1)];\n return [...without.slice(0, to), arr[from], ...without.slice(to)];\n },\n moveFromTo(from, to),\n (len) =>\n Number.isInteger(from) &&\n Number.isInteger(to) &&\n from >= 0 &&\n from < len &&\n to >= 0 &&\n to < len,\n ),\n arraySwap: (path: string, a: number, b: number) =>\n applyArrayOp(\n path,\n (arr) => arr.map((v, i) => (i === a ? arr[b] : i === b ? arr[a] : v)),\n swapIndices(a, b),\n (len) =>\n Number.isInteger(a) &&\n Number.isInteger(b) &&\n a >= 0 &&\n a < len &&\n b >= 0 &&\n b < len,\n ),\n handleSubmit:\n (\n onValid: SubmitHandler<TSchema>,\n onInvalidOrOptions?: InvalidSubmitHandler | SubmitOptions,\n positionalOptions?: SubmitOptions,\n ) =>\n async (event?: { preventDefault: () => void }) => {\n event?.preventDefault();\n const opts =\n typeof onInvalidOrOptions === \"object\"\n ? onInvalidOrOptions\n : positionalOptions;\n const result = await submit(\n onValid,\n onInvalidOrOptions,\n positionalOptions,\n );\n // The event-handler form is fire-and-forget: nobody reads the\n // resolved result, so a save failure with no onError handler\n // would otherwise vanish COMPLETELY — no state, no rejection, no\n // log — and the button just re-enables. Dev builds say so once\n // per occurrence; production stays silent by design (resolving\n // instead of rejecting is the documented contract).\n if (\n result.kind === \"error\" &&\n opts?.onError === undefined &&\n isDevBuild()\n ) {\n console.warn(\n \"[formstand] submit handler threw and nothing observed it — the form shows no feedback. Pass { onError } to handleSubmit (or setError inside your handler):\",\n result.error,\n );\n }\n return result;\n },\n diff: () => {\n const state = store.getState();\n return Object.fromEntries(\n dirtyPathsOf(state.values, state.initialValues, \"\").map((path) => [\n path,\n getAtPath(state.values, path),\n ]),\n );\n },\n dirtyFields: () => {\n const state = store.getState();\n return dirtyPathsOf(state.values, state.initialValues, \"\");\n },\n snapshot: () => store.getState(),\n restore: (snap) => {\n // A snapshot is a whole state put back, so a pass that started before\n // it judged values the snapshot may not hold. The full-pass guard\n // (values reference) already drops such a write, but a subschema\n // pass compares only its own slot and could still commit a verdict\n // the snapshot never had. Disown every in-flight pass, as reset() and\n // adoptValues() do; the flags are cleared below either way.\n sequences.clear();\n // A snapshot restores PRIOR array references — exactly the recurring\n // references stale op records could falsely chain against.\n clearArrayOpsUnder(store, \"\");\n store.setState(() => {\n // Snapshots can come from persistence or hand construction: default\n // missing channels (pre-channel shapes) and re-derive the merged map\n // so the errors-is-derived invariant holds at this boundary too —\n // otherwise an inconsistent snapshot renders phantom errors until\n // the next write silently rewrites them (or crashes a channel scan).\n const schemaErrors = dropEmptyLists(snap.schemaErrors ?? emptyErrors);\n const serverErrors = dropEmptyLists(snap.serverErrors ?? emptyErrors);\n return {\n ...snap,\n schemaErrors,\n serverErrors,\n errors: reuseErrorRefs(\n mergeErrorChannels(schemaErrors, serverErrors),\n snap.errors ?? emptyErrors,\n ),\n // In-flight state is owned by live passes, never by snapshots: a\n // snapshotted flag has no pass left to clear it (the pass that set\n // it cleared its ORIGINAL entry when it settled), so restoring one\n // would stick it forever. isSubmitting follows the same rule — a\n // mid-submit snapshot restored later must not disable submit\n // buttons forever, so it reflects the LIVE submit count instead of\n // the snapshotted flag (a live pass's finally still resets it).\n isValidating: emptyBools,\n isValidatingForm: false,\n isSubmitting: inFlight.count > 0,\n };\n });\n },\n }) as Form<TSchema, D>;\n};\n","export type ValidationMode =\n | \"onChange\"\n | \"onBlur\"\n | \"onSubmit\"\n // Validate on blur always; on change only once the field has been touched.\n | \"onTouched\"\n // Validate on both change and blur.\n | \"all\";\n\nexport type ValidationTrigger = \"change\" | \"blur\";\n\nexport const shouldValidateOn = (\n trigger: ValidationTrigger,\n mode: ValidationMode,\n reValidateMode: ValidationMode,\n submitAttempted: boolean,\n touched: boolean = false,\n): boolean => {\n const effective = submitAttempted ? reValidateMode : mode;\n switch (effective) {\n case \"onChange\":\n return trigger === \"change\";\n case \"onBlur\":\n return trigger === \"blur\";\n case \"onSubmit\":\n return false;\n case \"onTouched\":\n return trigger === \"blur\" || touched;\n case \"all\":\n return true;\n }\n};\n","// A trailing-edge debouncer: `schedule` replaces any pending call, `cancel`\n// drops it. One production for the two timers the library keeps (the\n// persistence draft writer and useField's async-validation debounce), so\n// the cancel-then-reschedule rule lives in one place. Deliberately NOT a\n// `debounce(fn)` wrapper: both callers close over per-call data (the values\n// to write, the value that scheduled a validation) and decide at fire time,\n// so the scheduled thunk is the unit, not a fixed function.\nexport type Debouncer = Readonly<{\n schedule: (run: () => void) => void;\n cancel: () => void;\n // Run the pending thunk NOW instead of waiting out the delay (a no-op\n // when nothing is pending): persistForm's dispose and flush, where the\n // moment cannot wait.\n flush: () => void;\n // True while a scheduled run has not fired or been cancelled.\n readonly pending: () => boolean;\n}>;\n\n// A delay of 0 runs synchronously — the callers treat 0 as \"no debounce\"\n// and the caller-visible ordering (write happens before schedule returns)\n// is part of their contract.\nexport const createDebouncer = (ms: number): Debouncer => {\n // Sanctioned mutable ref for the timer handle (same shape as the\n // codebase's other timer/subscription refs).\n const timer: { current: ReturnType<typeof setTimeout> | null } = {\n current: null,\n };\n // The thunk the timer will run, kept so flush can run it early.\n const scheduled: { current: (() => void) | null } = { current: null };\n const cancel = (): void => {\n if (timer.current !== null) {\n clearTimeout(timer.current);\n timer.current = null;\n }\n scheduled.current = null;\n };\n const schedule = (run: () => void): void => {\n cancel();\n if (ms === 0) {\n run();\n return;\n }\n scheduled.current = run;\n timer.current = setTimeout(() => {\n timer.current = null;\n scheduled.current = null;\n run();\n }, ms);\n };\n const flush = (): void => {\n const run = scheduled.current;\n if (run === null) return;\n cancel();\n run();\n };\n return Object.freeze({\n schedule,\n cancel,\n flush,\n pending: () => timer.current !== null,\n });\n};\n","import type { z } from \"zod\";\nimport type { Form } from \"./createForm\";\nimport { createDebouncer } from \"./debounce\";\nimport { isDevBuild } from \"./env\";\nimport { isPlainObject } from \"./equality\";\nimport type { DefaultPathDepth, PathDepth } from \"./fieldPath\";\nimport {\n fieldSchemaForIntrospection,\n isObjectSchemaAt,\n schemaAcceptsUndefined,\n schemaAllowsKindChangeAt,\n} from \"./validation\";\n\n// Draft persistence for a form: watch the values, debounce-write them as JSON\n// under a storage key, and re-apply a found draft on the next visit. This is\n// the autosave recipe (examples/AutosaveForm) promoted to a helper — same\n// caveat as the recipe: drafts round-trip through JSON, so they are for\n// JSON-safe values only (Dates become strings, undefined slots drop; the\n// helper does NOT try to revive them).\n\n// Structural storage contract — window.localStorage and sessionStorage\n// satisfy it, as does any Map-backed stub in tests.\nexport type PersistStorage = Readonly<{\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n}>;\n\n// TSchema is phantom for now (no option carries schema-typed data — drafts\n// are typed at the persistForm call, not here), but the parameter keeps the\n// option bag tied to the form it configures and leaves room for schema-typed\n// options later without a breaking signature change.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type PersistOptions<TSchema extends z.ZodType> = Readonly<{\n // Storage key the draft lives under.\n key: string;\n // Defaults to globalThis.localStorage, guarded: where it is absent or\n // throws on access (SSR, locked-down browsers), persistence is a no-op but\n // the helper still returns working handles.\n storage?: PersistStorage;\n // Trailing-edge debounce for writes. Default 300; 0 writes synchronously\n // on every change.\n debounceMs?: number;\n // Bump when the schema's SHAPE changes and old drafts should be discarded\n // rather than applied. A draft is stored with the version it was written\n // under and ignored when the two disagree, which is the only reliable way\n // to catch a renamed or removed field: an absent key is indistinguishable\n // from an optional the user never filled in, so the automatic guard below\n // cannot tell those apart. Leaving this unset keeps the stored format\n // exactly as it was, so existing drafts survive an upgrade.\n version?: string | number;\n // How a found draft is applied on start, and what load() does later.\n // \"adopt\" (default) uses form.adoptValues: the draft becomes the new\n // baseline, so the form reads CLEAN. \"edit\" uses form.setValues: the\n // draft loads but stays DIRTY against the original initial values.\n // \"manual\" never auto-applies; the caller decides when via the returned\n // load(), which then applies with adopt semantics (a caller-triggered\n // load is a rebase, not an edit; pick \"edit\" for dirty-vs-initials).\n // \"restore\" is the pre-0.22 spelling of \"edit\", kept as an alias: it\n // collided with form.restore(snapshot), which puts back a whole\n // FormState, and with load() (which used to be called restore), three\n // restore-ish words for three behaviors.\n apply?: \"adopt\" | \"edit\" | \"restore\" | \"manual\";\n}>;\n\nexport type PersistHandle = Readonly<{\n // Load + apply the stored draft now (see `apply` for the semantics):\n // returns true if a draft existed, parsed, and applied. Corrupt or absent\n // JSON returns false and never throws; a dev build also logs WHY a draft\n // that was present got ignored. (Named load, not restore: the DEFAULT\n // application is adoptValues — a rebase that reads clean — and \"restore\"\n // promised setValues semantics the method only has when the apply option\n // asks for them.)\n load: () => boolean;\n // Write the pending debounced draft now (a no-op when nothing is\n // pending): for the moments that cannot wait out the debounce, a route\n // change or a pagehide handler.\n flush: () => void;\n // Delete the stored draft (e.g. after a successful submit). Also cancels\n // any pending debounced write, so a stale draft isn't re-written right\n // after clearing, and a rebase that follows (reset(), adoptValues()) does\n // not re-create it either; the next real edit does.\n clear: () => void;\n // Stop watching the form (does not clear storage). Writes any pending\n // debounced draft first: unmounting inside the debounce window used to\n // cancel it, which lost the last edits an autosave exists to keep.\n dispose: () => void;\n}>;\n\n// The JSON kind of a value, as it exists AFTER a storage round trip. The\n// reference side is round-tripped before comparison rather than special-cased,\n// so a Date (which stores as a string) compares against a string and the\n// documented Date-becomes-string limitation is not mistaken for corruption.\nconst kindOf = (value: unknown): string =>\n value === null\n ? \"null\"\n : Array.isArray(value)\n ? \"array\"\n : typeof value;\n\nconst joinPath = (base: string, key: string | number): string =>\n base === \"\" ? String(key) : `${base}.${String(key)}`;\n\n// The first path where the draft CONFLICTS with the shape the form expects,\n// or null when the two agree everywhere they overlap. Only overlapping paths\n// are compared, and only their kinds.\n//\n// Deliberately not a key-set equality check. JSON drops undefined slots, so an\n// optional the user never filled is absent from the reference, and an optional\n// they did fill is present only in the draft. Neither is evidence of a schema\n// change, so treating a key-set difference as corruption would throw away\n// perfectly good drafts on any form with an optional field. What IS\n// unambiguous is a path holding a string on one side and an object on the\n// other: no edit produces that, only a changed schema. Renames and removals\n// are the `version` option's job.\n//\n// `flexibleAt` is the schema's word on a kind mismatch: a coerced number\n// behind a \"\" initial, a pipe, or a union whose variants shape the key\n// differently all make the mismatch legitimate (see schemaAllowsKindChangeAt),\n// and the guard used to refuse exactly those drafts with no reason given.\nconst conflictPath = (\n draft: unknown,\n reference: unknown,\n path: string,\n flexibleAt: (path: string) => boolean,\n): string | null => {\n // null and undefined carry NO shape information, on either side. null is the\n // canonical empty for a nullable field (see emptyValue), so it can legally\n // appear at any nullable path whatever that path's filled shape is: a\n // nullable object starting null and then filled in, or starting filled and\n // then cleared, are both ordinary edits. Reading either as a kind conflict\n // would discard the drafts of every form with a nullable field.\n if (draft === undefined || draft === null) return null;\n if (reference === undefined || reference === null) return null;\n const draftKind = kindOf(draft);\n const referenceKind = kindOf(reference);\n if (draftKind !== referenceKind) return flexibleAt(path) ? null : path;\n if (draftKind === \"array\") {\n const [d] = draft as readonly unknown[];\n const [r] = reference as readonly unknown[];\n // Row counts differ for ordinary reasons; the ROW SHAPE is the signal.\n return conflictPath(d, r, joinPath(path, 0), flexibleAt);\n }\n if (draftKind === \"object\") {\n const d = draft as Record<string, unknown>;\n const r = reference as Record<string, unknown>;\n return Object.keys(d).reduce<string | null>(\n (found, key) =>\n found ?? conflictPath(d[key], r[key], joinPath(path, key), flexibleAt),\n null,\n );\n }\n return null;\n};\n\n// Resolved lazily inside persistForm — never at module scope — so importing\n// this module is SSR-safe. jsdom provides localStorage; node without DOM may\n// lack it (typeof check) or throw on access (try/catch).\nconst defaultStorage = (): PersistStorage | null => {\n try {\n return typeof globalThis.localStorage === \"undefined\"\n ? null\n : globalThis.localStorage;\n } catch {\n return null;\n }\n};\n\n// What load() found. The boolean the handle returns is \"applied\"; the\n// reason an existing draft was ignored is for the dev-build warning, since\n// a silent false left no way to tell a version mismatch from a shape\n// conflict from an empty storage slot.\ntype LoadOutcome =\n | Readonly<{ kind: \"applied\" }>\n | Readonly<{ kind: \"absent\" }>\n | Readonly<{ kind: \"ignored\"; reason: string }>;\n\nexport const persistForm = <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const storage = options.storage ?? defaultStorage();\n const debounceMs = options.debounceMs ?? 300;\n const apply = options.apply ?? \"adopt\";\n const schema: z.ZodType = form.schema;\n\n // A draft stored before the schema GAINED a key lacks that key, and\n // applying it wholesale erased the key's initial value from values AND\n // initialValues (reset() could not bring it back, and the user met zod's\n // generic message instead of the author's). Fill the gap from the initial\n // values, but only where the schema does NOT accept undefined there: an\n // optional key absent from the draft may have been cleared on purpose\n // (JSON drops undefined), and filling it would undo that edit, while a\n // nullable-but-required key cannot hold the hole at all. Objects recurse\n // so a nested gain is covered, but only while the schema says the\n // container IS a plain object: under a union the draft's keys belong to\n // whichever variant it holds (walking the initial values' variant spliced\n // its key into another variant), and a record key the draft lacks was\n // removed on purpose. Arrays are left alone (row counts differ for\n // ordinary reasons). A key the schema walk cannot place is filled too:\n // the initial value is the author's default, the safer guess.\n const fillRequiredGaps = (\n draft: unknown,\n initial: unknown,\n path: string,\n ): unknown => {\n if (!isPlainObject(draft) || !isPlainObject(initial)) return draft;\n if (!isObjectSchemaAt(schema, path)) return draft;\n return Object.keys(initial).reduce<Record<string, unknown>>(\n (acc, key) => {\n const childPath = joinPath(path, key);\n if (Object.hasOwn(draft, key)) {\n const next = fillRequiredGaps(draft[key], initial[key], childPath);\n return Object.is(next, draft[key]) ? acc : { ...acc, [key]: next };\n }\n if (initial[key] === undefined) return acc;\n const sub = fieldSchemaForIntrospection(schema, childPath);\n return sub !== null && schemaAcceptsUndefined(sub)\n ? acc\n : { ...acc, [key]: initial[key] };\n },\n draft,\n );\n };\n\n // Armed while a draft is being written into the form. The values watcher\n // below fires synchronously inside the write, so a manual load() used to\n // schedule a write of the very draft it had just read. (The auto-apply at\n // construction runs before the watcher exists; only a later load() meets\n // it.) A sanctioned mutable ref, like `cleared` below.\n const applying = { current: false };\n\n // \"edit\" (and its alias \"restore\") is a plain values write (dirty vs the\n // original initials); \"adopt\" and \"manual\" rebase via adoptValues so the\n // draft reads clean.\n const applyDraft = (values: z.input<TSchema>): void => {\n const filled = fillRequiredGaps(\n values,\n form.getState().initialValues,\n \"\",\n ) as z.input<TSchema>;\n applying.current = true;\n try {\n if (apply === \"edit\" || apply === \"restore\") {\n form.setValues(filled);\n } else {\n form.adoptValues(filled);\n }\n } finally {\n applying.current = false;\n }\n };\n\n // Is the draft already what the form holds, compared in stored form (the\n // keys a previous apply filled were written back, so they read equal)?\n // A non-serializable values tree cannot be compared and counts as new.\n const isCurrent = (values: unknown): boolean => {\n try {\n return (\n JSON.stringify(values) === JSON.stringify(form.getState().values)\n );\n } catch {\n return false;\n }\n };\n\n // The shape the draft is checked against, in stored form. Round-tripping\n // the reference through JSON puts both sides in the same representation.\n const referenceShape = (): unknown => {\n try {\n return JSON.parse(JSON.stringify(form.getState().initialValues));\n } catch {\n // A non-serializable initial value means we cannot compare; the write\n // path would have failed too, so let the draft through unchecked\n // rather than rejecting every draft for this form.\n return undefined;\n }\n };\n\n const flexibleAt = (path: string): boolean =>\n schemaAllowsKindChangeAt(schema, path);\n\n const inspect = (skipWhenCurrent: boolean): LoadOutcome => {\n // Every storage touch is guarded: private-mode/security errors read as\n // \"no draft\", corrupt JSON as an ignored one — load never throws.\n const raw = ((): string | null => {\n try {\n return storage === null ? null : storage.getItem(options.key);\n } catch {\n return null;\n }\n })();\n if (raw === null) return { kind: \"absent\" };\n try {\n const parsed: unknown = JSON.parse(raw);\n // Versioned drafts are wrapped; unversioned ones are the bare values,\n // which is the format every existing draft is already in.\n const versioned =\n options.version !== undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"__v\" in parsed;\n if (options.version !== undefined && !versioned) {\n return {\n kind: \"ignored\",\n reason: `it carries no version and this configuration expects version ${String(options.version)}`,\n };\n }\n // The config-downgrade hole: a draft WRITTEN with a version is the\n // {__v, values} wrapper, and if the app later ships without the\n // version option, nothing above catches it — the wrapper's keys\n // don't overlap the reference shape, so the shape guard stays quiet\n // and the WRAPPER OBJECT gets adopted as form values (then\n // re-persisted, making the corruption self-sustaining). A versioned\n // draft under a version-less config is a contract the current app\n // no longer declares: discard it, like every other draft the config\n // cannot vouch for.\n if (\n options.version === undefined &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n Object.hasOwn(parsed, \"__v\") &&\n Object.hasOwn(parsed, \"values\")\n ) {\n return {\n kind: \"ignored\",\n reason: \"it was written with a version and this configuration has none\",\n };\n }\n const wrapper = parsed as unknown as {\n readonly __v?: unknown;\n readonly values?: unknown;\n };\n if (versioned && wrapper.__v !== options.version) {\n return {\n kind: \"ignored\",\n reason: `its version (${String(wrapper.__v)}) is not the configured version (${String(options.version)})`,\n };\n }\n // A wrapper with no payload is not a draft. Only reachable via tampered\n // or foreign storage, but applying it would write undefined over the\n // whole values object.\n if (versioned && wrapper.values === undefined) {\n return { kind: \"ignored\", reason: \"its version wrapper holds no values\" };\n }\n const values = (versioned ? wrapper.values : parsed) as z.input<TSchema>;\n // A null or missing TOP-LEVEL payload is not a draft either (an\n // unversioned \"null\" in storage, or a versioned wrapper holding\n // values: null). The shape guard deliberately treats null as shapeless\n // because nested nullable fields legally hold it, so the top level is\n // the one place to refuse it: adoptValues(null) would make every path\n // read on the form crash and then re-persist the same null.\n if (values === null || values === undefined) {\n return { kind: \"ignored\", reason: \"it holds no values\" };\n }\n // A draft whose shape conflicts with the form's is from another schema.\n // Applying it would rebase the form onto values it cannot validate, and\n // because \"adopt\" clears errors, the form would read CLEAN while holding\n // them. Ignore it instead; the next change overwrites it.\n const reference = referenceShape();\n const conflict =\n reference === undefined\n ? null\n : conflictPath(values, reference, \"\", flexibleAt);\n if (conflict !== null) {\n return {\n kind: \"ignored\",\n reason: `its shape conflicts with the form's initial values at \"${conflict}\" (set the version option when the schema changes)`,\n };\n }\n // The auto-apply skips a draft the form already holds: a resubscribe\n // (usePersistForm after dispose() flushed the values), StrictMode's\n // second mount, or initial values equal to the draft. Applying again\n // would only rebase, clearing errors and dirty state, and with an\n // inline storage object every render resubscribed, every resubscribe\n // re-adopted and every adopt re-rendered. A caller's load() applies\n // regardless: that call asks for the rebase.\n if (skipWhenCurrent && isCurrent(values)) return { kind: \"applied\" };\n applyDraft(values);\n return { kind: \"applied\" };\n } catch {\n return { kind: \"ignored\", reason: \"it is not valid JSON\" };\n }\n };\n\n const loadWith = (skipWhenCurrent: boolean): boolean => {\n const outcome = inspect(skipWhenCurrent);\n if (outcome.kind === \"ignored\" && isDevBuild()) {\n console.warn(\n `[formstand] persistForm: ignored the draft under \"${options.key}\": ${outcome.reason}. The next edit overwrites it.`,\n );\n }\n return outcome.kind === \"applied\";\n };\n const load = (): boolean => loadWith(false);\n\n const writeDraft = (values: z.input<TSchema>): void => {\n // Quota/private-mode setItem errors just skip this write. The wrapper is\n // written ONLY when a version is configured, so a form that never opts in\n // keeps the exact bytes it wrote before and its existing drafts still load.\n try {\n storage?.setItem(\n options.key,\n JSON.stringify(\n options.version === undefined\n ? values\n : { __v: options.version, values },\n ),\n );\n } catch {\n /* persistence is best-effort */\n }\n };\n\n // Trailing-edge debounce of draft writes (0 = write synchronously).\n const writes = createDebouncer(debounceMs);\n\n // Auto-apply BEFORE subscribing, so applying the draft doesn't immediately\n // schedule a write of the values we just read.\n if (apply !== \"manual\") {\n loadWith(true);\n }\n\n // Armed by clear(): the usual after-submit pair is clear() then reset(),\n // and the reset's values change used to write the fresh baseline straight\n // back as a draft, which the next visit then adopted over whatever initial\n // values the app had meanwhile computed. A rebase leaves values ===\n // initialValues (reset, adoptValues, a pristine restore); while armed,\n // such a write is skipped. Any real edit disarms it. A sanctioned mutable\n // ref, like the timer handle inside the debouncer.\n const cleared = { current: false };\n\n const unsubscribe = form.watchValues((values) => {\n if (applying.current) return;\n if (cleared.current && values === form.getState().initialValues) return;\n cleared.current = false;\n writes.schedule(() => writeDraft(values));\n });\n\n return Object.freeze({\n load,\n flush: () => writes.flush(),\n clear: () => {\n // Cancel first: a pending debounced write landing after removeItem\n // would silently resurrect the draft.\n writes.cancel();\n cleared.current = true;\n try {\n storage?.removeItem(options.key);\n } catch {\n /* persistence is best-effort */\n }\n },\n dispose: () => {\n writes.flush();\n unsubscribe();\n },\n });\n};\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport {\n type PersistHandle,\n type PersistOptions,\n type PersistStorage,\n persistForm,\n} from \"../core/persist\";\n\n// The React lifecycle wrapper persistForm was missing: every useForm\n// consumer hand-wrote the mount/dispose effect (plus a ref to reach\n// clear() after submit), and calling persistForm during render\n// double-subscribed under StrictMode. This hook owns that dance:\n//\n// const form = useForm(schema, { initialValues });\n// const draft = usePersistForm(form, { key: \"profile-draft\" });\n// // ... later: draft.clear() after a successful submit.\n//\n// The returned handle is REFERENCE-STABLE across renders and delegates to\n// whichever inner subscription is currently live, so it is safe to close\n// over in submit handlers. Before the mount effect has run (and after\n// unmount) load() reads false and clear() is a no-op — the same\n// guarded no-throw posture persistForm itself has.\n//\n// Options are read when the subscription (re)starts — on mount, and again\n// if `form` or `options.key` changes — not on every render, mirroring\n// useForm's locked-options rule; pass a stable options object or accept\n// that later edits to it are ignored until the key or form changes. The\n// one exception is `storage`: every call goes to the storage of the\n// LATEST render through a proxy, so a swap (session to local, a per-user\n// namespace) takes effect on the next touch without a resubscribe. With\n// storage in the effect deps instead, an inline storage literal\n// resubscribed on every render, and the outgoing subscription's dispose()\n// flushed, which collapsed the debounce to nothing and re-read the draft\n// each render.\nexport const usePersistForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n options: PersistOptions<TSchema>,\n): PersistHandle => {\n const inner = useRef<PersistHandle | null>(null);\n const latestOptions = useRef(options);\n // An effect, not a render-time ref write (refs are off-limits during\n // render): it runs before the subscription effect below in the same\n // commit, so a resubscribe always reads the options of the render that\n // triggered it.\n useEffect(() => {\n latestOptions.current = options;\n });\n\n const key = options.key;\n // Whether a storage is given at all still keys the subscription: the\n // proxy cannot stand in for persistForm's default (localStorage), so\n // switching between \"a storage\" and \"the default\" resubscribes.\n const hasStorage = options.storage !== undefined;\n const storageProxy = useMemo<PersistStorage>(\n () => ({\n getItem: (k) => latestOptions.current.storage?.getItem(k) ?? null,\n setItem: (k, v) => latestOptions.current.storage?.setItem(k, v),\n removeItem: (k) => latestOptions.current.storage?.removeItem(k),\n }),\n [],\n );\n useEffect(() => {\n const options = latestOptions.current;\n const handle = persistForm(form, {\n ...options,\n ...(options.storage === undefined ? {} : { storage: storageProxy }),\n });\n inner.current = handle;\n return () => {\n inner.current = null;\n handle.dispose();\n };\n // StrictMode's mount-cleanup-mount runs this twice: each pass gets its\n // own subscription and disposes the previous, so no double-writes.\n }, [form, key, hasStorage, storageProxy]);\n\n return useMemo(\n () => ({\n load: () => inner.current?.load() ?? false,\n flush: () => inner.current?.flush(),\n clear: () => inner.current?.clear(),\n // dispose stops THIS component's watching early; the effect cleanup\n // still runs its own dispose harmlessly (persistForm's dispose is\n // idempotent by construction — it only cancels and unsubscribes).\n dispose: () => inner.current?.dispose(),\n }),\n [],\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport {\n type CreateFormOptions,\n type Form,\n createForm,\n} from \"../core/createForm\";\nimport { valuesEqual } from \"../core/equality\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// Lazy-creates a Form bound to this component instance. Schema and options are\n// locked in on the first render; later changes are ignored (warned once below).\n// D mirrors createForm's inference: a literal from `options.pathDepth`\n// (constrained to PathDepth, 0-25), defaulting to the 9-segment typed-path\n// budget.\nexport const useForm = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n schema: TSchema,\n options: CreateFormOptions<TSchema, D>,\n // NoInfer for the same reason createForm's return has it: an inline\n // `useFieldArray(useForm(schema, opts), \"items\")` would otherwise infer\n // the depth from the outer call's unresolved parameter.\n): Form<TSchema, NoInfer<D>> => {\n const formRef = useRef<Form<TSchema, D> | null>(null);\n if (formRef.current === null) {\n formRef.current = createForm(schema, options);\n }\n // Lazy init of an external store handle — the sanctioned useRef exception\n // (react.dev: \"avoiding recreating the ref contents\"); the rule can't see\n // that this read is guarded by the null-check init above.\n // eslint-disable-next-line react-hooks/refs\n const form = formRef.current;\n\n const mountInitialsRef = useRef(options.initialValues);\n const warnedRef = useRef(false);\n useEffect(() => {\n // Two footguns, one warning: a new schema reference, or initial values\n // whose CONTENT changed after mount (the async-fetch pattern\n // `initialValues: data ?? {}` with a module-hoisted schema — the schema\n // check alone would never see it). Structural compare, so inline object\n // literals that re-create identical options every render stay silent.\n const changedInitials =\n !Object.is(options.initialValues, mountInitialsRef.current) &&\n !valuesEqual(options.initialValues, mountInitialsRef.current);\n if (!warnedRef.current && (form.schema !== schema || changedInitials)) {\n warnedRef.current = true;\n console.warn(\n \"[formstand] useForm received a different schema or initial values \" +\n \"after the first render; schema and options changes are ignored \" +\n \"for the life of the component. If the schema is defined inline \" +\n \"this is harmless (but consider hoisting it to module scope). For \" +\n \"initial values that arrive later (e.g. from a fetch), call \" +\n \"form.adoptValues(values) or form.reset(values) instead.\",\n );\n }\n }, [form, schema, options.initialValues]);\n\n return form;\n};\n","import type { ChangeEvent } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\n\nexport type TextInputProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type NumberInputProps = Readonly<{\n type: \"number\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type DateInputProps = Readonly<{\n type: \"date\";\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type CheckboxProps = Readonly<{\n type: \"checkbox\";\n name: string;\n checked: boolean;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\nexport type SelectProps = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLSelectElement>) => void;\n onBlur: () => void;\n}>;\n\n// THE predicate for \"does this field currently show an error\" — shared by\n// the aria-invalid mapping here and the field shells in fields.tsx, so the\n// notion of \"showing an error\" cannot drift between bindings.\nexport const hasFieldError = (\n error: readonly string[] | undefined,\n): boolean => error !== undefined && error.length > 0;\n\nconst ariaInvalid = (\n field: Readonly<{ error: readonly string[] | undefined }>,\n): true | undefined => (hasFieldError(field.error) ? true : undefined);\n\n// A cleared input writes back `field.emptyValue` when the schema ACCEPTS it\n// (`field.clearable`: optional, nullable, or defaulted — useField introspects\n// the form's zod schema), so z.number().nullable() round-trips to null and\n// z.string().optional() to undefined instead of a lingering \"\". A required\n// string cleared to \"\" stays \"\": writing undefined there would trade a\n// visible value the schema can judge for a hole it rejects.\n\n// Canonical display text for a numeric field value (\"\" for empty/NaN; null\n// counts as empty so nullable fields don't render the literal text \"null\").\n// Shared with NumberField so the two number bindings can't drift.\nexport const numberToInputText = (value: number | null | undefined): string =>\n value === undefined || value === null || Number.isNaN(value)\n ? \"\"\n : String(value);\n\nexport type ParsedNumberText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"number\"; value: number }>\n // Text that doesn't parse to a finite number — partial entries (\"-\",\n // \"1e\") or Infinity. A trailing point (\"1.\") is a number (1): the\n // text input keeps the point, the form already holds the value.\n | Readonly<{ kind: \"invalid\" }>;\n\n// Plain decimal notation: an optional sign, digits with an optional\n// fraction (a bare \".5\" included, and a trailing \"1.\" reads as 1: the\n// number is live while a text input keeps the point on screen), an\n// optional exponent. Number() alone also reads hex, octal and binary\n// literals (\"0x10\" stored 16) and the Infinity spellings, none of which a\n// person means in a number field.\nconst DECIMAL_TEXT = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// The single rule for turning user-typed text into a numeric field value:\n// whitespace counts as empty (Number(\" \") is 0), only decimal notation\n// parses, and non-finite results are rejected. Shared with NumberField.\nexport const parseNumberText = (text: string): ParsedNumberText => {\n const trimmed = text.trim();\n if (trimmed === \"\") return { kind: \"empty\" };\n if (!DECIMAL_TEXT.test(trimmed)) return { kind: \"invalid\" };\n const parsed = Number(trimmed);\n return Number.isFinite(parsed)\n ? { kind: \"number\", value: parsed }\n : { kind: \"invalid\" };\n};\n\nexport const textInputProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): TextInputProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const text = e.target.value;\n // Deleting all text from a clearable field restores its emptyValue\n // (null or undefined), so it isn't left permanently dirty (or invalid)\n // by a visual no-op.\n field.setValue((text === \"\" && field.clearable ? field.emptyValue : text) as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const numberInputProps = <T extends number | null | undefined>(\n field: UseFieldReturn<T>,\n): NumberInputProps => ({\n type: \"number\",\n name: field.path,\n value: numberToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseNumberText(e.target.value);\n // \"invalid\" is a PARTIAL entry (a lone \"-\", \"1e\") — keep the stored\n // value untouched, matching useNumberInput's deliberate semantics,\n // instead of writing emptyValue mid-keystroke (which flashed a\n // required error and flipped dirty while the user was still typing).\n // \"empty\" still clears to emptyValue. Note browsers report \"\" for\n // badInput on type=\"number\", so some partial entries arrive as\n // \"empty\" regardless — useNumberInput (a text input with its own raw\n // state) remains the binding that preserves every keystroke.\n if (parsed.kind === \"invalid\") return;\n field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\n },\n onBlur: field.onBlur,\n});\n\n// Canonical display text for a Date field value — the local calendar date\n// as \"yyyy-MM-dd\" (what <input type=\"date\"> speaks). Local parts, NOT\n// toISOString(): a date picked as June 1 must not render as May 31 for\n// users west of UTC. Invalid Dates count as empty. Shared with DateField.\n//\n// A value that is not a Date at runtime is read as one for display: a\n// persisted draft hands a Date field back as the ISO string JSON made of\n// it (persistForm documents that it does not revive Dates), and the\n// `.getTime()` on that string threw at render, on every visit, since the\n// crashing draft was the one being rewritten. The schema still rejects the\n// string at validation, which is the honest state to leave it in.\nexport const dateToInputText = (value: Date | null | undefined): string => {\n if (value === undefined || value === null) return \"\";\n // A date-only string (a persisted draft's \"2026-03-01\") is read as the\n // calendar date it spells: the Date constructor parses that form as UTC\n // midnight, which rendered the previous day west of UTC.\n if (typeof value === \"string\") {\n // Out of the declared type (the parameter says Date), hence the cast.\n const text = value as unknown as string;\n const parsed = parseDateText(text);\n if (parsed.kind === \"date\") return dateToInputText(parsed.value);\n // A date-shaped string the parser rejects (a rolled-over \"2026-02-31\")\n // must not fall through to the Date constructor's UTC reading either;\n // it spells no day, so it renders as empty.\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(text.trim())) return \"\";\n }\n const date =\n value instanceof Date ? value : new Date(value as unknown as string);\n if (Number.isNaN(date.getTime())) return \"\";\n const pad = (part: number): string => String(part).padStart(2, \"0\");\n return `${String(date.getFullYear()).padStart(4, \"0\")}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n};\n\nexport type ParsedDateText =\n | Readonly<{ kind: \"empty\" }>\n | Readonly<{ kind: \"date\"; value: Date }>\n // Not \"yyyy-MM-dd\", or parts that roll over (2026-02-31).\n | Readonly<{ kind: \"invalid\" }>;\n\n// The single rule for turning \"yyyy-MM-dd\" into a Date field value: LOCAL\n// midnight — a calendar date, not a UTC instant (new Date(\"2026-06-01\")\n// would be UTC midnight and read back as May 31 west of Greenwich).\n// Shared with DateField.\nexport const parseDateText = (text: string): ParsedDateText => {\n if (text.trim() === \"\") return { kind: \"empty\" };\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n if (match === null) return { kind: \"invalid\" };\n const [, year, month, day] = match;\n const y = Number(year);\n const date = new Date(y, Number(month) - 1, Number(day));\n // The Date constructor maps two-digit years 0–99 to 1900–1999, so a valid\n // \"0099-01-01\" would fail the survival check below; force the literal year\n // back on for years under 100 before checking rollover.\n if (y < 100) date.setFullYear(y);\n // The parts must survive the Date constructor — rollovers are invalid,\n // not silently the 3rd of next month.\n return date.getFullYear() === y &&\n date.getMonth() === Number(month) - 1 &&\n date.getDate() === Number(day)\n ? { kind: \"date\", value: date }\n : { kind: \"invalid\" };\n};\n\nexport const dateInputProps = <T extends Date | null | undefined>(\n field: UseFieldReturn<T>,\n): DateInputProps => ({\n type: \"date\",\n name: field.path,\n value: dateToInputText(field.value),\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const parsed = parseDateText(e.target.value);\n if (parsed.kind !== \"date\") {\n field.setValue(field.emptyValue as T);\n return;\n }\n // Preserve the existing value's time-of-day: <input type=\"date\"> only\n // edits the calendar date, so re-picking the SAME day on a value that\n // carried a time (an initial `new Date()`) must stay a no-op — otherwise\n // the new local-midnight Date differs from the timestamped original and\n // the field reads spuriously dirty. Changing the day keeps that time.\n const current = field.value;\n const next =\n current instanceof Date && !Number.isNaN(current.getTime())\n ? new Date(\n parsed.value.getFullYear(),\n parsed.value.getMonth(),\n parsed.value.getDate(),\n current.getHours(),\n current.getMinutes(),\n current.getSeconds(),\n current.getMilliseconds(),\n )\n : parsed.value;\n field.setValue(next as T);\n },\n onBlur: field.onBlur,\n});\n\nexport const checkboxProps = <T extends boolean | null | undefined>(\n field: UseFieldReturn<T>,\n): CheckboxProps => ({\n type: \"checkbox\",\n name: field.path,\n checked: field.value ?? false,\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => field.setValue(e.target.checked as T),\n onBlur: field.onBlur,\n});\n\n// `?? \"\"` keeps the <select> controlled when the field has no value yet\n// (undefined for optional fields, null for nullable ones); pair it with an\n// <option value=\"\"> (SelectField renders one) so the blank state is a real\n// option instead of silently showing the first entry.\nexport const selectProps = <T extends string | null | undefined>(\n field: UseFieldReturn<T>,\n): SelectProps => ({\n name: field.path,\n value: field.value ?? \"\",\n \"aria-invalid\": ariaInvalid(field),\n onChange: (e) => {\n const v = e.target.value;\n field.setValue((v === \"\" && field.clearable ? field.emptyValue : v) as T);\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, useState } from \"react\";\nimport type { UseFieldReturn } from \"./useField\";\nimport { hasFieldError } from \"./inputProps\";\n\n// The raw-text editing pattern behind NumberField/useNumberInput,\n// generalized to ANY parsed-and-formatted value: phone numbers, currency,\n// percentages, locale-formatted anything. A naive controlled input\n// re-renders the canonical format on every keystroke, which eats the\n// separators and partial entries the user is mid-way through typing. This\n// hook keeps the raw text locally while editing, pushes PARSED values to\n// the form as soon as a keystroke parses, and snaps the display back to\n// the canonical format on blur — so the form always holds a real value\n// while the input stays typeable.\n\nexport type MaskedParse<TValue> =\n // A complete value — pushed to the form immediately.\n | Readonly<{ kind: \"value\"; value: TValue }>\n // Nothing entered — the field's emptyValue is pushed (null/undefined\n // per the schema, same rule as the number and date bindings).\n | Readonly<{ kind: \"empty\" }>\n // A partial or unparseable entry — kept as local text, the form value\n // untouched (matching useNumberInput's deliberate semantics).\n | Readonly<{ kind: \"invalid\" }>;\n\nexport type MaskedInputOptions<TValue> = Readonly<{\n // The single rule for turning user-typed text into a field value.\n parse: (text: string) => MaskedParse<TValue>;\n // Canonical display text for a field value — what blur snaps back to.\n format: (value: TValue) => string;\n}>;\n\nexport type MaskedInputBinding = Readonly<{\n name: string;\n value: string;\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype MaskedEditState<TValue> = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a\n // partial entry). When field.value diverges, an external writer\n // (reset/adoptValues/another component) changed it — drop the raw text\n // so the input shows the external value.\n pushed: TValue | null | undefined;\n}>;\n\n// Generic over the field's OWN value type (nullability included), so an\n// optional field binds as naturally as a nullable one: parse/format speak\n// the non-null value, and the nullish side is the emptyValue round trip.\nexport const useMaskedInput = <TValue>(\n field: UseFieldReturn<TValue>,\n options: MaskedInputOptions<NonNullable<TValue>>,\n): MaskedInputBinding => {\n const [edit, setEdit] = useState<MaskedEditState<TValue>>({\n raw: null,\n pushed: undefined,\n });\n // Render-phase derived-state reset, same as useNumberInput: an external\n // value change while editing wins over the local text. Object.is works\n // for reference values too — the hook pushed the very instance it holds.\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit({ raw: null, pushed: undefined });\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value:\n raw ??\n (field.value === undefined || field.value === null\n ? \"\"\n : options.format(field.value as NonNullable<TValue>)),\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = options.parse(text);\n switch (parsed.kind) {\n case \"value\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"empty\": {\n // The same clearing rule as textInputProps: emptyValue only when\n // the schema ACCEPTS it (field.clearable: optional, nullable,\n // defaulted). A REQUIRED string field clears back to \"\", so it\n // reads clean against a \"\" initial and reports the author's\n // message (z.string().min(1, \"required\")) instead of zod's\n // \"expected string, received undefined\". Non-string fields\n // (a masked number or date) have no honest blank besides\n // emptyValue, exactly like numberInputProps, so they keep it.\n // TValue is erased, so the runtime values are the signal: the\n // initial value, OR the current one, because a required string\n // whose key the initial values omitted (filled in later) read\n // as a non-string field on the initial value alone and cleared\n // to undefined where the schema wanted \"\". The cast is the\n // emptyValue contract, not a guess.\n const isStringField =\n typeof field.initialValue === \"string\" ||\n typeof field.value === \"string\";\n const empty = (\n field.clearable || !isStringField ? field.emptyValue : \"\"\n ) as TValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form\n // value so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n // Snap the display to the canonical format of whatever the form\n // holds, then run the field's ordinary blur (touched + mode gate).\n setEdit({ raw: null, pushed: undefined });\n field.onBlur();\n },\n };\n};\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type FormStateApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n}>;\n\nexport function useFormSelector<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above. Without\n// it, Form<TSchema> would structurally satisfy FormStateApi too and a\n// bad selector could silently widen to FormState<unknown>.\nexport function useFormSelector<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelector<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, selector);\n}\n\nexport function useFormSelectorShallow<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, useShallow(selector));\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n type SettledFieldsValidationResult,\n isPathOrChild,\n} from \"../core/validation\";\nimport { useFormSelectorShallow } from \"./useFormSelector\";\n\n// The multi-step (wizard) story: one form, one schema, one values object —\n// and a step index that gates progress on the CURRENT step's fields\n// validating clean. Everything else falls out of what the library already\n// does: next() runs validateFieldsAsync over the step's paths (just those\n// slots when every path extracts a subschema; a refine on an ancestor\n// object sends the batch through the full parse, so cross-field rules\n// inside a step still fire; either way the errors are scoped to the\n// step), a failed advance marks the errored fields touched\n// exactly the way a failed submit does (so touched-gated error UIs show),\n// and going BACK never validates — leaving a half-filled step is normal.\n//\n// The step index is deliberately React state, not form state: it is UI\n// navigation, not form data, and FormState's shape is owned by the\n// library. Render a progress bar elsewhere by lifting the returned value,\n// exactly as you would any other component state.\n//\n// Cross-STEP rules (a schema-level refine over fields in different steps)\n// surface at submit, like every wizard: a step only re-judges its own\n// paths, and the root \"\" key belongs to the whole form.\n\nexport type FormStep<TValues, D extends PathDepth = DefaultPathDepth> = Readonly<{\n // For progress UIs; steps are addressed by index either way.\n name?: string;\n // The paths this step owns — a container path covers its whole subtree.\n fields: readonly FieldPath<TValues, D>[];\n}>;\n\nexport type StepStatus = Readonly<{\n name: string | undefined;\n // The user has been ON this step (the first step starts visited).\n visited: boolean;\n // Any error currently at or under the step's fields — live, so a\n // progress bar can flag a step the user broke after leaving it.\n hasErrors: boolean;\n}>;\n\nexport type UseFormStepsReturn = Readonly<{\n step: number;\n name: string | undefined;\n count: number;\n isFirst: boolean;\n isLast: boolean;\n // Validate the current step; on clean, advance (no-op advance on the\n // last step — submit is the last step's \"next\"). Resolves whether the\n // step validated clean AND the advance applied, so `if (await\n // steps.next())` reads naturally on any step, the last included; a\n // user who navigated elsewhere while the pass was in flight keeps their\n // newer position and the call resolves false.\n next: () => Promise<boolean>;\n // Never validates: leaving a half-filled step backward is normal.\n back: () => void;\n // Backward jumps are free. A forward jump validates each step from the\n // current one up to (not including) the target and LANDS ON THE FIRST\n // ONE THAT FAILS, errors visible — so a step header can be a plain\n // goTo() without letting anyone skip past an invalid step. Resolves the\n // index actually landed on.\n goTo: (target: number) => Promise<number>;\n // Per-step live status, index-aligned with the definitions.\n steps: readonly StepStatus[];\n}>;\n\n// A step's verdict for the values it holds NOW. validateFieldsAsync's\n// verdict describes the values the pass started with: the core refuses to\n// commit a stale one but still resolves it, so a step whose value changed\n// while an async rule was in flight used to advance on the old value. A\n// changed step re-runs on the live values; a few rounds cover a user still\n// typing, past that (null) the advance refuses.\nconst settleOnLiveValues = async <\n TSchema extends z.ZodType,\n D extends PathDepth,\n>(\n form: Form<TSchema, D>,\n fields: readonly FieldPath<z.input<TSchema>, D>[],\n round = 0,\n): Promise<SettledFieldsValidationResult | null> => {\n const before = fields.map((path) => form.getField(path));\n const result = await form.validateFieldsAsync(fields);\n const changed = fields.some(\n (path, i) => !Object.is(form.getField(path), before[i]),\n );\n if (!changed) return result;\n return round < 3 ? settleOnLiveValues(form, fields, round + 1) : null;\n};\n\nexport const useFormSteps = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n steps: readonly FormStep<z.input<TSchema>, D>[],\n): UseFormStepsReturn => {\n const [step, setStep] = useState(0);\n const [visited, setVisited] = useState<ReadonlySet<number>>(\n () => new Set([0]),\n );\n\n // Latest-ref so next/goTo/back are reference-stable however the caller\n // writes the steps array (the usePersistForm pattern; navigation only\n // fires after mount, so the ref is always populated). The COUNT should\n // stay stable for sensible UX, but nothing here breaks if it doesn't —\n // there are no per-step hooks.\n const latest = useRef(steps);\n useEffect(() => {\n latest.current = steps;\n });\n\n // Validate one step's paths and mirror submit's convention on failure:\n // the errored keys (already scoped to the step by validateFieldsAsync)\n // are marked touched, so touched-gated error UIs show why the advance\n // refused. The pass is judged on the step's live values (see\n // settleOnLiveValues).\n const validateStep = useCallback(\n async (index: number): Promise<boolean> => {\n const definition = latest.current[index];\n if (definition === undefined) return true;\n const result = await settleOnLiveValues(form, definition.fields);\n if (result === null) return false;\n if (result.kind === \"invalid\") {\n Object.keys(result.errors).forEach((key) => {\n form.setTouched(key as FieldPath<z.input<TSchema>, D>, true);\n });\n return false;\n }\n return true;\n },\n [form],\n );\n\n // The step the user is on RIGHT NOW: a ref every navigation writes\n // synchronously, which next() and goTo() read when they start and again\n // after their await. The render-time `step` lagged twice over: a closure\n // held the step of the render it came from, so two awaited next() calls\n // from one handler validated the same step twice (both resolved true,\n // the wizard moved once), and the guard ref used to move in an effect, a\n // commit late. State mirrors the ref for rendering. The user may press\n // back() while a validation is in flight; applying the advance then\n // would land two steps past where they now are, so each transition\n // re-checks that the step is still the one it validated before writing,\n // and otherwise leaves the user's newer navigation alone.\n const currentStep = useRef(step);\n const navigate = useCallback((target: number): void => {\n currentStep.current = target;\n setStep(target);\n }, []);\n\n const next = useCallback(async (): Promise<boolean> => {\n const from = currentStep.current;\n const ok = await validateStep(from);\n if (!ok) return false;\n if (currentStep.current !== from) return false;\n // Clamped at 0 as well: with no steps defined the last index is -1.\n const target = Math.max(0, Math.min(from + 1, latest.current.length - 1));\n navigate(target);\n setVisited((prev) => new Set([...prev, target]));\n return true;\n }, [validateStep, navigate]);\n\n const back = useCallback((): void => {\n navigate(Math.max(currentStep.current - 1, 0));\n }, [navigate]);\n\n const goTo = useCallback(\n async (target: number): Promise<number> => {\n const count = latest.current.length;\n // A NaN target (Number(\"\") from an empty <select> option) passed\n // through the clamp as NaN, and the forward walk's `from >= NaN`\n // never held, so it recursed without bound. A target that is not a\n // finite number is a no-op that resolves where the form is.\n if (!Number.isFinite(target)) return currentStep.current;\n const from = currentStep.current;\n const clamped = Math.max(0, Math.min(Math.trunc(target), count - 1));\n if (clamped <= from) {\n navigate(clamped);\n return clamped;\n }\n // Walk forward, validating each step on the way; land on the first\n // failure so its errors are on screen.\n const walk = async (at: number): Promise<number> => {\n if (at >= clamped) return clamped;\n return (await validateStep(at)) ? walk(at + 1) : at;\n };\n const landed = await walk(from);\n // The user navigated during the walk (back(), or another goTo that\n // resolved first): their newer position wins, and the caller learns\n // where the form actually is.\n if (currentStep.current !== from) return currentStep.current;\n navigate(landed);\n setVisited(\n (prev) =>\n new Set([\n ...prev,\n ...Array.from({ length: landed - from + 1 }, (_, i) => from + i),\n ]),\n );\n return landed;\n },\n [validateStep, navigate],\n );\n\n // Live per-step error presence, shallow-compared so renders happen only\n // when some step's flag flips — not on every error-map write.\n const errorFlags = useFormSelectorShallow(form, (state) =>\n steps.map((definition) =>\n definition.fields.some((path) =>\n Object.keys(state.errors).some((key) => isPathOrChild(key, path)),\n ),\n ),\n );\n\n const statuses = useMemo(\n () =>\n steps.map(\n (definition, index): StepStatus => ({\n name: definition.name,\n visited: visited.has(index),\n hasErrors: errorFlags[index] ?? false,\n }),\n ),\n [steps, visited, errorFlags],\n );\n\n return useMemo(\n () => ({\n step,\n name: steps[step]?.name,\n count: steps.length,\n isFirst: step === 0,\n isLast: step === steps.length - 1,\n next,\n back,\n goTo,\n steps: statuses,\n }),\n [step, steps, next, back, goTo, statuses],\n );\n};\n","import { useActionState, useCallback, useEffect, useRef } from \"react\";\nimport { isDevBuild } from \"../core/env\";\nimport type { z } from \"zod\";\nimport type {\n Form,\n InvalidSubmitHandler,\n SubmitResult,\n} from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\n// The React 19 form-actions bridge: bind a formstand form's validation and\n// submit lifecycle to `<form action={...}>` and useActionState, so the\n// action world gets what onSubmit callers already have — schema\n// validation before the action runs, isSubmitting/submitCount tracking,\n// errors written and their fields marked touched on a failed submit, and\n// the two-channel error model for the action's own verdicts.\n//\n// The handler receives PARSED, TYPED data (z.output of the schema), not\n// FormData: formstand inputs are controlled, so the store is the source of\n// truth and the schema has already judged it. The raw FormData still\n// arrives as the last argument for what only it can carry — uncontrolled\n// inputs in the same <form>, file pickers — and because a server action\n// can take it across the wire (FormData serializes under RSC).\n//\n// Honest scope: this is a CLIENT-side integration. React's no-JS\n// progressive enhancement only works when the server action itself is\n// passed to the form/useActionState, which by definition skips any\n// client-side wrapper — for that path, validate on the server with the\n// same zod schema and keep this bridge for the hydrated experience.\n//\n// Note on React's post-action reset: React 19 resets UNCONTROLLED form\n// fields after an action completes. formstand inputs are controlled, so\n// the form's values survive the action untouched.\n\nexport type FormActionHandler<TSchema extends z.ZodType> = (\n data: z.output<TSchema>,\n formData: FormData,\n) => void | Promise<void>;\n\n// S is the AWAITED state (what the reducer stores), so the handler's\n// return may be the state or a promise of it — the shape a \"use server\"\n// async function naturally has.\nexport type FormActionStateHandler<TSchema extends z.ZodType, S> = (\n prevState: S,\n data: z.output<TSchema>,\n formData: FormData,\n) => S | Promise<S>;\n\nexport type FormActionOptions = Readonly<{\n // Mirrors handleSubmit's second parameter: runs when validation fails\n // (errors are written and fields marked touched either way).\n onInvalid?: InvalidSubmitHandler;\n // Mirrors SubmitOptions.onError: the save-failure hook for a throwing\n // handler. Without it, dev builds warn when a failure resolves\n // unobserved — the action form is fire-and-forget, like handleSubmit.\n onError?: (error: unknown) => void;\n // Mirrors SubmitOptions.force: let this submit claim the in-flight slot\n // from one already running instead of resolving \"skipped\".\n force?: boolean;\n}>;\n\n// The fire-and-forget dev warning, same contract as handleSubmit's: a\n// throwing handler resolves {kind: \"error\"} writing no state, so with no\n// onError the failure would vanish completely.\nconst warnUnobserved = (\n result: SubmitResult<unknown>,\n options: FormActionOptions | undefined,\n site: string,\n): void => {\n if (\n result.kind === \"error\" &&\n options?.onError === undefined &&\n isDevBuild()\n ) {\n console.warn(\n `[formstand] action handler threw and nothing observed it — the form shows no feedback. Pass { onError } to ${site} (or setError inside your handler):`,\n result.error,\n );\n }\n};\n\n// The plain bridge: an action for `<form action={...}>`. Validation and\n// the submit lifecycle run first; the handler only sees data the schema\n// accepted. The returned function is REFERENCE-STABLE across renders\n// (handler and options are read through refs assigned in an effect —\n// actions only fire after mount, so the refs are always populated), which\n// keeps memoized subtrees quiet however the caller writes the handler.\nexport const useFormAction = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n): ((formData: FormData) => Promise<void>) => {\n const latest = useRef({ onValid, options });\n useEffect(() => {\n latest.current = { onValid, options };\n });\n return useCallback(\n async (formData: FormData) => {\n const { onValid: handler, options: opts } = latest.current;\n // FormActionOptions IS a SubmitOptions (onInvalid + onError), so it\n // rides through the options-object shape as it is.\n const result = await form.submit(\n (data) => handler(data, formData),\n opts ?? {},\n );\n warnUnobserved(result, opts, \"useFormAction\");\n },\n [form],\n );\n};\n\n// The stateful bridge: useActionState with schema-validated data. The\n// handler's shape mirrors the native (prevState, formData) signature with\n// the parsed data spliced in, so a \"use server\" function slots straight\n// in. A submission that fails validation (or is skipped, or throws)\n// returns the PREVIOUS state unchanged: field errors already live in the\n// form store where the bound components read them, so the action state\n// stays what it is — the last verdict an action actually produced.\nexport const useFormActionState = <\n TSchema extends z.ZodType,\n S,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n): [state: S, formAction: (formData: FormData) => void, isPending: boolean] => {\n const [state, formAction, isPending] = useActionState<S, FormData>(\n async (prevState, formData): Promise<S> => {\n // React hands the reducer Awaited<S>; S is declared as the awaited\n // state, so for any non-thenable state (the only kind a reducer can\n // meaningfully hold) the two are the same type — TS just won't\n // simplify the deferred conditional for an unconstrained S.\n const prev = prevState as S;\n // Sanctioned mutable ref for the handler's return value: submit owns\n // the lifecycle and its onValid returns void, so the next state\n // rides out through the closure (same shape as the codebase's other\n // capture refs).\n const nextRef: { current: S } = { current: prev };\n const result = await form.submit(\n async (data) => {\n nextRef.current = await action(prev, data, formData);\n },\n options ?? {},\n );\n warnUnobserved(result, options, \"useFormActionState\");\n return nextRef.current;\n },\n initialState as Awaited<S>,\n );\n return [state as S, formAction, isPending];\n};\n","import {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\n\nexport type FormProviderProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n Provider: (props: FormProviderProps<TSchema, D>) => ReactNode;\n useFormContext: () => Form<TSchema, D>;\n}>;\n\n// A form created with a non-default `pathDepth` names it here too:\n// createFormContext<typeof schema, 12>() — the context can't infer it (there\n// is no value argument), and Form<S, 12> is deliberately not Form<S, 9>.\n// The `PathDepth` constraint makes an out-of-range literal (26, -1) or a\n// widened `number` argument a compile error, same as createForm's option.\nexport const createFormContext = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(): FormContextApi<TSchema, D> => {\n const Context = createContext<Form<TSchema, D> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema, D>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema, D> => {\n const ctx = useContext(Context);\n if (ctx === null) {\n throw new Error(\n \"useFormContext must be used inside the matching <Provider>\",\n );\n }\n return ctx;\n };\n\n return { Provider, useFormContext };\n};\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport { type Debouncer, createDebouncer } from \"../core/debounce\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { entryAt, flagAt } from \"../core/maps\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n emptyValueForSchema,\n isClearableSchema,\n fieldSchemaForIntrospection,\n reportBackgroundFailure,\n} from \"../core/validation\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose write methods take the narrower\n// FieldPath<...> instead of string — still satisfies this API. Prefer calling\n// these through a typed Form when you have one.\nexport type FieldFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n setValue(path: string, value: unknown): void;\n setTouched(path: string, touched?: boolean): void;\n setError(path: string, errors: string | readonly string[]): void;\n clearErrors(path?: string): void;\n validateField(path: string): FieldValidationResult;\n // Settled by contract: an awaited pass can never resolve \"pending\" —\n // the promise IS the pending state, and a resolved {kind: \"pending\"}\n // would carry a promise that never runs. Custom implementations were\n // always expected to resolve settled; the type now says so.\n validateFieldAsync(path: string): Promise<SettledFieldValidationResult>;\n}>;\n\nexport type FieldPathArg<TValues> =\n | string\n | ((state: FormState<TValues>) => string);\n\nexport type UseFieldOptions = Readonly<{\n debounceMs?: number;\n}>;\n\nexport type UseFieldReturn<TValue> = Readonly<{\n // The resolved field path — useful as an input's `name` attribute (the\n // bound prop builders spread it as `name`).\n path: string;\n value: TValue;\n // The slice of initialValues at this path (what `dirty` compares against).\n initialValue: TValue;\n // What a cleared input writes back: null when the field's schema is\n // nullable (introspected when the form carries its schema — the zod-first\n // source of truth), undefined when it is optional or unknown. Falls back\n // to \"the initial value was null\" for schema-less FieldFormApi forms.\n emptyValue: null | undefined;\n // Whether the schema ACCEPTS that emptyValue (optional / nullable /\n // defaulted — see isClearableSchema). The string-shaped bindings write\n // emptyValue on a cleared input only when this is true; a required\n // string cleared to \"\" stays \"\" so the schema judges a visible value\n // instead of a hole it rejects. Schema-less forms fall back to the same\n // heuristic as emptyValue: a null initial value reads as clearable.\n clearable: boolean;\n error: readonly string[] | undefined;\n // The first error message, or undefined when the channel is empty — the\n // display shorthand every adapter otherwise re-derives by hand (the\n // `error?.[0]`-with-empty-array-guard helper each generated kit adapter\n // used to open with).\n firstError: string | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setValue: (value: TValue) => void;\n setTouched: (touched?: boolean) => void;\n // A single string is shorthand for a one-element array (like form.setError).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n validate: () => FieldValidationResult;\n // Settled: awaited passes never resolve \"pending\" (see FieldFormApi).\n validateAsync: () => Promise<SettledFieldValidationResult>;\n onBlur: () => void;\n}>;\n\ntype FieldSlice<TValue> = Readonly<{\n path: string;\n value: TValue;\n initialValue: TValue;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n // The field's schema for introspection, resolved against the live values\n // (see fieldSchemaForIntrospection), or null without a schema.\n schema: z.ZodType | null;\n}>;\n\n// The readable-error trap-guard for `useField<Values>(typedForm, \"email\")`:\n// any explicit type argument arity-matches ONLY the one-type-parameter\n// overloads, and the structural one's `schema?: undefined` brand then\n// rejects the Form with a baffling \"... not assignable to type 'undefined'\".\n// The error overload below intercepts that shape: its TValue defaults to\n// this unexported sentinel — an INFERRED call can never produce it (TValue\n// has no inference site, so it always falls back to the default), which\n// collapses `path` to `never` and fails the overload silently — while an\n// EXPLICIT TValue (never assignable to the unexported brand) on a\n// schema-carrying form types `path` as a string-literal error message, so\n// the compiler blames the path argument with instructions instead of brand\n// internals.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order is deliberate. When no overload matches, TypeScript reports\n// the LAST candidate's error — so the typed-path overload sits last, and a\n// typo'd path on a Form<TSchema> is blamed on the path argument against the\n// full FieldPath union ('\"naem\"' is not assignable to '\"name\" | \"age\" | ...')\n// instead of on the form argument.\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useField<Schema, \"name\">`) —\n// TS applies explicit type args to every arity-compatible overload, so a\n// second parameter here would check \"name\" against it.\nexport function useField<TSchema extends z.ZodType>(\n form: FieldFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): an explicit type argument on a\n// schema-carrying form binds here and blames the path argument with a\n// readable instruction. Inferred calls can never select it — TValue stays\n// at its sentinel default and `path` collapses to `never`.\nexport function useField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n path: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the value type from the path\",\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// The `schema?: undefined` brand forces TS past this widened overload when a\n// real Form is passed (Form has `schema: TSchema`, not undefined). Without\n// it, a Form<TSchema> with an invalid path would silently bind here and\n// return UseFieldReturn<unknown>.\nexport function useField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker), so a `pathDepth: 12` form checks paths against its widened union.\n// It sits LAST (P's constraint forward-references it — legal in TS) with a\n// default, so pre-existing explicit instantiations like\n// `useField<typeof schema, \"name\">` keep their arity.\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: FieldPathArg<unknown>,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue> {\n // Schema introspection wins over the runtime heuristic when the form\n // carries its schema (Form<TSchema> does; a bare FieldFormApi may not).\n const formSchema = (form as Readonly<{ schema?: z.ZodType }>).schema;\n const slice = useStore(\n form.store,\n useShallow((state): FieldSlice<TValue> => {\n const p =\n typeof pathArg === \"function\" ? pathArg(state) : pathArg;\n const value = getAtPath(state.values, p);\n const initialValue = getAtPath(state.initialValues, p);\n return {\n path: p,\n value: value as TValue,\n initialValue: initialValue as TValue,\n // Own-key reads: a field named \"constructor\" or \"toString\" would\n // otherwise read Object.prototype's function as its error/flag.\n error: entryAt(state.errors, p),\n touched: flagAt(state.touched, p),\n dirty: isFieldDirty(value, initialValue),\n isValidating: flagAt(state.isValidating, p),\n // Resolved inside the selector so a discriminant change re-reads\n // the ACTIVE variant's wrapper for a key the variants share; the\n // schema node is a stable reference, so the shallow compare holds.\n schema:\n formSchema === undefined\n ? null\n : fieldSchemaForIntrospection(formSchema, p, state.values),\n };\n }),\n );\n const path = slice.path;\n\n const sub = slice.schema;\n const initialValue = slice.initialValue;\n const { emptyValue, clearable } = useMemo(() => {\n if (sub !== null) {\n return {\n emptyValue: emptyValueForSchema(sub),\n clearable: isClearableSchema(sub),\n };\n }\n // Schema-less heuristic: a null initial value is the one runtime signal\n // that null round-trips, so it drives both answers.\n return initialValue === null\n ? { emptyValue: null, clearable: true }\n : { emptyValue: undefined, clearable: false };\n }, [sub, initialValue]);\n\n const debounceMs = options?.debounceMs;\n // One debouncer per (form, path, debounceMs) identity, created lazily on\n // the first debounced trigger and cancelled by the effect cleanup on\n // unmount or identity change — the ref keeps it across renders.\n const debouncerRef = useRef<Debouncer | null>(null);\n\n useEffect(() => {\n return () => {\n debouncerRef.current?.cancel();\n debouncerRef.current = null;\n };\n }, [form, path, debounceMs]);\n\n // The core routes async schemas itself: validateField returns\n // { kind: \"pending\" } having already started the async pass, which\n // commits its errors and isValidating flags to the store — so the\n // result needs no handling here beyond observing a rejection.\n const validateNow = useCallback(() => {\n const result = form.validateField(path);\n if (result.kind === \"pending\") {\n void result.promise.catch(reportBackgroundFailure);\n }\n }, [form, path]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n const debouncer = debouncerRef.current ?? createDebouncer(debounceMs);\n debouncerRef.current = debouncer;\n // The pending timer is invisible to the store, so a reset() /\n // adoptValues() inside the debounce window cannot cancel it the way\n // it invalidates in-flight validation (the ownership tokens): the\n // fire would claim a FRESH token and re-commit errors onto the\n // rebased form. Two fire-time guards close it. A REBASE is detected\n // as \"the values reference moved since scheduling AND now IS\n // initialValues\", which is exactly what reset and adoptValues leave\n // behind and nothing else produces (a keystroke moves the reference\n // away from initialValues, not onto it). The bare \"values is\n // initialValues\" test used before also matched a form nobody has\n // typed in yet, so a blur with debounceMs on an untouched required\n // field never validated. The second guard drops a stale fire: a path\n // whose value changed since scheduling (the write that changed it\n // scheduled its own validation, or was a restore to other values).\n // Scheduling runs after setValue, so the captured value is the\n // keystroke being validated.\n const scheduledValues = form.store.getState().values;\n const scheduled = getAtPath(scheduledValues, path);\n debouncer.schedule(() => {\n const state = form.store.getState();\n const rebased =\n state.values !== scheduledValues &&\n state.values === state.initialValues;\n if (rebased) return;\n if (!Object.is(getAtPath(state.values, path), scheduled)) return;\n // Nobody awaits a trigger's pass: a rejecting refine is reported\n // (the core has released the field's flag) instead of escaping as\n // an unhandled rejection.\n void form.validateFieldAsync(path).catch(reportBackgroundFailure);\n });\n return;\n }\n validateNow();\n }, [form, path, debounceMs, validateNow]);\n\n const setValue = useCallback(\n (value: TValue) => {\n const before = form.store.getState();\n form.setValue(path, value);\n const state = form.store.getState();\n // A no-op write (the identical value — createForm's setValue identity\n // guard leaves the state reference untouched) skips the revalidation\n // gate too: nothing changed, so the current error state already\n // reflects this value. Custom FieldFormApi implementations without\n // the guard produce a fresh state and keep the old behavior.\n if (state === before) return;\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n flagAt(state.touched, path),\n )\n ) {\n triggerValidate();\n }\n },\n [form, path, triggerValidate],\n );\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched(path, touched),\n [form, path],\n );\n\n const setError = useCallback(\n // Normalize the string shorthand HERE, before forwarding: custom\n // FieldFormApi implementations written against the pre-0.4 surface are\n // typed for readonly string[] and must never receive a bare string.\n (errors: string | readonly string[]) =>\n form.setError(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(\n () => form.clearErrors(path),\n [form, path],\n );\n\n const validate = useCallback(() => form.validateField(path), [form, path]);\n\n const validateAsync = useCallback(\n () => form.validateFieldAsync(path),\n [form, path],\n );\n\n const onBlur = useCallback(() => {\n form.setTouched(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n // Leaving the field is the moment to judge it: a change debounce\n // still pending is dropped in favour of validating now, so\n // debounceMs throttles keystroke validation without delaying the\n // verdict on blur (the one the user is waiting for).\n debouncerRef.current?.cancel();\n validateNow();\n }\n }, [form, path, validateNow]);\n\n return useMemo(\n () => ({\n path: slice.path,\n value: slice.value,\n initialValue: slice.initialValue,\n emptyValue,\n clearable,\n error: slice.error,\n // `?.[0]` covers both the undefined channel and an empty array.\n firstError: slice.error?.[0],\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setValue,\n setTouched,\n setError,\n clearError,\n validate,\n validateAsync,\n onBlur,\n }),\n [slice, emptyValue, clearable, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\n\n// Discriminated-union support. A z.discriminatedUnion field types its value\n// as a union of variant objects, and FieldPath<T> only exposes the keys\n// COMMON to every union member (via `keyof T`) — so the DISCRIMINANT binds\n// with plain useField (it's common), but a variant-specific field\n// (\"payment.cardNumber\", present only in the card branch) resolves to a\n// path FieldPath omits. useVariantField is the typed accessor for those.\n//\n// It binds `${unionPath}.${field}` and types the result as the field's value\n// across every variant that declares it, widened with `| undefined` because\n// the field is absent while a different variant is active:\n//\n// const method = useField(form, \"payment.method\"); // discriminant\n// const cardNumber = useVariantField(form, \"payment\", \"cardNumber\");\n// // -> UseFieldReturn<string | undefined>, rendered when method.value === \"card\"\n//\n// The hook is called unconditionally (React's rules) — every variant's\n// fields bind every render; you render the matching ones based on the\n// discriminant. Runtime behavior is exactly useField on the joined path.\n//\n// Gate WRITES on the discriminant too, not just rendering: the returned\n// setter writes `${unionPath}.${field}` regardless of the active variant, so\n// calling a card field's setValue while the paypal variant is active injects\n// a stray key into the stored object. z.discriminatedUnion strips it on\n// parse (validation looks clean), but dirtyFields()/persistForm see the\n// polluted shape. Render the matching fields only — as the example shows —\n// and their setters fire only for the active variant. formstand-gen's output\n// follows this; hand-written forms must too.\n\n// The value of variant path `TField` across the members of union `V` that\n// resolve it. Distributes over V: each member contributes its FieldValue\n// when TField is one of ITS typed paths, never otherwise; the union of\n// those is the result. `| undefined` is added by the caller (the field is\n// absent while another variant is active). Since 0.20 TField is a PATH,\n// not just a key — \"size.w\" reaches inside a variant-only object — so the\n// resolution rides the same FieldPath/FieldValue machinery as useField\n// (leaf classification, tuple positions, and the depth budget included;\n// the budget applies to the path WITHIN the variant, the union path\n// having already been budget-checked by its own binding).\nexport type VariantFieldValue<V, TField extends string> = V extends unknown\n ? // No FieldPath gate needed: FieldValue resolves a path a member does\n // not declare to `never` (StepValue's miss arm), so non-declaring\n // members drop out of the union by themselves — and the constraint\n // side (VariantFieldPath) already vouches that SOME member declares\n // it.\n FieldValue<V, TField>\n : never;\n\n// The variant-only field keys of union `V`: every member's keys minus the\n// keys shared by all members (the discriminant and any other common field,\n// which bind with plain useField). `keyof V` on a union is ALREADY the\n// common keys (the intersection) — it must NOT distribute, or it would\n// equal AllKeys and leave no variant keys. AllKeys distributes to collect\n// every member's keys.\ntype CommonKeys<V> = keyof V;\ntype AllKeys<V> = V extends unknown ? keyof V : never;\nexport type VariantKeys<V> = Exclude<AllKeys<V>, CommonKeys<V>> & string;\n\n// Every typed path of every member — FieldPath distributes over the union\n// — minus the paths ROOTED at a common key: the discriminant and other\n// common fields (and anything under them) bind with plain useField, so\n// offering them here would just duplicate the plain hook with a widened\n// `| undefined`. What remains is exactly what FieldPath on the union\n// cannot offer: variant-only keys and every path INSIDE them\n// (\"cardNumber\", \"size\", \"size.w\", \"lines.0.qty\").\nexport type VariantFieldPath<\n V,\n D extends PathDepth = DefaultPathDepth,\n> = Exclude<\n V extends unknown ? FieldPath<V, D> : never,\n (CommonKeys<V> & string) | `${CommonKeys<V> & string}.${string}`\n> &\n string;\n\n// The paths in `TValues` whose value is a discriminated union — an object\n// whose members don't all share the same keys. Kept permissive (any\n// top-level or nested key reaching a union of objects); misuse on a\n// non-union path yields `never` field keys, so the call simply won't\n// typecheck a field argument.\n// One segment's value, looked up PER MEMBER when TValues is itself a union:\n// `keyof` on a union is the common keys only, so a union nested inside\n// another union's variant (\"shape.detail\", where detail exists on one\n// shape) resolved to never and neither spelling of the nested bind\n// compiled. Distributing collects the value from every member that\n// declares the key; members without it contribute nothing.\ntype MemberValueAt<TValues, K extends string> = TValues extends unknown\n ? K extends keyof TValues\n ? TValues[K]\n : never\n : never;\n\nexport type UnionValueAt<TValues, P extends string> = [\n MemberValueAt<TValues, P>,\n] extends [never]\n ? UnionValueAtDeep<TValues, P>\n : // NonNullable is essential: for an OPTIONAL/nullable union field the\n // resolved value includes undefined, which collapses `keyof V` to never\n // — VariantKeys would then leak EVERY key (discriminant included) and\n // the whole guard inverts. Strip the nullish part first.\n NonNullable<MemberValueAt<TValues, P>>;\n\ntype UnionValueAtDeep<TValues, P extends string> = P extends keyof TValues\n ? NonNullable<TValues[P]>\n : TValues extends readonly (infer Item)[]\n ? // Array rows: a numeric segment — a literal \"0\" or the `${number}`\n // a template path like `pavements.${index}` produces — selects the\n // ELEMENT type, so a union that IS the row item resolves the same\n // way a static object path does. (`keyof` above cannot do this:\n // an array's numeric index signature is `number`, and the string\n // segment types never extend it.) Without this branch every\n // row-indexed union path collapsed the field keys to `never`,\n // making unions inside array rows unbindable — the exact wall the\n // generated array-row TODO used to steer people into.\n P extends `${number}`\n ? NonNullable<Item>\n : P extends `${infer Head}.${infer Tail}`\n ? // Tuple positionality first: a tuple's keyof carries its literal\n // indices, so \"wrap.0.pay\" resolves element 0's OWN shape\n // instead of the all-elements union `Item` (whose keyof\n // collapses to common keys and killed the variant-key set). A\n // plain array's keyof has no numeric-string members, so it\n // falls through to the element branch unchanged.\n [MemberValueAt<TValues, Head>] extends [never]\n ? Head extends `${number}`\n ? UnionValueAt<NonNullable<Item>, Tail>\n : never\n : UnionValueAt<NonNullable<MemberValueAt<TValues, Head>>, Tail>\n : never\n : P extends `${infer Head}.${infer Tail}`\n ? [MemberValueAt<TValues, Head>] extends [never]\n ? never\n : UnionValueAt<NonNullable<MemberValueAt<TValues, Head>>, Tail>\n : never;\n\n// The readable-error trap-guard, mirroring useField's/useFieldArray's: an\n// explicit type argument (`useVariantField<string>(typedForm, \"payment\",\n// \"cardNumber\")`) arity-matches ONLY the one-type-parameter overloads, and\n// the structural one's `schema?: undefined` brand then rejects the Form\n// with a baffling \"... not assignable to type 'undefined'\". The error\n// overload below intercepts that shape — TValue defaults to this unexported\n// sentinel, which inferred calls can never escape (TValue has no inference\n// site), collapsing `unionPath` to `never`; an explicit TValue on a\n// schema-carrying form instead types `unionPath` as a string-literal\n// instruction the compiler blames the argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the trap\n// guard sits before the widened structural overload, and the typed overload\n// sits LAST so a bad union path / field name on a Form<TSchema> is blamed\n// on that argument against the real union instead of on the form argument.\nexport function useVariantField<TValue = InferredTypeArg>(\n form: FieldFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TValue extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the variant value from the union path and field\",\n field: string,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue | undefined>;\n// Schema-less forms keep the plain-string, caller-typed shape. The\n// `schema?: undefined` brand forces a real Form past this widened overload\n// (Form has `schema: TSchema`, not undefined).\nexport function useVariantField<TValue = unknown>(\n form: FieldFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n options?: UseFieldOptions,\n): UseFieldReturn<TValue | undefined>;\n// D is recovered from the form argument (the Form type's \"~pathDepth\"\n// marker). It sits LAST with a default, so pre-existing explicit\n// instantiation expressions like\n// `typeof useVariantField<typeof schema, \"payment\", \"cardNumber\">` keep\n// their arity.\nexport function useVariantField<\n TSchema extends z.ZodType,\n P extends string,\n // The DEFAULT depth budget on purpose, not D: a constraint may not\n // consume a later type parameter before inference resolves it — TS\n // substitutes D's CONSTRAINT (the whole PathDepth union) while checking\n // TField, which collapses the offered paths to never. Variant subtrees\n // are shallow by construction (they sit under an already-budgeted union\n // path), so the fixed default costs nothing real.\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n // The same per-field options useField takes (debounceMs): a variant\n // field is an ordinary field that FieldPath could not name.\n options?: UseFieldOptions,\n): UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\nexport function useVariantField(\n form: FieldFormApi,\n unionPath: string,\n field: string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown> {\n // Structural string-path bind: the joined path is exactly what a variant\n // field lives at; only its TYPE was unreachable through FieldPath, so the\n // runtime is ordinary useField.\n return useField(\n form as FieldFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n options,\n );\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport {\n type ArrayOpRecord,\n arrayOpsFor,\n clearArrayOps,\n} from \"../core/arrayOpLog\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { entryAt, flagAt } from \"../core/maps\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n reportBackgroundFailure,\n} from \"../core/validation\";\nimport type { FieldPathArg } from \"./useField\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\n// Method (shorthand) syntax on purpose: method parameters are checked\n// bivariantly, so a Form<TSchema> — whose array ops take the narrower\n// FieldPath<...> instead of string — still satisfies this API.\n// NOTE for custom implementations: exact row-id tracking for ops on\n// Object.is-equal rows is a createForm feature (its ops record their index\n// mappings internally) — a hand-rolled implementation of these methods gets\n// value-based id reconciliation only.\nexport type FieldArrayFormApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n arrayPush(path: string, item: unknown): void;\n arrayRemove(path: string, index: number): void;\n arrayInsert(path: string, index: number, item: unknown): void;\n arrayMove(path: string, from: number, to: number): void;\n arraySwap(path: string, a: number, b: number): void;\n // OPTIONAL, probed before use: when present (createForm always provides\n // it), the hook's op wrappers revalidate the array path after an op under\n // the same change-trigger gate useField.setValue applies — so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. NOTE for custom implementations: a hand-rolled FieldArrayFormApi\n // without this member still works — the ops simply skip revalidation.\n validateField?(path: string): FieldValidationResult;\n // OPTIONAL, the awaitable twin: backs the hook's validateAsync, which\n // resolves valid without running on an implementation that lacks it.\n validateFieldAsync?(path: string): Promise<SettledFieldValidationResult>;\n // OPTIONAL like validateField, same custom-implementation contract: when\n // present (createForm always provides them), the hook exposes the\n // array-level server-error channel — a \"too many rows\" verdict from the\n // API is set and cleared from the hook that owns the array, the same\n // symmetry useField has had all along. Absent members make the returned\n // setError/clearError no-ops.\n setError?(path: string, errors: string | readonly string[]): void;\n clearErrors?(path?: string): void;\n // OPTIONAL, same contract: `setTouched` backs the hook's touched/onBlur\n // half of its useField parity, `setValue` backs the whole-array writes\n // (replace/update/clear). Absent members make those returned functions\n // no-ops, like setError/clearError above.\n setTouched?(path: string, touched?: boolean): void;\n setValue?(path: string, value: unknown): void;\n}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n // The resolved array path — the same convenience useField exposes.\n path: string;\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\n // The first array-level message, or undefined — same shorthand as\n // useField.firstError (the docs used to hand-roll error[0] here).\n firstError: string | undefined;\n // The array-level server channel, scoped to this path (see the\n // FieldArrayFormApi note: no-ops on custom implementations without the\n // optional members).\n setError: (errors: string | readonly string[]) => void;\n clearError: () => void;\n // The array's own flags, read at ITS path like useField reads a leaf's:\n // `touched` is the array path's flag (set by onBlur/setTouched, not by\n // a row's blur), `dirty` compares the whole array against its initial\n // value, `isValidating` is the array path's in-flight flag. A \"touched\n // array\" UI used to drop to selectors for these.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n setTouched: (touched?: boolean) => void;\n // Marks the array touched and validates it under the blur gate, the\n // same gate useField.onBlur applies; for a list whose \"control\" is the\n // add row or the group as a whole.\n onBlur: () => void;\n // Array-scoped validation, the same result shape as useField.validate.\n // On a hand-rolled FieldArrayFormApi without validateField it reports\n // valid without running anything (the member is optional, see above).\n validate: () => FieldValidationResult;\n // The awaitable form, the same shape as useField.validateAsync: for an\n // async array rule a caller wants a verdict from (a submit gate on the\n // list alone). Resolves valid without running on a hand-rolled\n // FieldArrayFormApi without validateFieldAsync.\n validateAsync: () => Promise<SettledFieldValidationResult>;\n push: (item: TItem) => void;\n remove: (index: number) => void;\n insert: (index: number, item: TItem) => void;\n move: (from: number, to: number) => void;\n swap: (a: number, b: number) => void;\n // The whole-array writes. `replace` and `clear` go through the form's\n // setValue, so ids come from reconciliation: a row REFERENCE that\n // survives keeps its id, a fresh row at the same index keeps that\n // index's id. `update` writes one row in place (the row keeps its id,\n // an edit at the same index), `prepend` is insert(0, item). All four\n // revalidate under the change gate like the index ops.\n replace: (items: readonly TItem[]) => void;\n update: (index: number, item: TItem) => void;\n prepend: (item: TItem) => void;\n clear: () => void;\n}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n // Unique per (form, path) entry, so ids minted for different arrays (or\n // for the same hook after a dynamic path switch) can never collide as\n // React keys.\n prefix: string;\n}>;\n\n// Stable reference for \"path holds no array yet\" — a fresh [] per selector\n// run would defeat useShallow and re-render on every store change.\nconst EMPTY_ITEMS: readonly never[] = [];\n\n// 1-based mint numbers for the positions needing a fresh id, in order.\n// BOTH id-derivation paths (value reconciliation in reconcileIds and the\n// exact op mappings in mappedIdState) number their mints through this one\n// helper, so the collision-free scheme — counter + consecutive 1-based\n// counts, counter advanced by the map's size — cannot diverge between them.\nconst mintNumbers = (\n needsMint: readonly boolean[],\n): ReadonlyMap<number, number> =>\n new Map(\n needsMint\n .flatMap((mint, i) => (mint ? [i] : []))\n .map((position, k) => [position, k + 1] as const),\n );\n\n// Derive a stable id per item by reconciling the live items against the\n// last-seen items. Ids follow items by identity/value, so resets and\n// mutations that bypass the array ops (setValue of a whole array, restore)\n// keep keys glued to their rows — not just length-preserving appends/\n// truncations. A same-index fallback keeps an edited row's id (editing\n// produces a fresh item reference at the same position) without remounting\n// it. This is the FALLBACK path: array ops (hook-issued OR imperative)\n// replay their exact recorded mappings via the core's op log first (see\n// deriveIds), because value matching cannot tell Object.is-equal rows\n// apart.\nconst reconcileIds = (prev: IdState, nextItems: readonly unknown[]): IdState => {\n if (prev.items === nextItems) return prev;\n if (\n prev.items.length === nextItems.length &&\n prev.items.every((item, i) => Object.is(item, nextItems[i]))\n ) {\n // Same rows, fresh array reference (a normalization pass, a server\n // refresh of unchanged data): the ids are unchanged but the anchor\n // MUST move to the live reference — a later op's record chains from\n // it, and a stale anchor would silently break replay back to value\n // matching (the duplicate-row bug all over again).\n return { ...prev, items: nextItems };\n }\n\n // Zeroth pass: a row that is Object.is-equal AT ITS OWN INDEX keeps its\n // own id before any value matching runs. Without this, duplicate\n // primitives steal each other's ids on an edit: with [\"\", \"\"] and a\n // keystroke into row 0 ([\"x\", \"\"]), the value pass below would hand row\n // 0's id to row 1 (the first \"\" bucket slot), row 0 would then mint, and\n // React would remount the input the user is typing in. Reserving\n // same-index identity first keeps row 1 on its own id and leaves row 0's\n // slot for the same-index leftover pass, which is what an edit needs.\n const keptAtIndex: readonly boolean[] = nextItems.map(\n (item, i) => i < prev.items.length && Object.is(item, prev.items[i]),\n );\n\n // Bucket the REMAINING prev positions by item so duplicate primitives\n // match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\n if (keptAtIndex[i] === true) return acc;\n const bucket = acc.get(item);\n if (bucket === undefined) {\n acc.set(item, [i]);\n } else {\n bucket.push(i);\n }\n return acc;\n }, new Map());\n\n // First pass: reuse the id of the matching prev item, consuming that slot so\n // each id is reused at most once (`shift` empties the bucket as we go).\n const matchedIds: readonly (string | null)[] = nextItems.map((item, i) => {\n if (keptAtIndex[i] === true) return prev.ids[i] ?? null;\n const prevIndex = buckets.get(item)?.shift();\n return prevIndex === undefined ? null : (prev.ids[prevIndex] ?? null);\n });\n\n // Second pass: an unmatched item reuses its SAME-INDEX leftover id (an\n // in-place edit keeps its row); any other leftover id belongs to a row\n // that is genuinely gone. Handing those out positionally would let a\n // remove-then-push in one batch key the new row with the deleted row's\n // id — a React reorder that resurrects the dead row's DOM state — so\n // they die and new items mint fresh ids instead. (Trade-off: an edit\n // that also MOVES in the same write remounts; value-identity matching\n // above already covers pure moves.)\n const leftoverAt = new Map(\n [...buckets.values()].flat().flatMap((i) => {\n const id = prev.ids[i];\n return id === undefined ? [] : ([[i, id]] as const);\n }),\n );\n const reused = matchedIds.map((id, i) => id ?? leftoverAt.get(i) ?? null);\n\n const mints = mintNumbers(reused.map((id) => id === null));\n const ids = reused.map(\n (id, i) => id ?? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`,\n );\n\n return {\n items: nextItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// Apply an exact index mapping to the id list: nextIds[i] =\n// prev.ids[mapping[i]], with -1 minting a fresh id (a new row). Returns null\n// — falling back to value reconciliation — unless every carried position's\n// live item is identity-equal to the recorded previous item, so a mapping\n// can never mis-key rows the store changed some other way (a refused\n// out-of-bounds op, an interleaved setValue).\nconst mappedIdState = (\n prev: IdState,\n mapping: readonly number[],\n liveItems: readonly unknown[],\n): IdState | null => {\n if (liveItems.length !== mapping.length) return null;\n const aligned = mapping.every((src, i) =>\n src === -1\n ? true\n : prev.ids[src] !== undefined &&\n Object.is(liveItems[i], prev.items[src]),\n );\n if (!aligned) return null;\n // (In practice an op mapping mints at most one row — push/insert — but\n // the numbering stays general via the shared scheme.)\n const mints = mintNumbers(mapping.map((src) => src === -1));\n const ids = mapping.map((src, i) =>\n src === -1\n ? `${prev.prefix}${prev.counter + (mints.get(i) ?? 0)}`\n : (prev.ids[src] as string),\n );\n return {\n items: liveItems,\n ids,\n counter: prev.counter + mints.size,\n prefix: prev.prefix,\n };\n};\n\n// One id state per (form store, path), shared by EVERY hook instance on\n// that array so sibling hooks always agree on row ids. A sanctioned\n// mutable-ref cache (like the core's subschemaCache): the entry is derived\n// bookkeeping — each commit is a pure function of a REAL store state, so a\n// discarded render leaves a sound (if not identical) state behind: rows may\n// remint where reuse was possible (a cosmetic remount), but a surviving row\n// can never receive another row's id. Entries are access-ordered and capped\n// so a long-lived store with churning dynamic paths (rows.N.tags) can't\n// accumulate snapshots forever; the WeakMap releases the rest with the\n// store.\ntype SharedIdEntry = { state: IdState };\ntype StoreIdEntries = { byPath: Map<string, SharedIdEntry>; seq: number };\n\n// Generous like path.ts's PARSE_CACHE_MAX: eviction of a MOUNTED array's\n// entry remints every row id (a full remount), so the cap is a backstop\n// against unbounded dynamic-path churn, never a working-set limit.\nconst MAX_ID_PATHS = 4096;\nconst sharedIdEntries = new WeakMap<object, StoreIdEntries>();\n\nconst storeIdEntries = (store: object): StoreIdEntries => {\n const existing = sharedIdEntries.get(store);\n const forStore = existing ?? { byPath: new Map(), seq: 1 };\n if (existing === undefined) sharedIdEntries.set(store, forStore);\n return forStore;\n};\n\nconst sharedIdEntry = (\n forStore: StoreIdEntries,\n path: string,\n): SharedIdEntry => {\n const existing = forStore.byPath.get(path);\n if (existing !== undefined) {\n // Re-insert to refresh recency, so eviction takes the longest-unused\n // path, not merely the oldest-created.\n forStore.byPath.delete(path);\n forStore.byPath.set(path, existing);\n return existing;\n }\n // Prefix from a PER-STORE sequence (deterministic per form, unlike a\n // module-global counter whose value depends on app-wide first-touch\n // order), so ids from different arrays — or a hook whose dynamic path\n // switches — can never collide as React keys.\n const created: SharedIdEntry = {\n state: {\n items: EMPTY_ITEMS,\n ids: [],\n counter: 0,\n prefix: `__zfa_${forStore.seq}_`,\n },\n };\n forStore.seq += 1;\n forStore.byPath.set(path, created);\n if (forStore.byPath.size > MAX_ID_PATHS) {\n const oldest = forStore.byPath.keys().next().value;\n if (oldest !== undefined) forStore.byPath.delete(oldest);\n }\n return created;\n};\n\n// Walk EVERY record in order, applying its exact mapping. A gap before a\n// record (a chain-breaking write between ops — though the core now clears\n// records at such writes, so gaps are rare) bridges by value to the\n// record's `from` first, so an op keeps its exactness no matter which side\n// of a whole-array write it fell on. The final hop to the live items — when\n// the last record didn't land there — reconciles by value too.\nconst walkOps = (\n start: IdState,\n items: readonly unknown[],\n ops: readonly ArrayOpRecord[],\n): IdState => {\n const walked = ops.reduce<IdState>((acc, op) => {\n const base = acc.items === op.from ? acc : reconcileIds(acc, op.from);\n return mappedIdState(base, op.mapping, op.to) ?? base;\n }, start);\n return walked.items === items ? walked : reconcileIds(walked, items);\n};\n\n// A row's DESCENDANT arrays have id entries of their own, keyed by path\n// (\"teams.0.members\"), so when the outer array reorders, the entry at\n// \"teams.2.members\" would otherwise meet team A's members with team C's\n// history: value reconciliation finds nothing it knows, the same-index\n// fallback hands the first rows the OTHER team's ids, the rest remint, and\n// React remounts inputs a user may be typing in. Move the entries with their\n// rows instead. The outer walk already decided which row went where (the\n// id that was at index j is now at index i, or is gone), so the re-seat\n// follows the ids, not the op: it is the same for an exact op mapping and\n// for a whole-array write that reconciled by value. A vacated slot's\n// entries are dropped so a later row at that index starts clean rather\n// than inheriting a dead row's ids. Entries at an index the previous state\n// never had (a hook mounted on a not-yet-existing slot) are left where\n// they are. Only an outer hook runs this (it derives before its rows' inner\n// hooks, parent before child); inner-only trees keep today's value\n// fallback.\nconst reseatDescendants = (\n forStore: StoreIdEntries,\n path: string,\n prev: IdState,\n next: IdState,\n): void => {\n if (prev.ids.length === 0) return;\n const newIndexById = new Map(next.ids.map((id, i) => [id, i] as const));\n // old index -> new index; undefined marks a removed row. Decided before\n // the entry map is scanned: a keystroke in any row re-derives the outer\n // ids (new array reference, same rows) and must not pay for the scan.\n const moves = prev.ids.map((id) => newIndexById.get(id));\n if (moves.every((to, from) => to === from)) return;\n const prefix = `${path}.`;\n const descendants = [...forStore.byPath.keys()].filter((key) =>\n key.startsWith(prefix),\n );\n const relocations = descendants.flatMap((key) => {\n const rest = key.slice(prefix.length);\n const dot = rest.indexOf(\".\");\n const segment = dot === -1 ? rest : rest.slice(0, dot);\n const from = Number(segment);\n if (!/^\\d+$/.test(segment) || from >= prev.ids.length) return [];\n const entry = forStore.byPath.get(key);\n if (entry === undefined) return [];\n const to = moves[from];\n const target =\n to === undefined\n ? undefined\n : `${prefix}${to}${dot === -1 ? \"\" : rest.slice(dot)}`;\n return [{ key, target, entry }];\n });\n // Clear every moving source first, then seat the survivors: a swap's two\n // entries trade keys, so interleaving the two passes would overwrite one\n // of them before it was read.\n relocations.forEach(({ key }) => forStore.byPath.delete(key));\n relocations.forEach(({ target, entry }) => {\n if (target !== undefined) forStore.byPath.set(target, entry);\n });\n};\n\nconst deriveIds = (\n store: object,\n path: string,\n items: readonly unknown[],\n): IdState => {\n const forStore = storeIdEntries(store);\n const entry = sharedIdEntry(forStore, path);\n if (entry.state.items === items) return entry.state;\n const ops = arrayOpsFor(store, path);\n // The walk consumes every record, so the log is spent bookkeeping\n // afterwards — clear it, which also keeps ring composition from ever\n // merging a record a consumer is still anchored at. (The one residual:\n // a render discarded between clear and commit re-derives the final hop\n // by value — sound ids, possibly reminted where reuse was possible.)\n if (ops.length > 0) clearArrayOps(store, path);\n const next = walkOps(entry.state, items, ops);\n reseatDescendants(forStore, path, entry.state, next);\n entry.state = next;\n return next;\n};\n\n// The readable-error trap-guard, mirroring useField's: an explicit type\n// argument (`useFieldArray<Item>(typedForm, \"users\")`) arity-matches ONLY\n// the one-type-parameter overloads, and the structural one's brand then\n// rejects the Form with a baffling \"... not assignable to type\n// 'undefined'\". The error overload below intercepts that shape — TItem\n// defaults to this unexported sentinel, which inferred calls can never\n// escape (TItem has no inference site), collapsing `path` to `never`; an\n// explicit TItem on a schema-carrying form instead types `path` as a\n// string-literal instruction the compiler blames the path argument with.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useField (and is just as deliberate): the\n// typed-path overload sits last so a typo'd path on a Form<TSchema> is\n// blamed on the path argument against the full FieldPath union, and the\n// `schema?: undefined` brand forces a real Form past the widened structural\n// overload — without it, `useFieldArray(form, \"users\")` would bind there\n// and return UseFieldArrayReturn<unknown> instead of inferring the item\n// type from the path. Schema-less FieldFormApi forms keep the explicit\n// TItem parameter (there is nothing to infer from).\n// The form is matched structurally (schema witness + typed store) instead\n// of as Form<TSchema, D>: every Form is assignable regardless of its\n// pathDepth, and keeping this overload at ONE type parameter preserves\n// explicit instantiation expressions (`typeof useFieldArray<Schema,\n// \"tags\">`) — TS applies explicit type args to every arity-compatible\n// overload, so a second parameter here would check \"tags\" against it.\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: FieldArrayFormApi &\n Readonly<{\n schema: TSchema;\n store: ReadonlyStore<FormState<z.input<TSchema>>>;\n }>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\n// The trap-guard (see InferredTypeArg above): explicit type argument on a\n// schema-carrying form → readable error on the path argument; inferred\n// calls fall through (path collapses to never).\nexport function useFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n path: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the path\",\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem>;\n// D last with a default (P's constraint forward-references it), preserving\n// the arity of explicit instantiations like\n// `useFieldArray<typeof schema, \"tags\">`. P is an ARRAY path (the core's\n// ArrayFieldPath: variable-length arrays only, optional/nullable included):\n// a scalar path used to bind here with a never-typed item (every write an\n// error, the hook itself not), and a tuple path bound with the tuple's\n// element union while the core refused the same push. The item type comes\n// from the core's ArrayItemOf, so the hook and form.arrayPush agree.\n// The `& string` is load-bearing: P's constraint depends on D, which is\n// inferred from the SAME call, so while P is being inferred the constraint\n// is a deferred conditional type and TS cannot see that it is made of\n// string literals. Without a visible primitive constraint the \"users\"\n// candidate widens to `string`, fails the constraint, and P falls back to\n// the whole array-path union (every item type at once). Intersecting with\n// string keeps the literal, exactly as FieldPath's own shape happened to.\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends ArrayFieldPath<z.input<TSchema>, D> & string,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: FieldPathArg<unknown>,\n): UseFieldArrayReturn<TItem> {\n const path = useStore(form.store, (state) =>\n typeof pathArg === \"function\" ? pathArg(state) : pathArg,\n );\n const slice = useStore(\n form.store,\n useShallow((state) => {\n const value = getAtPath(state.values, path);\n return {\n items: (Array.isArray(value) ? value : EMPTY_ITEMS) as readonly TItem[],\n // Own-key read, like useField: an array named \"constructor\" must\n // not read Object as its error list.\n error: entryAt(state.errors, path),\n touched: flagAt(state.touched, path),\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: flagAt(state.isValidating, path),\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Ids derive from the shared per-(store, path) entry: the core's op log\n // replays each array op's exact index mapping (hook-issued or imperative\n // — both go through applyArrayOp, which records them), and value\n // reconciliation covers everything else (setValue of a whole array,\n // restore, resets). Deriving during render is safe because the entry is\n // a convergent cache — every commit is a pure function of a real store\n // state — and cheap because it early-exits on the same items reference.\n // All hook instances on the same path read the same entry, so their ids\n // can never disagree.\n const ids = deriveIds(form.store, path, items).ids;\n\n // After every op, revalidate the ARRAY path under the exact change-trigger\n // gate useField.setValue applies (same shouldValidateOn call), so a visible\n // array-level error (z.array().min()) tracks push/remove instead of going\n // stale. The core self-routes async schemas (validateField returns\n // { kind: \"pending\" } having already started the async pass); nobody\n // awaits that pass, so a throwing array refine is reported the way\n // useField's triggers report it instead of escaping as an unhandled\n // rejection. validateField is probed: a hand-rolled FieldArrayFormApi\n // without it skips revalidation instead of crashing. The IMPERATIVE\n // form.arrayPush/arrayRemove stay non-revalidating on purpose — the same\n // layering as form.setValue (raw write) vs useField.setValue (write + gate).\n const validateNow = useCallback(() => {\n const result = form.validateField?.(path);\n if (result?.kind === \"pending\") {\n void result.promise.catch(reportBackgroundFailure);\n }\n }, [form, path]);\n\n const revalidate = useCallback(() => {\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n flagAt(state.touched, path),\n )\n ) {\n validateNow();\n }\n }, [form, path, validateNow]);\n\n const push = useCallback(\n (item: TItem) => {\n form.arrayPush(path, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const remove = useCallback(\n (index: number) => {\n form.arrayRemove(path, index);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => {\n form.arrayInsert(path, index, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const move = useCallback(\n (from: number, to: number) => {\n form.arrayMove(path, from, to);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const swap = useCallback(\n (a: number, b: number) => {\n form.arraySwap(path, a, b);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const fields = useMemo<readonly FieldArrayEntry<TItem>[]>(\n () =>\n items.map((value, index) => ({\n id: ids[index] ?? `__zfa_fallback_${index}`,\n value,\n })),\n [items, ids],\n );\n\n const setError = useCallback(\n // Same string-shorthand normalization as useField.setError, so custom\n // implementations typed for readonly string[] never receive a bare\n // string.\n (errors: string | readonly string[]) =>\n form.setError?.(path, typeof errors === \"string\" ? [errors] : errors),\n [form, path],\n );\n\n const clearError = useCallback(() => form.clearErrors?.(path), [form, path]);\n\n const setTouched = useCallback(\n (touched?: boolean) => form.setTouched?.(path, touched),\n [form, path],\n );\n\n // useField.onBlur without the debounce: array-level rules are cheap\n // (length, uniqueness) and the hook takes no debounceMs option.\n const onBlur = useCallback(() => {\n form.setTouched?.(path, true);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"blur\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n true,\n )\n ) {\n validateNow();\n }\n }, [form, path, validateNow]);\n\n const validate = useCallback(\n (): FieldValidationResult =>\n form.validateField?.(path) ?? { kind: \"valid\" },\n [form, path],\n );\n\n const validateAsync = useCallback(\n (): Promise<SettledFieldValidationResult> =>\n form.validateFieldAsync?.(path) ?? Promise.resolve({ kind: \"valid\" }),\n [form, path],\n );\n\n const replace = useCallback(\n (next: readonly TItem[]) => {\n form.setValue?.(path, next);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const update = useCallback(\n (index: number, item: TItem) => {\n // Bounds-checked like the index ops: a write past the end went\n // through setValue, which filled the gap with null holes that crash\n // row renders and fail the schema, with no warning.\n const current = getAtPath(form.store.getState().values, path);\n const length = Array.isArray(current) ? current.length : 0;\n if (!Number.isInteger(index) || index < 0 || index >= length) {\n console.warn(\n `[formstand] array op on \"${path}\" with an out-of-range or non-integer index (length ${String(length)}). Operation skipped.`,\n );\n return;\n }\n form.setValue?.(`${path}.${String(index)}`, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const prepend = useCallback(\n (item: TItem) => {\n form.arrayInsert(path, 0, item);\n revalidate();\n },\n [form, path, revalidate],\n );\n\n const clear = useCallback(() => {\n form.setValue?.(path, []);\n revalidate();\n }, [form, path, revalidate]);\n\n return useMemo(\n () => ({\n path,\n fields,\n items,\n length: items.length,\n error,\n firstError: error?.[0],\n setError,\n clearError,\n touched: slice.touched,\n dirty: slice.dirty,\n isValidating: slice.isValidating,\n setTouched,\n onBlur,\n validate,\n validateAsync,\n push,\n remove,\n insert,\n move,\n swap,\n replace,\n update,\n prepend,\n clear,\n }),\n [\n path,\n fields,\n items,\n error,\n setError,\n clearError,\n slice.touched,\n slice.dirty,\n slice.isValidating,\n setTouched,\n onBlur,\n validate,\n validateAsync,\n push,\n remove,\n insert,\n move,\n swap,\n replace,\n update,\n prepend,\n clear,\n ],\n );\n}\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport type { UnionValueAt, VariantFieldValue } from \"./useVariantField\";\n\n// The array twin of useVariantField. A z.array that lives in ONE variant of\n// a discriminated union (\"asphalt\" pavements have `lights`, \"grass\" ones do\n// not) sits at a path FieldPath omits, since FieldPath on a union offers\n// only the keys every member shares, so useFieldArray(form, \"top.lights\")\n// is a compile error even though the runtime binding is ordinary. This hook\n// binds `${unionPath}.${field}` and types the rows from the variants that\n// declare the array:\n//\n// const kind = useField(form, \"top.kind\"); // discriminant\n// const lights = useVariantFieldArray(form, \"top\", \"lights\");\n// // -> UseFieldArrayReturn<{ color: string }>, rendered when kind.value === \"asphalt\"\n//\n// Like useVariantField, call it unconditionally and render the matching\n// rows based on the discriminant; its ops write the variant path whatever\n// the active variant is, so gate the UI, not the hook. Runtime behavior is\n// exactly useFieldArray on the joined path, row ids included.\n//\n// The field argument is a variant sub-PATH, not just a key, the same way\n// useVariantField's is: \"lights\", \"spec.lights\" (an array inside a\n// variant-only object), or a row template such as `lights.${index}.bulbs`\n// for an array nested in the rows of another variant array. formstand-gen\n// emits this hook for arrays inside union variants, the one shape that\n// used to degrade to a TODO.\n\n// The variable-length array paths of union `V` that are NOT rooted at a\n// common key. Built from the core's ArrayFieldPath, distributed over the\n// members like VariantFieldPath distributes FieldPath, so optional and\n// nullable arrays and template paths with numeric holes all qualify. A\n// common-key array binds with plain useFieldArray, which types it from the\n// union directly; offering it here would duplicate that hook.\nexport type VariantArrayFieldPath<\n V,\n D extends PathDepth = DefaultPathDepth,\n> = Exclude<\n V extends unknown ? ArrayFieldPath<V, D> : never,\n (keyof V & string) | `${keyof V & string}.${string}`\n> &\n string;\n\n// The trap-guard sentinel, mirroring useVariantField's: an explicit type\n// argument on a schema-typed form lands on the one-type-parameter overload\n// below and reads the instruction instead of a baffling structural error.\ndeclare const inferredCallsOnly: unique symbol;\ninterface InferredTypeArg {\n readonly [inferredCallsOnly]: typeof inferredCallsOnly;\n}\n\n// Overload order mirrors useVariantField: the trap guard first, the widened\n// structural overload for schema-less forms next, the typed overload LAST\n// so a bad union path or field on a Form<TSchema> is blamed on that\n// argument against the real union.\nexport function useVariantFieldArray<TItem = InferredTypeArg>(\n form: FieldArrayFormApi & Readonly<{ schema: z.ZodType }>,\n unionPath: TItem extends InferredTypeArg\n ? never\n : \"Remove the explicit type argument: a schema-typed form infers the item type from the union path and field\",\n field: string,\n): UseFieldArrayReturn<TItem>;\nexport function useVariantFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n unionPath: string,\n field: string,\n): UseFieldArrayReturn<TItem>;\n// D is recovered from the form argument and sits last with a default, so\n// explicit instantiation expressions keep their arity. TField's constraint\n// uses the DEFAULT depth on purpose, the same reasoning as useVariantField:\n// a constraint may not consume a later type parameter before inference\n// resolves it, and variant subtrees are shallow by construction.\nexport function useVariantFieldArray<\n TSchema extends z.ZodType,\n P extends string,\n TField extends VariantArrayFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n unionPath: P,\n field: TField,\n): UseFieldArrayReturn<\n ArrayItemOf<VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField>>\n>;\nexport function useVariantFieldArray(\n form: FieldArrayFormApi,\n unionPath: string,\n field: string,\n): UseFieldArrayReturn<unknown> {\n // Structural string-path bind: the joined path is exactly where the\n // variant's array lives; only its TYPE was unreachable through\n // ArrayFieldPath, so the runtime is ordinary useFieldArray.\n return useFieldArray(\n form as FieldArrayFormApi & { readonly schema?: undefined },\n `${unionPath}.${field}`,\n );\n}\n","import { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\nexport const useFormError = (\n form: FormStateApi,\n): readonly string[] | undefined =>\n useStore(\n form.store,\n useShallow((state) => state.errors[\"\"]),\n );\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Whole-values subscription in render — sugar for\n// useFormSelector(form, (s) => s.values), the render-side sibling of\n// form.watchValues. The classic use is derived rendering driven by live\n// form values (a map re-rendering as coordinates are edited).\n//\n// Deliberately NOT shallow-compared: the store replaces the values object\n// immutably on every value change, so reference equality (useStore's\n// default Object.is) is exactly right — one comparison, re-render if and\n// only if some value changed. Unrelated state changes (touched, errors,\n// isSubmitting) leave the values reference alone and cause no re-render.\n\nexport function useFormValues<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>): z.input<TSchema>;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above — same rule as\n// useFormSelector. Structural forms have nothing to infer from and read\n// `unknown`.\nexport function useFormValues(\n form: FormStateApi & { readonly schema?: undefined },\n): unknown;\nexport function useFormValues(form: FormStateApi): unknown {\n return useStore(form.store, (state) => state.values);\n}\n","import { useMemo, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\n\n// Composite fields: ONE control backed by SEVERAL schema paths — a\n// coordinate pair behind a single map-driven input, a range's min/max, a\n// date span. Binding each path with its own useField works, but the\n// coordination (a combined error line, one blur, one touched/dirty answer)\n// is the same hand-written boilerplate every time. useFields binds the\n// paths together:\n//\n// const location = useFields(form, [\"latitude\", \"longitude\"]);\n// const [latitude, longitude] = location.fields; // full UseFieldReturns\n// <span>{location.firstError}</span> // combined error line\n//\n// Each element of `fields` is a REAL UseFieldReturn — it spreads into the\n// same prop builders and Bound components a solo binding would — and the\n// wrapper adds the combined view: errors merged in path order (deduped, so\n// a cross-field superRefine that stamps both paths reads once), touched /\n// dirty / isValidating as \"any of them\", and one onBlur that blurs every\n// path (each under the form's own validation mode gate).\n//\n// THE PATHS TUPLE IS PART OF THE HOOK CONTRACT: its length and order must\n// be stable across renders, because it expands to exactly that many hook\n// calls. The hook enforces it at the very render that broke the contract\n// (pinned by the test suite), with its own message ahead of React's\n// \"Rendered fewer/more hooks\" error, so pass a literal or a module-level\n// constant, never a filtered array.\n\nexport type UseFieldsReturn<TFields extends readonly unknown[]> = Readonly<{\n fields: TFields;\n // Every bound path's messages, merged in path order and deduped.\n error: readonly string[] | undefined;\n firstError: string | undefined;\n // \"Any of them\": one answer for the composite control's chrome.\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n // Blurs every bound path — each under the form's validation mode gate,\n // so the composite behaves like one control losing focus.\n onBlur: () => void;\n}>;\n\n// Schema-less forms keep the caller-typed shape (the `schema?: undefined`\n// brand forces a real Form past this overload, mirroring useField).\nexport function useFields(\n form: FieldFormApi & { readonly schema?: undefined },\n paths: readonly string[],\n options?: UseFieldOptions,\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]>;\n// The typed overload: `paths` is a const-inferred tuple and `fields` maps\n// it position-for-position, so destructuring keeps each path's exact value\n// type. D is recovered from the form (the \"~pathDepth\" marker), like the\n// sibling hooks.\nexport function useFields<\n TSchema extends z.ZodType,\n const P extends readonly FieldPath<z.input<TSchema>, D>[],\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n paths: P,\n // One options bag for every bound path (a composite control debounces\n // as one control).\n options?: UseFieldOptions,\n): UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\nexport function useFields(\n form: FieldFormApi,\n paths: readonly string[],\n options?: UseFieldOptions,\n): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> {\n // The arity the hook was first called with, held in a hook slot that\n // sits BEFORE the per-path calls: a tuple that changes length is caught\n // here with a message that names the hook, before the shifted hook\n // slots below would surface as React's generic hooks-count error (or,\n // with the memo below, as a crash inside React's dependency compare).\n const [arity] = useState(paths.length);\n if (paths.length !== arity) {\n throw new Error(\n `[formstand] useFields: the paths tuple changed length (${String(arity)} to ${String(paths.length)}); its length and order must be stable across renders, so pass a literal or a module-level constant.`,\n );\n }\n const fields = paths.map((path) =>\n // eslint-disable-next-line react-hooks/rules-of-hooks -- a fixed hook count by the stable-arity contract above; each element must be a REAL UseFieldReturn so it spreads into the prop builders\n useField(\n form as FieldFormApi & { readonly schema?: undefined },\n path,\n options,\n ),\n );\n // Memoized on the bound fields themselves (each a memoized\n // UseFieldReturn), so the composite keeps its identity, its `fields`\n // array and its onBlur across renders that change none of them, the\n // way useField and useFieldArray do; a fresh object per render made\n // every memoized consumer of the composite re-render on every store\n // write. The tuple is a fixed-length dependency list by the arity\n // check above, which is what the literal-array lint rule exists to\n // guarantee.\n return useMemo(() => {\n const merged = [\n ...new Set(fields.flatMap((field) => field.error ?? [])),\n ];\n return {\n fields,\n error: merged.length > 0 ? merged : undefined,\n firstError: merged[0],\n touched: fields.some((field) => field.touched),\n dirty: fields.some((field) => field.dirty),\n isValidating: fields.some((field) => field.isValidating),\n onBlur: () => {\n fields.forEach((field) => {\n field.onBlur();\n });\n },\n };\n // eslint-disable-next-line react-hooks/use-memo, react-hooks/exhaustive-deps -- the stable-arity tuple IS the dependency list (see the arity check above)\n }, fields);\n}\n","import type { z } from \"zod\";\nimport { useStore } from \"zustand/react\";\nimport type { Form } from \"../core/createForm\";\nimport { isFieldDirty } from \"../core/equality\";\nimport type { DefaultPathDepth, FieldPath, PathDepth } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport { isPathOrChild } from \"../core/validation\";\nimport type { FormStateApi } from \"./useFormSelector\";\n\n// Both flag hooks take an optional path and scope to it with the same\n// prefix semantics as the rest of the library (isPathOrChild): \"shipping\"\n// covers \"shipping.city\". Omitted path = whole form. Overload order mirrors\n// useField: the typed-path overload sits last so a typo'd path on a\n// Form<TSchema> is blamed against the full FieldPath union, and the\n// `schema?: undefined` brand keeps real Forms off the widened string\n// overload. Subscriptions are boolean-only — the component re-renders when\n// the flag flips, not on every keystroke (unlike useField(...).dirty).\n\n// Derived from the values (memoized per values reference), so it always\n// agrees with per-field dirty reads. The scoped form compares just the\n// subtree at `path` — a missing path on both sides reads as clean.\nexport function useIsDirty(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsDirty<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsDirty(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) =>\n path === undefined || path === \"\"\n ? isFieldDirty(state.values, state.initialValues)\n : isFieldDirty(\n getAtPath(state.values, path),\n getAtPath(state.initialValues, path),\n ),\n );\n}\n\n// \"No errors currently in the merged map\" (not a fresh validation pass);\n// the scoped form only looks at errors at or under `path`, including the\n// path's own key (array-level errors like `items` count for path \"items\").\nexport function useIsValid(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValid<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n // A loop rather than Object.entries().some(): this selector re-runs on\n // EVERY store change, and the loop exits at the first error without\n // materializing an entries array for a map that is usually empty.\n for (const k in state.errors) {\n const errs = state.errors[k];\n if (\n errs !== undefined &&\n errs.length > 0 &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return false;\n }\n }\n return true;\n });\n}\n\n// Whether async validation is in flight — form-level (a whole-form pass,\n// or any field's own pass) or scoped to a path subtree, boolean-only like\n// the sibling flags. The form-level read was previously reachable only\n// through a selector, asymmetric with useIsSubmitting.\nexport function useIsValidating(\n form: FormStateApi & { readonly schema?: undefined },\n path?: string,\n): boolean;\nexport function useIsValidating<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>, D>,\n D extends PathDepth = DefaultPathDepth,\n>(form: Form<TSchema, D>, path?: P): boolean;\nexport function useIsValidating(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\n if (path === undefined || path === \"\") {\n if (state.isValidatingForm) return true;\n }\n // Same first-hit loop rationale as useIsValid: this selector re-runs\n // on every store change over a usually-empty map.\n for (const k in state.isValidating) {\n if (\n state.isValidating[k] === true &&\n (path === undefined || path === \"\" || isPathOrChild(k, path))\n ) {\n return true;\n }\n }\n return false;\n });\n}\n\nexport const useIsSubmitting = (form: FormStateApi): boolean =>\n useStore(form.store, (state) => state.isSubmitting);\n\nexport const useSubmitCount = (form: FormStateApi): number =>\n useStore(form.store, (state) => state.submitCount);\n","import type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n ArrayItemOf,\n DefaultPathDepth,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport type { PersistHandle, PersistOptions } from \"../core/persist\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldFormApi,\n type UseFieldOptions,\n type UseFieldReturn,\n useField,\n} from \"./useField\";\nimport {\n type UnionValueAt,\n type VariantFieldValue,\n type VariantFieldPath,\n useVariantField,\n} from \"./useVariantField\";\nimport {\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport {\n type VariantArrayFieldPath,\n useVariantFieldArray,\n} from \"./useVariantFieldArray\";\nimport { useFormError } from \"./useFormError\";\nimport { useFormValues } from \"./useFormValues\";\nimport {\n type FormStep,\n type UseFormStepsReturn,\n useFormSteps,\n} from \"./useFormSteps\";\nimport { type UseFieldsReturn, useFields } from \"./useFields\";\nimport {\n type FormActionHandler,\n type FormActionOptions,\n type FormActionStateHandler,\n useFormAction,\n useFormActionState,\n} from \"./useFormAction\";\nimport { usePersistForm } from \"./usePersistForm\";\nimport {\n useIsDirty,\n useIsSubmitting,\n useIsValid,\n useIsValidating,\n useSubmitCount,\n} from \"./useFormFlags\";\nimport {\n type FormStateApi,\n useFormSelector,\n useFormSelectorShallow,\n} from \"./useFormSelector\";\n\n// createFormHooks(form, name?) — every hook, pre-wired to one form. The\n// context-free way to share a form: create it at module scope, export the\n// returned hooks, and no component ever passes `form` through props or a\n// provider. The optional name is baked into the hook names (both at the\n// type level and at runtime), so a module reads like a domain API:\n//\n// const form = createForm(invoiceSchema, { initialValues });\n// export const { useInvoiceField, useInvoiceFieldArray, useInvoiceIsDirty } =\n// createFormHooks(form, \"invoice\");\n//\n// Typed paths survive the binding: useInvoiceField(\"customer\") infers the\n// value type from the schema, and a typo'd path is a compile error.\n//\n// Every hook that takes a form is bound, the form-actions bridges and\n// usePersistForm included (they were the three the first cut skipped\n// while the docs promised every hook). The bound names drop the \"Form\"\n// of the originals, as the others do: useFormAction becomes\n// use{Name}Action, useFormActionState use{Name}ActionState, and\n// usePersistForm use{Name}Persist. Without a name the keys are the bare\n// spellings (useAction, useActionState, usePersist), which shadow the\n// library's own exports and, for useActionState, React's, wherever they\n// are destructured; a name is the better habit.\n//\n// Reach for this when the form is a genuine module-level singleton (one\n// instance for the app's lifetime — settings, a global compose box). For a\n// form that mounts per page/dialog with its own lifecycle, use useForm and\n// createFormContext instead: a module singleton never unmounts, so state\n// persists across navigations until you reset() it.\n\n// The bound signatures mirror the unbound hooks minus the form parameter;\n// the typed-path call signature sits last for the same error-blame reason\n// as the originals.\nexport type BoundUseField<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>, D>>(\n path: P,\n options?: UseFieldOptions,\n ): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\n};\n\n// The variant-field accessor bound to the form: the type math (variant\n// paths, value across resolving variants) lives in useVariantField; the\n// bound signature just drops the form parameter.\nexport type BoundUseVariantField<TSchema extends z.ZodType> = <\n P extends string,\n // Default depth, matching the unbound hook (see its comment on why the\n // constraint cannot ride the form's D).\n TField extends VariantFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n options?: UseFieldOptions,\n) => UseFieldReturn<\n VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField> | undefined\n>;\n\n// The variant-array accessor bound to the form, the array twin of\n// BoundUseVariantField: the type math lives in useVariantFieldArray.\nexport type BoundUseVariantFieldArray<TSchema extends z.ZodType> = <\n P extends string,\n TField extends VariantArrayFieldPath<UnionValueAt<z.input<TSchema>, P>>,\n>(\n unionPath: P,\n field: TField,\n) => UseFieldArrayReturn<\n ArrayItemOf<VariantFieldValue<UnionValueAt<z.input<TSchema>, P>, TField>>\n>;\n\nexport type BoundUseFieldArray<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n ): UseFieldArrayReturn<unknown>;\n // Array paths only, like the unbound hook's typed overload.\n <P extends ArrayFieldPath<z.input<TSchema>, D>>(\n path: P,\n ): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\n};\n\nexport type BoundUseSelector<TSchema extends z.ZodType> = <U>(\n selector: (state: FormState<z.input<TSchema>>) => U,\n) => U;\n\nexport type BoundUseFlag<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = (\n path?: FieldPath<z.input<TSchema>, D>,\n) => boolean;\n\n// The form-actions bridges and persistence, bound: the unbound signatures\n// minus the form argument, like every other entry.\nexport type BoundUseAction<TSchema extends z.ZodType> = (\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n) => (formData: FormData) => Promise<void>;\n\nexport type BoundUseActionState<TSchema extends z.ZodType> = <S>(\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n) => [state: S, formAction: (formData: FormData) => void, isPending: boolean];\n\nexport type BoundUsePersist<TSchema extends z.ZodType> = (\n options: PersistOptions<TSchema>,\n) => PersistHandle;\n\n// One single-key mapped type per hook, intersected: template-literal keys\n// carry the capitalized name, so the destructured names are typo-checked\n// ({ useInvoceField } fails to compile against createFormHooks(f, \"invoice\")).\nexport type FormHooks<\n TSchema extends z.ZodType,\n N extends string,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<\n { [K in `use${Capitalize<N>}Field`]: BoundUseField<TSchema, D> } & {\n [K in `use${Capitalize<N>}VariantField`]: BoundUseVariantField<TSchema>;\n } & {\n [K in `use${Capitalize<N>}FieldArray`]: BoundUseFieldArray<TSchema, D>;\n } & {\n [K in `use${Capitalize<N>}VariantFieldArray`]: BoundUseVariantFieldArray<TSchema>;\n } & { [K in `use${Capitalize<N>}Selector`]: BoundUseSelector<TSchema> } & {\n [K in `use${Capitalize<N>}SelectorShallow`]: BoundUseSelector<TSchema>;\n } & {\n [K in `use${Capitalize<N>}Error`]: () => readonly string[] | undefined;\n } & { [K in `use${Capitalize<N>}IsDirty`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsValid`]: BoundUseFlag<TSchema, D>;\n } & { [K in `use${Capitalize<N>}IsValidating`]: BoundUseFlag<TSchema, D> } & {\n [K in `use${Capitalize<N>}IsSubmitting`]: () => boolean;\n } & {\n [K in `use${Capitalize<N>}SubmitCount`]: () => number;\n } & { [K in `use${Capitalize<N>}Values`]: () => z.input<TSchema> } & {\n [K in `use${Capitalize<N>}Fields`]: BoundUseFields<TSchema, D>;\n } & {\n [K in `use${Capitalize<N>}Steps`]: (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ) => UseFormStepsReturn;\n } & { [K in `use${Capitalize<N>}Action`]: BoundUseAction<TSchema> } & {\n [K in `use${Capitalize<N>}ActionState`]: BoundUseActionState<TSchema>;\n } & { [K in `use${Capitalize<N>}Persist`]: BoundUsePersist<TSchema> }\n>;\n\n// The bound composite-fields hook: same const-inferred tuple and\n// position-typed fields as the plain useFields.\nexport type BoundUseFields<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = <const P extends readonly FieldPath<z.input<TSchema>, D>[]>(\n paths: P,\n options?: UseFieldOptions,\n) => UseFieldsReturn<{\n readonly [K in keyof P]: UseFieldReturn<\n FieldValue<z.input<TSchema>, P[K] & string>\n >;\n}>;\n\n// Runtime twin of TypeScript's Capitalize<N> (ASCII names; a leading\n// non-letter passes through unchanged in both).\nconst capitalize = (name: string): string =>\n name.length === 0 ? name : name.charAt(0).toUpperCase() + name.slice(1);\n\n// D (the form's typed-path depth budget) sits LAST so existing explicit\n// instantiations — createFormHooks<Schema, \"invoice\"> — keep compiling; it\n// is inferred from the form argument anyway.\nexport const createFormHooks = <\n TSchema extends z.ZodType,\n N extends string = \"\",\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n name?: N,\n): FormHooks<TSchema, N, D> => {\n // Calling the unbound hooks through a structural view (no `schema`\n // property) binds their widened overloads — the precise typing is\n // re-established by the Bound* signatures above, which the type tests pin.\n const structural: FieldFormApi & FieldArrayFormApi & FormStateApi = form;\n\n const useBoundField = (\n path: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown> => useField(structural, path, options);\n\n const useBoundVariantField = (\n unionPath: string,\n field: string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown> =>\n useVariantField(\n structural as FieldFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n options,\n );\n\n const useBoundFieldArray = (\n path: string | ((state: FormState<unknown>) => string),\n ): UseFieldArrayReturn<unknown> => useFieldArray(structural, path);\n\n const useBoundVariantFieldArray = (\n unionPath: string,\n field: string,\n ): UseFieldArrayReturn<unknown> =>\n useVariantFieldArray(\n structural as FieldArrayFormApi & { readonly schema?: undefined },\n unionPath,\n field,\n );\n\n const useBoundSelector = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelector(structural, selector);\n\n const useBoundSelectorShallow = <U,>(\n selector: (state: FormState<unknown>) => U,\n ): U => useFormSelectorShallow(structural, selector);\n\n const useBoundError = (): readonly string[] | undefined =>\n useFormError(structural);\n\n const useBoundIsDirty = (path?: string): boolean =>\n useIsDirty(structural, path);\n\n const useBoundIsValid = (path?: string): boolean =>\n useIsValid(structural, path);\n\n const useBoundIsValidating = (path?: string): boolean =>\n useIsValidating(structural, path);\n\n const useBoundIsSubmitting = (): boolean => useIsSubmitting(structural);\n\n const useBoundValues = (): unknown => useFormValues(structural);\n\n const useBoundFields = (\n paths: readonly string[],\n options?: UseFieldOptions,\n ): UseFieldsReturn<readonly UseFieldReturn<unknown>[]> =>\n useFields(\n structural as FieldFormApi & { readonly schema?: undefined },\n paths,\n options,\n );\n\n const useBoundSubmitCount = (): number => useSubmitCount(structural);\n\n const useBoundSteps = (\n steps: readonly FormStep<z.input<TSchema>, D>[],\n ): UseFormStepsReturn => useFormSteps(form, steps);\n\n const useBoundAction = (\n onValid: FormActionHandler<TSchema>,\n options?: FormActionOptions,\n ): ((formData: FormData) => Promise<void>) =>\n useFormAction(form, onValid, options);\n\n const useBoundActionState = <S,>(\n action: FormActionStateHandler<TSchema, S>,\n initialState: S,\n options?: FormActionOptions,\n ): [state: S, formAction: (formData: FormData) => void, isPending: boolean] =>\n useFormActionState(form, action, initialState, options);\n\n const useBoundPersist = (options: PersistOptions<TSchema>): PersistHandle =>\n usePersistForm(form, options);\n\n const prefix = capitalize(name ?? \"\");\n // Computed keys erase to an index signature, so the literal is asserted\n // to the mapped FormHooks type — the real contract, verified by type\n // tests on both the key names and the bound signatures.\n return {\n [`use${prefix}Field`]: useBoundField,\n [`use${prefix}VariantField`]: useBoundVariantField,\n [`use${prefix}FieldArray`]: useBoundFieldArray,\n [`use${prefix}VariantFieldArray`]: useBoundVariantFieldArray,\n [`use${prefix}Selector`]: useBoundSelector,\n [`use${prefix}SelectorShallow`]: useBoundSelectorShallow,\n [`use${prefix}Error`]: useBoundError,\n [`use${prefix}IsDirty`]: useBoundIsDirty,\n [`use${prefix}IsValid`]: useBoundIsValid,\n [`use${prefix}IsValidating`]: useBoundIsValidating,\n [`use${prefix}IsSubmitting`]: useBoundIsSubmitting,\n [`use${prefix}SubmitCount`]: useBoundSubmitCount,\n [`use${prefix}Values`]: useBoundValues,\n [`use${prefix}Fields`]: useBoundFields,\n [`use${prefix}Steps`]: useBoundSteps,\n [`use${prefix}Action`]: useBoundAction,\n [`use${prefix}ActionState`]: useBoundActionState,\n [`use${prefix}Persist`]: useBoundPersist,\n } as FormHooks<TSchema, N, D>;\n};\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n ArrayFieldPath,\n FieldPath,\n FieldValue,\n PathDepth,\n} from \"../core/fieldPath\";\nimport {\n checkboxProps,\n dateInputProps,\n hasFieldError,\n numberToInputText,\n parseNumberText,\n selectProps,\n textInputProps,\n} from \"./inputProps\";\nimport { type FieldFormApi, type UseFieldReturn, useField } from \"./useField\";\n\n// The paths a bound component accepts for a given `form` prop: when the form\n// carries its schema (a real Form<TSchema>), `path` narrows to the schema's\n// FieldPath union — a typo'd path is a compile error, matching useField's\n// typed overloads. Template-literal paths with a numeric hole\n// (`users.${index}.email`) are part of that union, so dynamic array rows\n// still typecheck. A bare structural FieldFormApi keeps plain string paths.\n// The form's own depth budget (createForm's `pathDepth`, default 9) is\n// recovered alongside the schema, so a widened form widens its bound\n// components' paths too.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? FieldPath<z.input<TSchema>, D>\n : string;\n\n// The subset of a form's paths whose VALUE a control can hold: TextField\n// takes string-valued paths, NumberField number-valued ones, and so on.\n// Before this filter `<TextField path=\"age\" />` on a z.number() compiled\n// and stored the string \"42\", failing validation at submit, while the\n// lower-level `textInputProps(useField(form, \"age\"))` had always been a\n// compile error; the beginner API was less safe than the expert one.\n// Distributes over the FieldPath union and keeps the paths whose\n// FieldValue is assignable to V (V always includes null | undefined, so\n// optional and nullable fields qualify). A bare FieldFormApi keeps plain\n// string paths, as PathsOf does.\nexport type PathsAccepting<F extends FieldFormApi, V> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? PathsWhereValue<z.input<TSchema>, FieldPath<z.input<TSchema>, D>, V>\n : string;\n\ntype PathsWhereValue<Values, P extends string, V> = P extends unknown\n ? FieldValue<Values, P> extends V\n ? P\n : never\n : never;\n\n// The form-level spelling of the core's ArrayFieldPath: the paths a\n// `form` prop's array ops and useFieldArray accept (variable-length arrays,\n// optional/nullable included, tuples excluded). For a component that takes\n// a form and an array path, the way PathsOf serves one taking any path. A\n// bare FieldFormApi keeps plain string paths.\nexport type ArrayPathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType,\n infer D extends PathDepth\n>\n ? ArrayFieldPath<z.input<TSchema>, D>\n : string;\n\n// The string values a select at `path` may hold: the field's own literal\n// union for an enum (so an option outside z.enum([...]) is a compile\n// error at the option), plain string for a free z.string(), and any\n// string for a bare FieldFormApi.\nexport type SelectValueAt<\n F extends FieldFormApi,\n P extends string,\n> = F extends Form<infer TSchema extends z.ZodType, infer D extends PathDepth>\n ? P extends FieldPath<z.input<TSchema>, D>\n ? Extract<NonNullable<FieldValue<z.input<TSchema>, P>>, string>\n : string\n : string;\n\n// Structural stand-in for React.Ref<T>: accepts useRef objects and callback\n// refs (including React 19 cleanup-returning ones — any return type is\n// assignable to a void-returning signature). Declared structurally instead of\n// as React.Ref so it unifies even when the consumer resolves a different\n// @types/react copy than the library.\nexport type FieldRef<T> =\n | ((instance: T | null) => void)\n | Readonly<{ current: T | null }>\n | null;\n\n// The chrome every bound field renders: wrapper, optional label, the\n// control, and the error line. `wrapLabel` puts the control INSIDE the\n// label (the checkbox layout: box, then text) instead of after a preceding\n// sibling label. One component so an a11y change lands everywhere at once.\ntype FieldShellProps = Readonly<{\n id: string;\n errorId: string;\n label: ReactNode | undefined;\n error: readonly string[] | undefined;\n wrapLabel?: boolean;\n children: ReactNode;\n}>;\n\n// Shared id wiring for every bound field: a stable control id, the error\n// line's id derived from it, and the aria-describedby value — set only\n// while an error shows, so assistive tech is never pointed at a node that\n// isn't rendered.\nconst useFieldA11y = (\n error: readonly string[] | undefined,\n): Readonly<{ id: string; errorId: string; describedBy: string | undefined }> => {\n const id = useId();\n const errorId = `${id}-error`;\n return {\n id,\n errorId,\n describedBy: hasFieldError(error) ? errorId : undefined,\n };\n};\n\n// role=\"alert\" announces the message to assistive tech when it appears; the\n// id lets the input point at it via aria-describedby.\nconst ErrorText = ({\n id,\n error,\n}: Readonly<{ id: string; error: readonly string[] | undefined }>) =>\n hasFieldError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nconst FieldShell = ({\n id,\n errorId,\n label,\n error,\n wrapLabel,\n children,\n}: FieldShellProps) => (\n <div className=\"zf-field\">\n {wrapLabel === true && label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {children} {label}\n </label>\n ) : (\n <>\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n {children}\n </>\n )}\n <ErrorText id={errorId} error={error} />\n </div>\n);\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsAccepting<F, string | null | undefined>;\n label?: ReactNode;\n placeholder?: string;\n type?: \"text\" | \"password\" | \"email\" | \"url\" | \"tel\";\n autoComplete?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\nexport const TextField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n type = \"text\",\n autoComplete,\n ref,\n}: TextFieldProps<F>) => {\n const field = useField<string | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type DateFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsAccepting<F, Date | null | undefined>;\n label?: ReactNode;\n min?: string;\n max?: string;\n ref?: FieldRef<HTMLInputElement>;\n}>;\n\n// <input type=\"date\"> holds Date-typed state: display and parsing go\n// through the shared dateInputProps rules (local calendar-date semantics —\n// see inputProps.ts), so a nullable date clears back to null and an\n// invalid/partial entry writes the field's emptyValue. No raw-text state:\n// unlike number inputs, the date control has no partial entries to\n// preserve — the browser only fires change with \"\" or a complete date.\nexport const DateField = <F extends FieldFormApi>({\n form,\n path,\n label,\n min,\n max,\n ref,\n}: DateFieldProps<F>) => {\n const field = useField<Date | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n {...dateInputProps(field)}\n min={min}\n max={max}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsAccepting<F, number | null | undefined>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport type NumberInputBinding = Readonly<{\n name: string;\n value: string;\n inputMode: \"decimal\";\n \"aria-invalid\": true | undefined;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onBlur: () => void;\n}>;\n\ntype NumberEditState = Readonly<{\n raw: string | null;\n // The form value this hook last wrote (or observed when it kept a partial\n // entry). When field.value diverges, an external writer (reset/adoptValues/\n // another field) changed it — drop the raw text so the input shows it.\n pushed: number | null | undefined;\n}>;\n\nconst IDLE_EDIT: NumberEditState = { raw: null, pushed: undefined };\n\n// Holds the raw text while editing so intermediate, not-yet-valid numbers\n// (\"-\", \"1.\", \"1e\") stay visible instead of being coerced to \"\". Keystrokes\n// that parse to a number (via the shared parseNumberText rules) are pushed to\n// the form; partial input is kept locally. On blur the display snaps back to\n// the form's canonical value, and an external value change while editing wins\n// over the local text (render-phase derived-state reset).\n// Exported for custom number inputs (and the CLI's kit adapters mirror its\n// semantics): spread the binding onto an <input type=\"text\"> — a naive\n// value={String(field.value)} controlled input eats the \".\" of \"85000.50\"\n// and the \"-\" of \"-5\" as they're typed.\nexport const useNumberInput = (\n field: UseFieldReturn<number | null | undefined>,\n): NumberInputBinding => {\n const [edit, setEdit] = useState<NumberEditState>(IDLE_EDIT);\n const externallyChanged =\n edit.raw !== null && !Object.is(field.value, edit.pushed);\n if (externallyChanged) {\n setEdit(IDLE_EDIT);\n }\n const raw = externallyChanged ? null : edit.raw;\n return {\n name: field.path,\n value: raw ?? numberToInputText(field.value),\n inputMode: \"decimal\",\n \"aria-invalid\": hasFieldError(field.error) ? true : undefined,\n onChange: (e) => {\n const text = e.target.value;\n const parsed = parseNumberText(text);\n switch (parsed.kind) {\n case \"empty\": {\n const empty = field.emptyValue;\n setEdit({ raw: text, pushed: empty });\n field.setValue(empty);\n return;\n }\n case \"number\":\n setEdit({ raw: text, pushed: parsed.value });\n field.setValue(parsed.value);\n return;\n case \"invalid\":\n // Partial entry: keep the text, remember the untouched form value\n // so it doesn't read as an external change.\n setEdit({ raw: text, pushed: field.value });\n return;\n }\n },\n onBlur: () => {\n setEdit(IDLE_EDIT);\n field.onBlur();\n },\n };\n};\n\nexport const NumberField = <F extends FieldFormApi>({\n form,\n path,\n label,\n placeholder,\n ref,\n}: NumberFieldProps<F>) => {\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <input\n id={a11y.id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsAccepting<F, boolean | null | undefined>;\n label?: ReactNode;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\nexport const CheckboxField = <F extends FieldFormApi>({\n form,\n path,\n label,\n ref,\n}: CheckboxFieldProps<F>) => {\n const field = useField<boolean | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n wrapLabel\n >\n <input\n id={a11y.id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={a11y.describedBy}\n />\n </FieldShell>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\n// P is the chosen path; the options' values are checked against the\n// field's own string union at that path (SelectValueAt), so an option the\n// schema's z.enum does not list is a compile error where it is written.\nexport type SelectFieldProps<\n F extends FieldFormApi = FieldFormApi,\n P extends PathsAccepting<F, string | null | undefined> = PathsAccepting<\n F,\n string | null | undefined\n >,\n> = Readonly<{\n form: F;\n path: P;\n label?: ReactNode;\n options: readonly SelectFieldOption<SelectValueAt<F, P>>[];\n // Shown as a disabled first option while the field has no value, so the\n // select stays controlled and the blank state is visible instead of\n // silently displaying the first option. Ignored when `options` itself\n // contains a \"\"-valued entry — that explicit, labelled option IS the\n // blank state and renders instead.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <\n F extends FieldFormApi,\n P extends PathsAccepting<F, string | null | undefined>,\n>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<F, P>) => {\n // null included: a nullable enum's \"not chosen yet\" must render the empty\n // option, or the browser shows the first real option while state stays null.\n const field = useField<SelectValueAt<F, P> | null | undefined>(form, path);\n const a11y = useFieldA11y(field.error);\n const select = selectProps(field);\n // A clearable field (nullable, optional, or defaulted) must be clearable\n // BACK to its emptyValue through the UI, so its empty option stays\n // visible after a choice and stays selectable — selectProps writes the\n // emptyValue for it. Everywhere else the empty option is only a\n // placeholder: visible while nothing is chosen, never selectable.\n // The value condition derives from selectProps' own coercion (undefined,\n // null, and \"\" all render as value \"\"), so any blank the select displays\n // has a matching option by construction. When the options list supplies\n // its OWN \"\"-valued entry, that explicit option IS the blank state —\n // rendering the implicit one too would duplicate the value, and the\n // browser would select the first (unlabelled) match instead.\n const clearable = field.clearable;\n const hasExplicitEmptyOption = options.some((opt) => opt.value === \"\");\n const showEmptyOption =\n !hasExplicitEmptyOption &&\n (clearable || select.value === \"\" || placeholder !== undefined);\n return (\n <FieldShell\n id={a11y.id}\n errorId={a11y.errorId}\n label={label}\n error={field.error}\n >\n <select\n id={a11y.id}\n ref={ref}\n {...select}\n aria-describedby={a11y.describedBy}\n >\n {showEmptyOption ? (\n <option value=\"\" disabled={!clearable}>\n {placeholder ?? \"\"}\n </option>\n ) : null}\n {options.map((opt, index) => (\n // Index-qualified: option lists may legitimately repeat a value\n // (e.g. differently-labelled aliases), and bare value keys would\n // collide.\n <option key={`${index}-${opt.value}`} value={opt.value}>\n {opt.label}\n </option>\n ))}\n </select>\n </FieldShell>\n );\n};\n","import type { ErrorMap } from \"../core/types\";\nimport { isPathOrChild } from \"../core/validation\";\n\n// The shared candidate walk for focusFirstError/focusField: form controls\n// with a `name`, in DOM order. Focusability is a SEPARATE, later filter —\n// matches()/closest() are ancestor walks, so they run on the few\n// name-matched candidates instead of every named control in the document\n// (a failed submit on a page with hundreds of controls shouldn't pay\n// hundreds of DOM traversals to focus one input).\nconst namedControls = (scope: ParentNode): readonly HTMLElement[] => [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n];\n\n// Hidden and disabled controls, and controls inside a closed <dialog>,\n// can't take focus — without the filter, a leading <input type=\"hidden\"\n// name=\"csrf\"> would swallow focusFirstError's root fallback, and a name\n// match inside a not-yet-opened dialog would shadow the visible one.\nconst isFocusCandidate = (el: HTMLElement): boolean =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null;\n\n// Does `el` actually hold focus? Ask the element's OWN root (document or\n// shadow root): document.activeElement retargets to the shadow HOST for a\n// focused control inside a shadow root, so it would read a successfully\n// focused shadow-DOM control as unfocused. A root that is neither (a\n// detached fragment) has no activeElement — fall back to the document,\n// where a detached element can never be the active one.\nconst holdsFocus = (el: HTMLElement): boolean => {\n const rootNode = el.getRootNode();\n const active =\n rootNode instanceof Document || rootNode instanceof ShadowRoot\n ? rootNode.activeElement\n : document.activeElement;\n return active === el;\n};\n\n// focus() can silently no-op (display:none ancestors and other unfocusable\n// states the cheap filters above can't see) — verify it took, and fall\n// through to the next candidate in DOM order. True only when a control\n// actually holds focus.\nconst focusFirstOf = (candidates: readonly HTMLElement[]): boolean =>\n candidates.some((el) => {\n el.focus();\n return holdsFocus(el);\n });\n\nconst nameMatchesAny = (\n el: HTMLElement,\n paths: readonly string[],\n): boolean => {\n const name = el.getAttribute(\"name\");\n return name !== null && paths.some((p) => isPathOrChild(name, p));\n};\n\n// CSS attribute-selector value for an arbitrary path: quoted, with the two\n// characters that are active inside a double-quoted CSS string escaped —\n// so paths with dots (\"address.region\") and hostile names select literally.\n// Control characters (a stray \"\\n\" in a computed path, DEL) are additionally\n// hex-escaped (`\\a `, with CSS's required trailing space): a raw newline\n// inside a quoted CSS string is a parse error, and querySelectorAll on an\n// invalid selector THROWS instead of matching nothing.\nconst cssQuoted = (value: string): string =>\n `\"${value\n .replace(/[\\\\\"]/g, (ch) => `\\\\${ch}`)\n .replace(\n /[\\x00-\\x1f\\x7f]/g,\n (ch) => `\\\\${ch.codePointAt(0)!.toString(16)} `,\n )}\"`;\n\n// The id fallback for composite widgets that render no `name` at all (e.g.\n// antd's Select — no form-posting input exists in it) but DO forward\n// `id={path}` to their real focusable control, the way the CLI's antd\n// adapter emits it. EXACT id match only, by design: descendant semantics\n// (\"address\" covering \"address.city\") belong to the name walk — an id names\n// one element, and inventing prefix matching over ids would guess. Runs\n// through the same focusability filter and post-focus verification as name\n// matches.\nconst idMatches = (\n scope: ParentNode,\n path: string,\n): readonly HTMLElement[] =>\n path === \"\"\n ? []\n : [...scope.querySelectorAll<HTMLElement>(`[id=${cssQuoted(path)}]`)];\n\n// Document order for a merged candidate list (name matches + id fallbacks\n// come from separate queries, but \"first error\" means first in the DOM).\nconst inDomOrder = (\n els: readonly HTMLElement[],\n): readonly HTMLElement[] =>\n [...els].sort((a, b) =>\n a === b\n ? 0\n : (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n ? -1\n : 1,\n );\n\n// The candidate walk shared by focusFirstError and focusField: name-matched\n// form controls for every path, plus — per path that matched NO named\n// control — the element whose `id` is exactly that path. Paths with a named\n// match never consult ids, so the name walk's semantics (descendants\n// included) stay authoritative wherever a `name` exists.\nconst pathCandidates = (\n scope: ParentNode,\n paths: readonly string[],\n): readonly HTMLElement[] => {\n const controls = namedControls(scope);\n const named = controls.filter((el) => nameMatchesAny(el, paths));\n // \"Has a named match\" is judged against focus-CANDIDATE controls only: a\n // hidden name-carrier (react-select's <input type=\"hidden\" name={path}>\n // value input, notably) can never take focus, so letting it claim the\n // path would suppress the id fallback and leave the real, id={path}\n // focusable control unreachable. The `named` list itself stays\n // pre-filter — callers apply isFocusCandidate to the merged result.\n const focusableControls = controls.filter(isFocusCandidate);\n const unnamedPaths = paths.filter(\n (p) => !focusableControls.some((el) => nameMatchesAny(el, [p])),\n );\n const byId = unnamedPaths.flatMap((p) => idMatches(scope, p));\n return inDomOrder([...new Set([...named, ...byId])]);\n};\n\n// Focus the first form control (in DOM order) whose `name` attribute matches\n// an entry in the error map — either exactly, or as a descendant of an\n// errored container path, so array-level errors (\"lineItems\" from\n// z.array().min()) and object-level refines (\"address\") land on their first\n// rendered field. Most specific wins: the root \"\" key (a form-wide refine)\n// falls back to the first control only when no field-keyed error matches\n// anything — otherwise a root error would steal focus from the actually\n// errored field. A path that matches NO named control at all additionally\n// tries the element whose `id` is exactly that path (see pathCandidates) —\n// how composite widgets with no `name` anywhere, like antd's Select with\n// id={path}, still get focused. The bound components and prop builders set\n// name={path}, so this works out of the box:\n//\n// form.handleSubmit(onValid, (errors) => focusFirstError(errors))\n//\n// Pass `root` to scope the search (e.g. the <form> element via a ref) — on a\n// page with several forms this is the way to keep focus inside YOUR form:\n// without it the search spans the whole document, and the root-\"\" fallback\n// refuses to guess between forms (it returns false when the document holds\n// more than one <form>). Returns whether a control actually received focus —\n// candidates that can't take it (disabled, hidden, inside a closed <dialog>,\n// display:none, ...) are passed over for the next match in DOM order. Safe to\n// import during SSR — it only touches the DOM when called.\nexport const focusFirstError = (\n errors: ErrorMap,\n root?: ParentNode,\n): boolean => {\n const scope = root ?? document;\n const erroredPaths = Object.keys(errors).filter(\n (k) => k !== \"\" && (errors[k]?.length ?? 0) > 0,\n );\n const hasRootError = (errors[\"\"]?.length ?? 0) > 0;\n const controls = namedControls(scope);\n const fieldMatches = pathCandidates(scope, erroredPaths).filter(\n isFocusCandidate,\n );\n // The root-\"\" fallback (\"focus the first control\") is only meaningful when\n // \"first control\" is unambiguous. With the default document scope on a\n // page holding several <form>s, the first control could belong to a form\n // that had nothing to do with this submit — refuse to guess and report\n // false; pass the form element as `root` to disambiguate.\n const rootFallbackApplies =\n hasRootError &&\n (root !== undefined || document.querySelectorAll(\"form\").length <= 1);\n const candidates =\n fieldMatches.length > 0\n ? fieldMatches\n : rootFallbackApplies\n ? controls.filter(isFocusCandidate)\n : [];\n return focusFirstOf(candidates);\n};\n\n// Imperative sibling of focusFirstError, keyed by a path instead of an error\n// map: focus the first control (in DOM order) whose `name` is `path` itself\n// or a descendant of it — focusField(\"address\") lands on the first rendered\n// address field. Same candidate walk (unfocusable controls are passed over,\n// focus is verified to have taken, a name-less path falls back to the\n// element whose `id` is exactly the path) and the same `root` scoping.\n// This is the \"setFocus\" of the library — reach for it after opening a\n// dialog or appending an array row:\n//\n// items.push(emptyItem);\n// requestAnimationFrame(() =>\n// focusField(`items.${items.length}.name`, formRef.current ?? undefined),\n// );\n//\n// The root \"\" path is whole-form scope, consistent with the imperative\n// surface (validateField(\"\") / resetField(\"\")): focus the first focusable\n// control in scope. Like focusFirstError's root-\"\" fallback, \"first control\"\n// under the default document scope is a guess when the page holds several\n// <form>s — focusField refuses to guess and returns false; pass the form\n// element as `root` to disambiguate.\n//\n// Returns whether a control actually received focus. Safe to import during\n// SSR — it only touches the DOM when called.\nexport const focusField = (path: string, root?: ParentNode): boolean => {\n const scope = root ?? document;\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(namedControls(scope).filter(isFocusCandidate))\n : focusFirstOf(pathCandidates(scope, [path]).filter(isFocusCandidate));\n};\n"]}
|