formstand 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/array.ts","../src/core/equality.ts","../src/core/path.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/mode.ts","../src/react/useForm.ts","../src/react/FormContext.tsx","../src/react/useFormSelector.ts","../src/react/useFormError.ts","../src/react/useFormFlags.ts","../src/react/useField.ts","../src/react/inputProps.ts","../src/react/fields.tsx","../src/react/focusError.ts","../src/react/useFieldArray.ts"],"names":["result","useStore","useShallow","initialValue","useRef","useEffect","validateAsync","jsx","useState","useCallback","useMemo"],"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;AAEhC,IAAM,YAA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AAC,MAAM,IAAI;AAAA,GACb;AAEA,EAAA,MAAM,MAAA,GAASC,OAAAA;AAAA,IACb,MACE,KAAA,CAAM,GAAA,CAAI,CAAC,OAAO,KAAA,MAAW;AAAA,MAC3B,EAAA,EAAI,GAAA,CAAI,KAAK,CAAA,IAAK,kBAAkB,KAAK,CAAA,CAAA;AAAA,MACzC;AAAA,KACF,CAAE,CAAA;AAAA,IACJ,CAAC,OAAO,GAAG;AAAA,GACb;AAEA,EAAA,OAAOA,OAAAA;AAAA,IACL,OAAO;AAAA,MACL,MAAA;AAAA,MACA,KAAA;AAAA,MACA,QAAQ,KAAA,CAAM,MAAA;AAAA,MACd,KAAA;AAAA,MACA,IAAA;AAAA,MACA,MAAA;AAAA,MACA,MAAA;AAAA,MACA,IAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,QAAQ,KAAA,EAAO,KAAA,EAAO,MAAM,MAAA,EAAQ,MAAA,EAAQ,MAAM,IAAI;AAAA,GACzD;AACF","file":"index.js","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\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","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 if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\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 return (\n aKeys.length === bKeys.length &&\n aKeys.every((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","export type PathSegment = string | number;\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\nexport const parsePath = (path: string): readonly PathSegment[] =>\n path === \"\"\n ? []\n : path.split(\".\").map((s) => (isIndexSegment(s) ? Number(s) : s));\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 return isPlainRecord(obj) ? obj[String(segment)] : 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 numeric segment addresses a real\n// slot: an in-range array index, or a record key (containers decide,\n// mirroring readSegment). An out-of-range index — including any index into\n// an absent or non-container value — addresses no slot at all: a full-form\n// parse would never key an error there. Object properties reached by STRING\n// segments may be legitimately absent (an empty optional field is still\n// addressable). Returns the resolved value so callers don't walk the path\n// 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 outOfBounds =\n typeof segment === \"number\" &&\n (Array.isArray(acc.current)\n ? segment >= acc.current.length\n : !isPlainRecord(acc.current));\n return !acc.ok || outOfBounds\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(acc.current, segment) };\n },\n { ok: true, current: obj },\n );\n return walked.ok ? { exists: true, value: walked.current } : { exists: false };\n};\n\nconst writeIntoArray = (\n arr: readonly unknown[],\n index: number,\n rest: readonly PathSegment[],\n value: unknown,\n): readonly unknown[] => {\n const length = Math.max(arr.length, index + 1);\n return Array.from({ length }, (_, i) =>\n i === index ? writeSegments(arr[i], rest, value) : 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): 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);\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 const key = String(head);\n return { ...obj, [key]: writeSegments(obj[key], rest, value) };\n }\n\n // Absent (or non-container) value: create a container from the segment type.\n if (typeof head === \"number\") {\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray([], head, rest, value);\n }\n return { [head]: writeSegments(undefined, rest, value) };\n};\n\nexport const setAtPath = <T>(obj: T, path: string, value: unknown): T =>\n writeSegments(obj, parsePath(path), value) as T;\n","import { z } from \"zod\";\nimport { type PathSegment, parsePath } 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\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\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Record<string, readonly string[]>>((acc, { path, message }) => {\n // Union branches often repeat the same complaint; drop exact duplicates.\n const existing = acc[path] ?? [];\n return existing.includes(message)\n ? acc\n : { ...acc, [path]: [...existing, message] };\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// 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 const child = shape[String(head)];\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.\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 return shape[segment] ?? 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 {\n type IndexMapper,\n insertAt,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport type { FieldPath, FieldValue } from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n type SettledValidationResult,\n type ValidationResult,\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<TSchema extends z.ZodType> = Readonly<{\n initialValues: z.input<TSchema>;\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}>;\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}>;\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\ntype ArrayItemOf<T> = T extends readonly (infer U)[] ? U : never;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key.\ntype ErrorPath<TValues> = FieldPath<TValues> | \"\";\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<TSchema extends z.ZodType> = Readonly<{\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>>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n watchField: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>>>(\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>>>(\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>>, 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>>,\n errors: string | readonly string[],\n ) => void;\n setErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>>) => 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>>) => 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>>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>>) => FieldValidationResult;\n // Returns a Promise (the async pass, already started) when the schema needs\n // async parsing — mirroring the \"pending\" result of validate/validateField.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>>[],\n ) => boolean | Promise<boolean>;\n validateAsync: () => Promise<ValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>>,\n ) => Promise<FieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>>[],\n ) => Promise<boolean>;\n submit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => Promise<SubmitResult<z.output<TSchema>>>;\n arrayPush: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayRemove: (path: FieldPath<z.input<TSchema>>, index: number) => void;\n arrayInsert: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n index: number,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayMove: (\n path: FieldPath<z.input<TSchema>>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (path: FieldPath<z.input<TSchema>>, a: number, b: number) => 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\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 (valuesEqual(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\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 // valuesEqual said the objects differ, but no child diverges by its own\n // comparison — a key-count mismatch where the extra key holds undefined\n // ({} vs { nickname: undefined }). Report the object itself so diff()/\n // dirtyFields() stay non-empty whenever isFieldDirty/useIsDirty say dirty.\n return childPaths.length > 0 ? childPaths : [prefix];\n }\n return [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.\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 = 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]) => 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 const extra = Object.entries(server).filter(([k]) => schema[k] === undefined);\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\nexport const createForm = <TSchema extends z.ZodType>(\n schema: TSchema,\n options: CreateFormOptions<TSchema>,\n): Form<TSchema> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\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 const store = createStore<FormState<Values>>(() => initial);\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 try {\n const result = validateSync(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 ): boolean | Promise<boolean> => {\n if (paths.length === 0) return true;\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 ? result.promise.then((r) => r.kind === \"valid\")\n : result.kind === \"valid\";\n }\n try {\n const result = validateSync(schema, store.getState().values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(\n state.schemaErrors,\n pickScope(fullErrors, paths),\n paths,\n ),\n state.schemaErrors,\n ),\n // A validation explicitly targeting these paths supersedes any\n // server verdict on them.\n serverErrors: omitScope(state.serverErrors, paths),\n }),\n }));\n return Object.keys(fullErrors).every((k) => !inScopeOfAny(k, paths));\n } catch (e) {\n if (isAsyncRequiredError(e)) return validateFieldsAsync(paths);\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 // 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 scopedFieldErrors = (path: string): ErrorMap => {\n const values = store.getState().values;\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n validateSync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n };\n\n const scopedFieldErrorsAsync = async (\n path: string,\n values: Values,\n ): Promise<ErrorMap> => {\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\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 // How a field validation's scoped errors land in state. validateField(\"\")\n // is a whole-form pass, so it lands like validate() (server channel\n // untouched). A real field path also releases the server entries in its\n // scope — a validation explicitly targeting them supersedes the server\n // verdict. Shared by the sync and async passes so their commit semantics\n // cannot diverge.\n const commitFieldErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, scoped)\n : errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(state.schemaErrors, scoped, [path]),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, [path]),\n });\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n try {\n const scoped = scopedFieldErrors(path);\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: state.errors[path],\n touched: state.touched[path] ?? false,\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: state.isValidating[path] ?? false,\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<boolean> => {\n if (paths.length === 0) return true;\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n const result = await validateAsyncOnForm();\n return result.kind === \"valid\";\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: paths.reduce<Record<string, boolean>>(\n (acc, p) => ({ ...acc, [p]: true }),\n { ...state.isValidating },\n ),\n }));\n\n const result = await validateAsync(schema, valuesAtStart);\n const fullErrors = result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedValid = Object.keys(fullErrors).every(\n (k) => !inScopeOfAny(k, paths),\n );\n\n const live = store.getState();\n const stillCurrent = paths.filter(\n (p) => sequences.get(p) === passes.get(p),\n );\n if (live.values !== valuesAtStart) {\n if (stillCurrent.length > 0) {\n store.setState((state) => ({\n ...state,\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n }\n return requestedValid;\n }\n\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(\n state.schemaErrors,\n pickScope(fullErrors, stillCurrent),\n stillCurrent,\n ),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, stillCurrent),\n }),\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n\n return requestedValid;\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 store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const scoped = await scopedFieldErrorsAsync(path, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\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 if (current !== undefined && !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 store.setState((state) => {\n const live = getAtPath(state.values, path);\n const arr: readonly unknown[] = Array.isArray(live) ? live : [];\n return {\n ...state,\n values: setAtPath(state.values, path, nextArray(arr)),\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 onInvalid?.(merged);\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 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>>>(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>>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>>>(\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>>>(\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 store.setState((state) => ({\n ...state,\n values: setAtPath(state.values, path, value),\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n })),\n setValues: (next) =>\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 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 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 store.setState((state) => {\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return state;\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 return {\n ...next,\n ...errorChannels(state, {\n schemaErrors: next.schemaErrors,\n serverErrors: next.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 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 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 store.setState((state) => ({\n ...state,\n values: setAtPath(\n state.values,\n path,\n getAtPath(state.initialValues, path),\n ),\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 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 return submit(onValid, onInvalid, opts);\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 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.\n isValidating: emptyBools,\n isValidatingForm: false,\n };\n }),\n }) as Form<TSchema>;\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","import { useEffect, useRef } from \"react\";\nimport type { z } from \"zod\";\nimport {\n type CreateFormOptions,\n type Form,\n createForm,\n} from \"../core/createForm\";\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).\nexport const useForm = <TSchema extends z.ZodType>(\n schema: TSchema,\n options: CreateFormOptions<TSchema>,\n): Form<TSchema> => {\n const formRef = useRef<Form<TSchema> | 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 warnedRef = useRef(false);\n useEffect(() => {\n if (!warnedRef.current && form.schema !== schema) {\n warnedRef.current = true;\n console.warn(\n \"[formstand] useForm received a different schema reference after \" +\n \"the first render; schema and options changes are ignored for the \" +\n \"life of the component. If the schema is defined inline this is \" +\n \"harmless (but consider hoisting it to module scope). For initial \" +\n \"values that arrive later (e.g. from a fetch), call \" +\n \"form.adoptValues(values) or form.reset(values) instead.\",\n );\n }\n }, [form, schema]);\n\n return form;\n};\n","import {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\n\nexport type FormProviderProps<TSchema extends z.ZodType> = Readonly<{\n form: Form<TSchema>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<TSchema extends z.ZodType> = Readonly<{\n Provider: (props: FormProviderProps<TSchema>) => ReactNode;\n useFormContext: () => Form<TSchema>;\n}>;\n\nexport const createFormContext = <\n TSchema extends z.ZodType,\n>(): FormContextApi<TSchema> => {\n const Context = createContext<Form<TSchema> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema> => {\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 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 { 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<TSchema extends z.ZodType, U>(\n form: Form<TSchema>,\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<TSchema extends z.ZodType, U>(\n form: Form<TSchema>,\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 { 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 { isFieldDirty } from \"../core/equality\";\nimport type { FieldPath } 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>>,\n>(form: Form<TSchema>, 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>>,\n>(form: Form<TSchema>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\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\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 { 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 { isFieldDirty } from \"../core/equality\";\nimport type { FieldPath, FieldValue } from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n emptyValueForSchema,\n fieldSchemaAtPath,\n isAsyncRequiredError,\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 validateFieldAsync(path: string): Promise<FieldValidationResult>;\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 error: readonly 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 validateAsync: () => Promise<FieldValidationResult>;\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// 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.\nexport function useField<TSchema extends z.ZodType>(\n form: Form<TSchema>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\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: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>>,\n>(\n form: Form<TSchema>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: string | ((state: FormState<unknown>) => string),\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 error: state.errors[p],\n touched: state.touched[p] ?? false,\n dirty: isFieldDirty(value, initialValue),\n isValidating: state.isValidating[p] ?? false,\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 = useMemo(() => {\n if (formSchema !== undefined) {\n const sub = fieldSchemaAtPath(formSchema, path);\n if (sub !== null) return emptyValueForSchema(sub);\n }\n return initialValue === null ? null : undefined;\n }, [formSchema, path, initialValue]);\n\n const debounceMs = options?.debounceMs;\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n debounceTimerRef.current = null;\n }\n };\n }, [form, path, debounceMs]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => {\n void form.validateFieldAsync(path);\n debounceTimerRef.current = null;\n }, debounceMs);\n return;\n }\n try {\n form.validateField(path);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n void form.validateFieldAsync(path);\n return;\n }\n throw e;\n }\n }, [form, path, debounceMs]);\n\n const setValue = useCallback(\n (value: TValue) => {\n form.setValue(path, value);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\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 error: slice.error,\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, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\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 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\nconst ariaInvalid = (field: Readonly<{ error: readonly string[] | undefined }>): true | undefined =>\n field.error !== undefined && field.error.length > 0 ? true : undefined;\n\n// A cleared input writes back `field.emptyValue` — null when the schema says\n// the field is nullable (useField introspects the form's zod schema), so\n// z.number().nullable() round-trips to a valid blank instead of an undefined\n// the schema 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 nullable field restores null, so it isn't\n // left permanently dirty (or invalid) by a visual no-op.\n field.setValue(\n (text === \"\" && field.emptyValue === null ? null : text) as T,\n );\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 field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\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(\n (v === \"\" && field.emptyValue === null ? null : v) as T,\n );\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath } from \"../core/fieldPath\";\nimport {\n checkboxProps,\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.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType\n>\n ? FieldPath<z.input<TSchema>>\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\nconst hasError = (error: readonly string[] | undefined): boolean =>\n error !== undefined && error.length > 0;\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 hasError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<string | null | undefined>(form, path);\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <input\n id={id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\ntype 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).\nconst 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\": hasError(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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <input\n id={id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<boolean | null | undefined>(form, path);\n return (\n <div className=\"zf-field\">\n <label htmlFor={id} className=\"zf-label\">\n <input\n id={id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />{\" \"}\n {label}\n </label>\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\nexport type SelectFieldProps<\n T extends string,\n F extends FieldFormApi = FieldFormApi,\n> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n options: readonly SelectFieldOption<T>[];\n // Shown as a disabled first option while the field value is undefined, so\n // the select stays controlled and the blank state is visible instead of\n // silently displaying the first option.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <T extends string, F extends FieldFormApi>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<T, F>) => {\n const id = useId();\n const errorId = `${id}-error`;\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<T | null | undefined>(form, path);\n const showEmptyOption =\n field.value === undefined ||\n field.value === null ||\n placeholder !== undefined;\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <select\n id={id}\n ref={ref}\n {...selectProps(field)}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n >\n {showEmptyOption ? (\n <option value=\"\" disabled>\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 <ErrorText id={errorId} error={field.error} />\n </div>\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, minus the ones that can't take focus. Hidden\n// and disabled controls, and controls inside a closed <dialog>, can't —\n// without the filter, a leading <input type=\"hidden\" name=\"csrf\"> would\n// swallow focusFirstError's root fallback, and a name match inside a\n// not-yet-opened dialog would shadow the visible one.\nconst focusableControls = (scope: ParentNode): readonly HTMLElement[] =>\n [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n ].filter(\n (el) =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null,\n );\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// 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. The bound components and prop builders set name={path}, so\n// 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 = focusableControls(scope);\n const fieldMatches = controls.filter((el) =>\n nameMatchesAny(el, erroredPaths),\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 ? fieldMatches : rootFallbackApplies ? controls : [];\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) and the same optional `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 controls = focusableControls(root ?? document);\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(controls)\n : focusFirstOf(controls.filter((el) => nameMatchesAny(el, [path])));\n};\n","import { useCallback, useMemo, useState } 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 { FieldPath, FieldValue } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\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.\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}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\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}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n}>;\n\nconst EMPTY_ID_STATE: IdState = { items: [], ids: [], counter: 0 };\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// Derive a stable id per item by reconciling the live items against the\n// previous render's items. Ids follow items by identity/value, so reorders,\n// resets, and mutations that bypass this hook all keep keys glued to their\n// rows — not just length-preserving appends/truncations. A positional\n// fallback hands a vanished item's id to a still-unmatched one, so editing a\n// field (which produces a fresh item reference) keeps its row instead of\n// remounting it.\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 return prev;\n }\n\n // Bucket prev positions by item so duplicate primitives match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\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) => {\n const prevIndex = buckets.get(item)?.shift();\n return prevIndex === undefined ? null : (prev.ids[prevIndex] ?? null);\n });\n\n // Whatever prev ids remain belong to items that vanished; feed them to the\n // still-unmatched items in order, in-place edits before fresh mints.\n const leftover = [...buckets.values()]\n .flat()\n .sort((a, b) => a - b)\n .map((i) => prev.ids[i])\n .filter((id): id is string => id !== undefined);\n\n // Running 1-based count of unmatched slots up to each position, so every\n // unmatched item maps straight to its leftover id (or a freshly minted one)\n // without rebuilding the ids array per element.\n const ordinals = matchedIds.reduce<number[]>((acc, id) => {\n const count = acc.length === 0 ? 0 : (acc[acc.length - 1] ?? 0);\n acc.push(id === null ? count + 1 : count);\n return acc;\n }, []);\n const unmatched =\n ordinals.length === 0 ? 0 : (ordinals[ordinals.length - 1] ?? 0);\n const ids = matchedIds.map((id, i) => {\n if (id !== null) return id;\n const ordinal = ordinals[i] ?? 0;\n return (\n leftover[ordinal - 1] ??\n `__zfa_${prev.counter + (ordinal - leftover.length)}`\n );\n });\n\n return {\n items: nextItems,\n ids,\n counter: prev.counter + Math.max(0, unmatched - leftover.length),\n };\n};\n\n// The element type at an array-valued path. FieldValue re-adds `| undefined`\n// for arrays reached through optional ancestors, so strip that before\n// extracting; a non-array path yields `never`, which makes every write\n// (`push(never)`) an immediate error instead of a silently-`unknown` bind.\ntype ArrayItemOf<T> = [NonNullable<T>] extends [readonly (infer U)[]]\n ? U\n : never;\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).\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: Form<TSchema>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: string | ((state: FormState<unknown>) => string),\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>>,\n>(\n form: Form<TSchema>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: string | ((state: FormState<unknown>) => string),\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 error: state.errors[path],\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Reconcile ids against the live items every render, using the\n // derived-state-from-props pattern (a render-phase setState, which React\n // supports and immediately re-renders with) instead of mutating a ref during\n // render — a discarded concurrent render must not advance id bookkeeping,\n // and skipping the commit when ids look unchanged is unsound (a reorder\n // after uncommitted in-place edits would then match against a stale items\n // snapshot and glue ids to the wrong rows). The re-render is cheap: its\n // reconcile early-exits on the same items reference. When the form or path\n // changes, drop the previous array's ids but carry the counter forward so\n // freshly minted ids never collide with old ones.\n const [idEntry, setIdEntry] = useState<\n Readonly<{ form: FieldArrayFormApi; path: string; state: IdState }>\n >({ form, path, state: EMPTY_ID_STATE });\n const base =\n idEntry.form === form && idEntry.path === path\n ? idEntry.state\n : { ...EMPTY_ID_STATE, counter: idEntry.state.counter };\n const nextIdState = reconcileIds(base, items);\n if (\n idEntry.form !== form ||\n idEntry.path !== path ||\n idEntry.state !== nextIdState\n ) {\n setIdEntry({ form, path, state: nextIdState });\n }\n const ids = nextIdState.ids;\n\n const push = useCallback(\n (item: TItem) => form.arrayPush(path, item),\n [form, path],\n );\n\n const remove = useCallback(\n (index: number) => form.arrayRemove(path, index),\n [form, path],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => form.arrayInsert(path, index, item),\n [form, path],\n );\n\n const move = useCallback(\n (from: number, to: number) => form.arrayMove(path, from, to),\n [form, path],\n );\n\n const swap = useCallback(\n (a: number, b: number) => form.arraySwap(path, a, b),\n [form, path],\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 return useMemo(\n () => ({\n fields,\n items,\n length: items.length,\n error,\n push,\n remove,\n insert,\n move,\n swap,\n }),\n [fields, items, error, push, remove, insert, move, swap],\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/core/array.ts","../src/core/equality.ts","../src/core/path.ts","../src/core/validation.ts","../src/core/createForm.ts","../src/core/mode.ts","../src/react/useForm.ts","../src/react/FormContext.tsx","../src/react/useField.ts","../src/react/useFieldArray.ts","../src/react/useFormError.ts","../src/react/useFormFlags.ts","../src/react/useFormSelector.ts","../src/react/createFormHooks.ts","../src/react/inputProps.ts","../src/react/fields.tsx","../src/react/focusError.ts"],"names":["result","initialValue","useRef","useEffect","validateAsync","useStore","useShallow","useCallback","useMemo","jsx","useState"],"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,KAA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AAA,MAAM,mBAAA,GACJ,iBACC,IAAA,KAAS,MAAA,IAAa,SAAS,gBAAA,CAAiB,MAAM,EAAE,MAAA,IAAU,CAAA,CAAA;AACrE,EAAA,MAAM,aACJ,YAAA,CAAa,MAAA,GAAS,IAAI,YAAA,GAAe,mBAAA,GAAsB,WAAW,EAAC;AAC7E,EAAA,OAAO,aAAa,UAAU,CAAA;AAChC;AAwBO,IAAM,UAAA,GAAa,CAAC,IAAA,EAAc,IAAA,KAA+B;AACtE,EAAA,MAAM,QAAA,GAAW,iBAAA,CAAkB,IAAA,IAAQ,QAAQ,CAAA;AACnD,EAAA,OAAO,IAAA,KAAS,EAAA,GAAA,CACX,IAAA,KAAS,MAAA,IACR,QAAA,CAAS,iBAAiB,MAAM,CAAA,CAAE,MAAA,IAAU,CAAA,KAC5C,YAAA,CAAa,QAAQ,IACvB,YAAA,CAAa,QAAA,CAAS,MAAA,CAAO,CAAC,EAAA,KAAO,cAAA,CAAe,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACtE","file":"index.js","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\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","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 if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\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","import { isPlainObject } from \"./equality\";\n\nexport type PathSegment = string | number;\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\nexport const parsePath = (path: string): readonly PathSegment[] =>\n path === \"\"\n ? []\n : path.split(\".\").map((s) => (isIndexSegment(s) ? Number(s) : s));\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 numeric segment addresses a real\n// slot: an in-range array index, or a record key (containers decide,\n// mirroring readSegment). An out-of-range index — including any index into\n// an absent or non-container value — addresses no slot at all: a full-form\n// parse would never key an error there. Object properties reached by STRING\n// segments may be legitimately absent (an empty optional field is still\n// addressable). Returns the resolved value so callers don't walk the path\n// 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 outOfBounds =\n typeof segment === \"number\" &&\n (Array.isArray(acc.current)\n ? segment >= acc.current.length\n : !isPlainRecord(acc.current));\n return !acc.ok || outOfBounds\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(acc.current, segment) };\n },\n { ok: true, current: obj },\n );\n return walked.ok ? { exists: true, value: walked.current } : { exists: false };\n};\n\nconst writeIntoArray = (\n arr: readonly unknown[],\n index: number,\n rest: readonly PathSegment[],\n value: unknown,\n): readonly unknown[] => {\n const length = Math.max(arr.length, index + 1);\n return Array.from({ length }, (_, i) =>\n i === index ? writeSegments(arr[i], rest, value) : 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): 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);\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 { ...obj, [key]: writeSegments(obj[key], rest, value) };\n }\n\n // Absent (or non-container) value: create a container from the segment type.\n if (typeof head === \"number\") {\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray([], head, rest, value);\n }\n return { [head]: writeSegments(undefined, rest, value) };\n};\n\nexport const setAtPath = <T>(obj: T, path: string, value: unknown): T =>\n writeSegments(obj, parsePath(path), value) as T;\n","import { z } from \"zod\";\nimport { type PathSegment, parsePath } 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\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\nexport const flattenIssues = (\n issues: readonly z.core.$ZodIssue[],\n): ErrorMap =>\n issues\n .flatMap((issue) => expandIssue(issue, []))\n .reduce<Record<string, readonly string[]>>((acc, { path, message }) => {\n // Union branches often repeat the same complaint; drop exact duplicates.\n const existing = acc[path] ?? [];\n return existing.includes(message)\n ? acc\n : { ...acc, [path]: [...existing, message] };\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// 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 const child = shape[String(head)];\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.\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 return shape[segment] ?? 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 {\n type IndexMapper,\n insertAt,\n moveFromTo,\n reKeyByArrayPath,\n removeAt,\n swapIndices,\n} from \"./array\";\nimport { isFieldDirty, isPlainObject, valuesEqual } from \"./equality\";\nimport type { FieldPath, FieldValue } from \"./fieldPath\";\nimport type { ValidationMode } from \"./mode\";\nimport { getAtPath, setAtPath, slotAtPath } from \"./path\";\nimport type { BoolMap, ErrorMap, FormState } from \"./types\";\nimport {\n type FieldValidationResult,\n type SettledFieldValidationResult,\n type SettledValidationResult,\n type ValidationResult,\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<TSchema extends z.ZodType> = Readonly<{\n initialValues: z.input<TSchema>;\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}>;\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}>;\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\ntype ArrayItemOf<T> = T extends readonly (infer U)[] ? U : never;\n\n// Root-level errors (schema-wide .refine) live at the \"\" key.\ntype ErrorPath<TValues> = FieldPath<TValues> | \"\";\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<TSchema extends z.ZodType> = Readonly<{\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>>>(\n path: P,\n ) => FieldValue<z.input<TSchema>, P>;\n watchField: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n listener: (snapshot: FieldSnapshot<FieldValue<z.input<TSchema>, P>>) => void,\n ) => () => void;\n watchValue: <P extends FieldPath<z.input<TSchema>>>(\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>>>(\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>>, 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>>,\n errors: string | readonly string[],\n ) => void;\n setErrors: (errors: ErrorMap) => void;\n clearErrors: (path?: ErrorPath<z.input<TSchema>>) => 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>>) => 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>>>(\n path: P,\n ) => FieldSnapshot<FieldValue<z.input<TSchema>, P>>;\n validate: () => ValidationResult<z.output<TSchema>>;\n validateField: (path: ErrorPath<z.input<TSchema>>) => FieldValidationResult;\n // Returns a Promise (the async pass, already started) when the schema needs\n // async parsing — mirroring the \"pending\" result of validate/validateField.\n validateFields: (\n paths: readonly FieldPath<z.input<TSchema>>[],\n ) => boolean | Promise<boolean>;\n validateAsync: () => Promise<ValidationResult<z.output<TSchema>>>;\n validateFieldAsync: (\n path: ErrorPath<z.input<TSchema>>,\n ) => Promise<FieldValidationResult>;\n validateFieldsAsync: (\n paths: readonly FieldPath<z.input<TSchema>>[],\n ) => Promise<boolean>;\n submit: (\n onValid: SubmitHandler<TSchema>,\n onInvalid?: InvalidSubmitHandler,\n options?: SubmitOptions,\n ) => Promise<SubmitResult<z.output<TSchema>>>;\n arrayPush: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayRemove: (path: FieldPath<z.input<TSchema>>, index: number) => void;\n arrayInsert: <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n index: number,\n item: ArrayItemOf<NonNullable<FieldValue<z.input<TSchema>, P>>>,\n ) => void;\n arrayMove: (\n path: FieldPath<z.input<TSchema>>,\n from: number,\n to: number,\n ) => void;\n arraySwap: (path: FieldPath<z.input<TSchema>>, a: number, b: number) => 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\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 (valuesEqual(values, initial)) return [];\n if (isPlainObject(values) && isPlainObject(initial)) {\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 // valuesEqual said the objects differ, but no child diverges by its own\n // comparison — a key-count mismatch where the extra key holds undefined\n // ({} vs { nickname: undefined }). Report the object itself so diff()/\n // dirtyFields() stay non-empty whenever isFieldDirty/useIsDirty say dirty.\n return childPaths.length > 0 ? childPaths : [prefix];\n }\n return [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.\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 = 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]) => 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 const extra = Object.entries(server).filter(([k]) => schema[k] === undefined);\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\nexport const createForm = <TSchema extends z.ZodType>(\n schema: TSchema,\n options: CreateFormOptions<TSchema>,\n): Form<TSchema> => {\n type Values = z.input<TSchema>;\n\n const initialMode: ValidationMode = options.mode ?? \"onBlur\";\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 const store = createStore<FormState<Values>>(() => initial);\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 try {\n const result = validateSync(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 ): boolean | Promise<boolean> => {\n if (paths.length === 0) return true;\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 ? result.promise.then((r) => r.kind === \"valid\")\n : result.kind === \"valid\";\n }\n try {\n const result = validateSync(schema, store.getState().values);\n const fullErrors =\n result.kind === \"invalid\" ? result.errors : emptyErrors;\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(\n state.schemaErrors,\n pickScope(fullErrors, paths),\n paths,\n ),\n state.schemaErrors,\n ),\n // A validation explicitly targeting these paths supersedes any\n // server verdict on them.\n serverErrors: omitScope(state.serverErrors, paths),\n }),\n }));\n return Object.keys(fullErrors).every((k) => !inScopeOfAny(k, paths));\n } catch (e) {\n if (isAsyncRequiredError(e)) return validateFieldsAsync(paths);\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 // 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 scopedFieldErrors = (path: string): ErrorMap => {\n const values = store.getState().values;\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n validateSync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\n );\n };\n\n const scopedFieldErrorsAsync = async (\n path: string,\n values: Values,\n ): Promise<ErrorMap> => {\n const scope = fieldScopeFor(path, values);\n return scope.kind === \"skip\"\n ? emptyErrors\n : scopeSettledResult(\n await validateAsync(scope.schema, scope.value),\n path,\n scope.viaSubschema,\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 // How a field validation's scoped errors land in state. validateField(\"\")\n // is a whole-form pass, so it lands like validate() (server channel\n // untouched). A real field path also releases the server entries in its\n // scope — a validation explicitly targeting them supersedes the server\n // verdict. Shared by the sync and async passes so their commit semantics\n // cannot diverge.\n const commitFieldErrors = (\n state: FormState<Values>,\n scoped: ErrorMap,\n path: string,\n ): ErrorChannels =>\n path === \"\"\n ? commitFullPass(state, scoped)\n : errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(state.schemaErrors, scoped, [path]),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, [path]),\n });\n\n const validateField = (path: string): FieldValidationResult => {\n warnMissingSchemaPath(\"validateField\", path);\n try {\n const scoped = scopedFieldErrors(path);\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: state.errors[path],\n touched: state.touched[path] ?? false,\n dirty: isFieldDirty(value, getAtPath(state.initialValues, path)),\n isValidating: state.isValidating[path] ?? false,\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<boolean> => {\n if (paths.length === 0) return true;\n // Whole-form scope: same delegation as validateFields (see above).\n if (paths.some((p) => p === \"\")) {\n const result = await validateAsyncOnForm();\n return result.kind === \"valid\";\n }\n const passes = new Map(paths.map((p) => [p, claimPass(p)]));\n const valuesAtStart = store.getState().values;\n store.setState((state) => ({\n ...state,\n isValidating: paths.reduce<Record<string, boolean>>(\n (acc, p) => ({ ...acc, [p]: true }),\n { ...state.isValidating },\n ),\n }));\n\n const result = await validateAsync(schema, valuesAtStart);\n const fullErrors = result.kind === \"invalid\" ? result.errors : emptyErrors;\n const requestedValid = Object.keys(fullErrors).every(\n (k) => !inScopeOfAny(k, paths),\n );\n\n const live = store.getState();\n const stillCurrent = paths.filter(\n (p) => sequences.get(p) === passes.get(p),\n );\n if (live.values !== valuesAtStart) {\n if (stillCurrent.length > 0) {\n store.setState((state) => ({\n ...state,\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n }\n return requestedValid;\n }\n\n store.setState((state) => ({\n ...state,\n ...errorChannels(state, {\n schemaErrors: reuseErrorRefs(\n mergeScopedErrors(\n state.schemaErrors,\n pickScope(fullErrors, stillCurrent),\n stillCurrent,\n ),\n state.schemaErrors,\n ),\n serverErrors: omitScope(state.serverErrors, stillCurrent),\n }),\n isValidating: stillCurrent.reduce(\n (acc, p) => omitKey(acc, p),\n state.isValidating,\n ),\n }));\n\n return requestedValid;\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 store.setState((state) => ({\n ...state,\n isValidating: { ...state.isValidating, [path]: true },\n }));\n\n const scoped = await scopedFieldErrorsAsync(path, valuesAtStart);\n\n const live = store.getState();\n const stillOwns = sequences.get(path) === pass;\n if (!stillOwns || live.values !== valuesAtStart) {\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 if (current !== undefined && !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 store.setState((state) => {\n const live = getAtPath(state.values, path);\n const arr: readonly unknown[] = Array.isArray(live) ? live : [];\n return {\n ...state,\n values: setAtPath(state.values, path, nextArray(arr)),\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 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>>>(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>>>(path: P) =>\n snapshotField(store.getState(), path) as FieldSnapshot<\n FieldValue<z.input<TSchema>, P>\n >,\n watchField: <P extends FieldPath<z.input<TSchema>>>(\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>>>(\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 store.setState((state) => ({\n ...state,\n values: setAtPath(state.values, path, value),\n ...errorChannels(state, {\n serverErrors: releaseSpine(state.serverErrors, path),\n }),\n })),\n setValues: (next) =>\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 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 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 store.setState((state) => {\n const patch: Partial<FormState<Values>> = updater(state);\n if (Object.keys(patch).length === 0) return state;\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 return {\n ...next,\n ...errorChannels(state, {\n schemaErrors: next.schemaErrors,\n serverErrors: next.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 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 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 store.setState((state) => ({\n ...state,\n values: setAtPath(\n state.values,\n path,\n getAtPath(state.initialValues, path),\n ),\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 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 return submit(onValid, onInvalid, opts);\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 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 }) as Form<TSchema>;\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","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\";\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).\nexport const useForm = <TSchema extends z.ZodType>(\n schema: TSchema,\n options: CreateFormOptions<TSchema>,\n): Form<TSchema> => {\n const formRef = useRef<Form<TSchema> | 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 {\n type ReactNode,\n createContext,\n useContext,\n} from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\n\nexport type FormProviderProps<TSchema extends z.ZodType> = Readonly<{\n form: Form<TSchema>;\n children: ReactNode;\n}>;\n\nexport type FormContextApi<TSchema extends z.ZodType> = Readonly<{\n Provider: (props: FormProviderProps<TSchema>) => ReactNode;\n useFormContext: () => Form<TSchema>;\n}>;\n\nexport const createFormContext = <\n TSchema extends z.ZodType,\n>(): FormContextApi<TSchema> => {\n const Context = createContext<Form<TSchema> | null>(null);\n\n const Provider = ({ form, children }: FormProviderProps<TSchema>) => (\n <Context.Provider value={form}>{children}</Context.Provider>\n );\n\n const useFormContext = (): Form<TSchema> => {\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 { isFieldDirty } from \"../core/equality\";\nimport type { FieldPath, FieldValue } from \"../core/fieldPath\";\nimport { shouldValidateOn } from \"../core/mode\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport {\n type FieldValidationResult,\n emptyValueForSchema,\n fieldSchemaAtPath,\n isAsyncRequiredError,\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 validateFieldAsync(path: string): Promise<FieldValidationResult>;\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 error: readonly 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 validateAsync: () => Promise<FieldValidationResult>;\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// 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.\nexport function useField<TSchema extends z.ZodType>(\n form: Form<TSchema>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n): UseFieldReturn<unknown>;\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: string | ((state: FormState<unknown>) => string),\n options?: UseFieldOptions,\n): UseFieldReturn<TValue>;\nexport function useField<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>>,\n>(\n form: Form<TSchema>,\n path: P,\n options?: UseFieldOptions,\n): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\nexport function useField<TValue = unknown>(\n form: FieldFormApi,\n pathArg: string | ((state: FormState<unknown>) => string),\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 error: state.errors[p],\n touched: state.touched[p] ?? false,\n dirty: isFieldDirty(value, initialValue),\n isValidating: state.isValidating[p] ?? false,\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 = useMemo(() => {\n if (formSchema !== undefined) {\n const sub = fieldSchemaAtPath(formSchema, path);\n if (sub !== null) return emptyValueForSchema(sub);\n }\n return initialValue === null ? null : undefined;\n }, [formSchema, path, initialValue]);\n\n const debounceMs = options?.debounceMs;\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n debounceTimerRef.current = null;\n }\n };\n }, [form, path, debounceMs]);\n\n const triggerValidate = useCallback(() => {\n if (debounceMs !== undefined && debounceMs > 0) {\n if (debounceTimerRef.current !== null) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => {\n void form.validateFieldAsync(path);\n debounceTimerRef.current = null;\n }, debounceMs);\n return;\n }\n try {\n form.validateField(path);\n } catch (e) {\n if (isAsyncRequiredError(e)) {\n void form.validateFieldAsync(path);\n return;\n }\n throw e;\n }\n }, [form, path, debounceMs]);\n\n const setValue = useCallback(\n (value: TValue) => {\n form.setValue(path, value);\n const state = form.store.getState();\n if (\n shouldValidateOn(\n \"change\",\n state.mode,\n state.reValidateMode,\n state.submitCount > 0,\n state.touched[path] ?? false,\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 error: slice.error,\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, setValue, setTouched, setError, clearError, validate, validateAsync, onBlur],\n );\n}\n","import { useCallback, useMemo, useState } 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 { FieldPath, FieldValue } from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\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.\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}>;\n\nexport type FieldArrayEntry<TItem> = Readonly<{\n id: string;\n value: TItem;\n}>;\n\nexport type UseFieldArrayReturn<TItem> = Readonly<{\n fields: readonly FieldArrayEntry<TItem>[];\n items: readonly TItem[];\n length: number;\n error: readonly string[] | undefined;\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}>;\n\ntype IdState = Readonly<{\n items: readonly unknown[];\n ids: readonly string[];\n counter: number;\n}>;\n\nconst EMPTY_ID_STATE: IdState = { items: [], ids: [], counter: 0 };\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// Derive a stable id per item by reconciling the live items against the\n// previous render's items. Ids follow items by identity/value, so reorders,\n// resets, and mutations that bypass this hook all keep keys glued to their\n// rows — not just length-preserving appends/truncations. A same-index\n// fallback keeps an edited row's id (editing produces a fresh item\n// reference at the same position) without remounting it.\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 return prev;\n }\n\n // Bucket prev positions by item so duplicate primitives match in order.\n const buckets = prev.items.reduce<Map<unknown, number[]>>((acc, item, i) => {\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) => {\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 // Running 1-based mint count up to each position, so fresh ids number\n // consecutively without rebuilding the ids array per element.\n const mintCounts = reused.reduce<readonly number[]>((acc, id) => {\n const count = acc[acc.length - 1] ?? 0;\n return [...acc, id === null ? count + 1 : count];\n }, []);\n const minted = mintCounts[mintCounts.length - 1] ?? 0;\n const ids = reused.map(\n (id, i) => id ?? `__zfa_${prev.counter + (mintCounts[i] ?? 0)}`,\n );\n\n return { items: nextItems, ids, counter: prev.counter + minted };\n};\n\n// The element type at an array-valued path. FieldValue re-adds `| undefined`\n// for arrays reached through optional ancestors, so strip that before\n// extracting; a non-array path yields `never`, which makes every write\n// (`push(never)`) an immediate error instead of a silently-`unknown` bind.\nexport type ArrayItemOf<T> = [NonNullable<T>] extends [readonly (infer U)[]]\n ? U\n : never;\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).\nexport function useFieldArray<TSchema extends z.ZodType>(\n form: Form<TSchema>,\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n): UseFieldArrayReturn<unknown>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi & { readonly schema?: undefined },\n path: string | ((state: FormState<unknown>) => string),\n): UseFieldArrayReturn<TItem>;\nexport function useFieldArray<\n TSchema extends z.ZodType,\n P extends FieldPath<z.input<TSchema>>,\n>(\n form: Form<TSchema>,\n path: P,\n): UseFieldArrayReturn<ArrayItemOf<FieldValue<z.input<TSchema>, P>>>;\nexport function useFieldArray<TItem = unknown>(\n form: FieldArrayFormApi,\n pathArg: string | ((state: FormState<unknown>) => string),\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 error: state.errors[path],\n };\n }),\n );\n const items = slice.items;\n const error = slice.error;\n\n // Reconcile ids against the live items every render, using the\n // derived-state-from-props pattern (a render-phase setState, which React\n // supports and immediately re-renders with) instead of mutating a ref during\n // render — a discarded concurrent render must not advance id bookkeeping,\n // and skipping the commit when ids look unchanged is unsound (a reorder\n // after uncommitted in-place edits would then match against a stale items\n // snapshot and glue ids to the wrong rows). The re-render is cheap: its\n // reconcile early-exits on the same items reference. When the form or path\n // changes, drop the previous array's ids but carry the counter forward so\n // freshly minted ids never collide with old ones.\n const [idEntry, setIdEntry] = useState<\n Readonly<{ form: FieldArrayFormApi; path: string; state: IdState }>\n >({ form, path, state: EMPTY_ID_STATE });\n const base =\n idEntry.form === form && idEntry.path === path\n ? idEntry.state\n : { ...EMPTY_ID_STATE, counter: idEntry.state.counter };\n const nextIdState = reconcileIds(base, items);\n if (\n idEntry.form !== form ||\n idEntry.path !== path ||\n idEntry.state !== nextIdState\n ) {\n setIdEntry({ form, path, state: nextIdState });\n }\n const ids = nextIdState.ids;\n\n const push = useCallback(\n (item: TItem) => form.arrayPush(path, item),\n [form, path],\n );\n\n const remove = useCallback(\n (index: number) => form.arrayRemove(path, index),\n [form, path],\n );\n\n const insert = useCallback(\n (index: number, item: TItem) => form.arrayInsert(path, index, item),\n [form, path],\n );\n\n const move = useCallback(\n (from: number, to: number) => form.arrayMove(path, from, to),\n [form, path],\n );\n\n const swap = useCallback(\n (a: number, b: number) => form.arraySwap(path, a, b),\n [form, path],\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 return useMemo(\n () => ({\n fields,\n items,\n length: items.length,\n error,\n push,\n remove,\n insert,\n move,\n swap,\n }),\n [fields, items, error, push, remove, insert, move, swap],\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 { isFieldDirty } from \"../core/equality\";\nimport type { FieldPath } 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>>,\n>(form: Form<TSchema>, 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>>,\n>(form: Form<TSchema>, path?: P): boolean;\nexport function useIsValid(form: FormStateApi, path?: string): boolean {\n return useStore(form.store, (state) => {\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\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 { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\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<TSchema extends z.ZodType, U>(\n form: Form<TSchema>,\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<TSchema extends z.ZodType, U>(\n form: Form<TSchema>,\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 type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath, FieldValue } 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 ArrayItemOf,\n type FieldArrayFormApi,\n type UseFieldArrayReturn,\n useFieldArray,\n} from \"./useFieldArray\";\nimport { useFormError } from \"./useFormError\";\nimport {\n useIsDirty,\n useIsSubmitting,\n useIsValid,\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> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n options?: UseFieldOptions,\n ): UseFieldReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>>>(\n path: P,\n options?: UseFieldOptions,\n ): UseFieldReturn<FieldValue<z.input<TSchema>, P>>;\n};\n\nexport type BoundUseFieldArray<TSchema extends z.ZodType> = {\n (\n pathSelector: (state: FormState<z.input<TSchema>>) => string,\n ): UseFieldArrayReturn<unknown>;\n <P extends FieldPath<z.input<TSchema>>>(\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> = (\n path?: FieldPath<z.input<TSchema>>,\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<TSchema extends z.ZodType, N extends string> = Readonly<\n { [K in `use${Capitalize<N>}Field`]: BoundUseField<TSchema> } & {\n [K in `use${Capitalize<N>}FieldArray`]: BoundUseFieldArray<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> } & {\n [K in `use${Capitalize<N>}IsValid`]: BoundUseFlag<TSchema>;\n } & { [K in `use${Capitalize<N>}IsSubmitting`]: () => boolean } & {\n [K in `use${Capitalize<N>}SubmitCount`]: () => number;\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\nexport const createFormHooks = <\n TSchema extends z.ZodType,\n N extends string = \"\",\n>(\n form: Form<TSchema>,\n name?: N,\n): FormHooks<TSchema, N> => {\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 useBoundFieldArray = (\n path: string | ((state: FormState<unknown>) => string),\n ): UseFieldArrayReturn<unknown> => useFieldArray(structural, path);\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 useBoundIsSubmitting = (): boolean => useIsSubmitting(structural);\n\n const useBoundSubmitCount = (): number => useSubmitCount(structural);\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}FieldArray`]: useBoundFieldArray,\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}IsSubmitting`]: useBoundIsSubmitting,\n [`use${prefix}SubmitCount`]: useBoundSubmitCount,\n } as FormHooks<TSchema, N>;\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 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\nconst ariaInvalid = (field: Readonly<{ error: readonly string[] | undefined }>): true | undefined =>\n field.error !== undefined && field.error.length > 0 ? true : undefined;\n\n// A cleared input writes back `field.emptyValue` — null when the schema says\n// the field is nullable (useField introspects the form's zod schema), so\n// z.number().nullable() round-trips to a valid blank instead of an undefined\n// the schema 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 nullable field restores null, so it isn't\n // left permanently dirty (or invalid) by a visual no-op.\n field.setValue(\n (text === \"\" && field.emptyValue === null ? null : text) as T,\n );\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 field.setValue(\n (parsed.kind === \"number\" ? parsed.value : field.emptyValue) as T,\n );\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(\n (v === \"\" && field.emptyValue === null ? null : v) as T,\n );\n },\n onBlur: field.onBlur,\n});\n","import { type ChangeEvent, type ReactNode, useId, useState } from \"react\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath } from \"../core/fieldPath\";\nimport {\n checkboxProps,\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.\nexport type PathsOf<F extends FieldFormApi> = F extends Form<\n infer TSchema extends z.ZodType\n>\n ? FieldPath<z.input<TSchema>>\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\nconst hasError = (error: readonly string[] | undefined): boolean =>\n error !== undefined && error.length > 0;\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 hasError(error) ? (\n <span className=\"zf-error\" id={id} role=\"alert\">\n {error?.[0]}\n </span>\n ) : null;\n\nexport type TextFieldProps<F extends FieldFormApi = FieldFormApi> = Readonly<{\n form: F;\n path: PathsOf<F>;\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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<string | null | undefined>(form, path);\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <input\n id={id}\n ref={ref}\n {...textInputProps(field)}\n type={type}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type NumberFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n placeholder?: string;\n ref?: FieldRef<HTMLInputElement>;\n }>;\n\ntype 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).\nconst 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\": hasError(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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<number | null | undefined>(form, path);\n const binding = useNumberInput(field);\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <input\n id={id}\n ref={ref}\n type=\"text\"\n {...binding}\n placeholder={placeholder}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type CheckboxFieldProps<F extends FieldFormApi = FieldFormApi> =\n Readonly<{\n form: F;\n path: PathsOf<F>;\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 id = useId();\n const errorId = `${id}-error`;\n const field = useField<boolean | null | undefined>(form, path);\n return (\n <div className=\"zf-field\">\n <label htmlFor={id} className=\"zf-label\">\n <input\n id={id}\n ref={ref}\n {...checkboxProps(field)}\n aria-describedby={hasError(field.error) ? errorId : undefined}\n />{\" \"}\n {label}\n </label>\n <ErrorText id={errorId} error={field.error} />\n </div>\n );\n};\n\nexport type SelectFieldOption<T extends string> = Readonly<{\n value: T;\n label: ReactNode;\n}>;\n\nexport type SelectFieldProps<\n T extends string,\n F extends FieldFormApi = FieldFormApi,\n> = Readonly<{\n form: F;\n path: PathsOf<F>;\n label?: ReactNode;\n options: readonly SelectFieldOption<T>[];\n // Shown as a disabled first option while the field value is undefined, so\n // the select stays controlled and the blank state is visible instead of\n // silently displaying the first option.\n placeholder?: string;\n ref?: FieldRef<HTMLSelectElement>;\n}>;\n\nexport const SelectField = <T extends string, F extends FieldFormApi>({\n form,\n path,\n label,\n options,\n placeholder,\n ref,\n}: SelectFieldProps<T, F>) => {\n const id = useId();\n const errorId = `${id}-error`;\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<T | null | undefined>(form, path);\n // A nullable field must be clearable BACK to null through the UI, so its\n // empty option stays visible after a choice and stays selectable —\n // selectProps writes null for it. Everywhere else the empty option is\n // only a placeholder: visible while nothing is chosen, never selectable.\n const clearable = field.emptyValue === null;\n const showEmptyOption =\n clearable ||\n field.value === undefined ||\n field.value === null ||\n placeholder !== undefined;\n return (\n <div className=\"zf-field\">\n {label !== undefined ? (\n <label htmlFor={id} className=\"zf-label\">\n {label}\n </label>\n ) : null}\n <select\n id={id}\n ref={ref}\n {...selectProps(field)}\n aria-describedby={hasError(field.error) ? errorId : undefined}\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 <ErrorText id={errorId} error={field.error} />\n </div>\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, minus the ones that can't take focus. Hidden\n// and disabled controls, and controls inside a closed <dialog>, can't —\n// without the filter, a leading <input type=\"hidden\" name=\"csrf\"> would\n// swallow focusFirstError's root fallback, and a name match inside a\n// not-yet-opened dialog would shadow the visible one.\nconst focusableControls = (scope: ParentNode): readonly HTMLElement[] =>\n [\n ...scope.querySelectorAll<HTMLElement>(\n \"input[name], select[name], textarea[name]\",\n ),\n ].filter(\n (el) =>\n !el.matches(':disabled, [type=\"hidden\"]') &&\n el.closest(\"dialog:not([open])\") === null,\n );\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// 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. The bound components and prop builders set name={path}, so\n// 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 = focusableControls(scope);\n const fieldMatches = controls.filter((el) =>\n nameMatchesAny(el, erroredPaths),\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 ? fieldMatches : rootFallbackApplies ? controls : [];\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) and the same optional `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 controls = focusableControls(root ?? document);\n return path === \"\"\n ? (root !== undefined ||\n document.querySelectorAll(\"form\").length <= 1) &&\n focusFirstOf(controls)\n : focusFirstOf(controls.filter((el) => nameMatchesAny(el, [path])));\n};\n"]}