formstand 0.25.0 → 0.26.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/CHANGELOG.md CHANGED
@@ -1,5 +1,117 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.0 — 2026-11-12
4
+
5
+ ### Added
6
+
7
+ - `PersistHandle.flush()` writes the pending debounced draft now, for
8
+ the moments that cannot wait out the debounce (a route change, a
9
+ `pagehide` handler). `dispose()` flushes too; see Fixed below.
10
+ - `submit` and `handleSubmit` take an options object in the second
11
+ position: `submit(onValid, { onInvalid, onError, force })`, the shape
12
+ `useFormAction`'s `FormActionOptions` always had, so `submit(onValid,
13
+ undefined, { force: true })` is no longer the only spelling.
14
+ `SubmitOptions` gains `onInvalid`; a positional `onInvalid` wins when
15
+ both are given. The positional shape stays.
16
+ - `ErrorPath<TValues, D>` is exported: the path type `setError`,
17
+ `clearErrors`, `validateField` and `validateFieldAsync` take
18
+ (`FieldPath` plus the root `""`), for wrappers that forward those
19
+ calls.
20
+ - `createFormHooks` binds the three hooks it skipped while the docs
21
+ promised every hook: `use{Name}Action` and `use{Name}ActionState`
22
+ (the form-actions bridges) and `use{Name}Persist` (`usePersistForm`),
23
+ with the `BoundUseAction`, `BoundUseActionState` and `BoundUsePersist`
24
+ types exported.
25
+ - `FieldSnapshot` (from `getFieldState` and `watchField`) carries
26
+ `initialValue` and `firstError`, matching `useField`.
27
+ - `fillField`, `blurField` and `fillAndBlurField` from `formstand/testing`
28
+ return the `FieldValidationResult` when the gate validated
29
+ (`undefined` when it did not), so a test can await a pending async
30
+ refine instead of guessing a delay.
31
+
32
+ ### Fixed
33
+
34
+ - A throwing async refinement (a rejected fetch inside `refine(async
35
+ ...)`) left `isValidatingForm` or `isValidating[path]` at `true` for
36
+ good: none of the async passes released their flag when the parse
37
+ rejected, so every spinner and submit gate built on them stuck after
38
+ one network failure. The passes now release the flags they own before
39
+ the rejection travels on to whoever awaited them. The passes nobody
40
+ awaits, `validateOnMount` and the change and blur triggers inside
41
+ `useField`, report the error through `console.error` instead of
42
+ leaving an unhandled rejection.
43
+ - Switching a discriminated union's variant through its discriminant
44
+ (`useField(form, "payment.method").setValue("paypal")`, which is how
45
+ generated forms bind it) left the old variant's schema errors in place
46
+ until a full `validate()` ran, so `useIsValid` read `false` for a form
47
+ the schema accepted. A field-scoped pass that runs the full parse (any
48
+ path under a union or a refined object) now also drops the schema
49
+ errors elsewhere that the parse no longer reports. It still adds
50
+ nothing outside its scope.
51
+ - `setErrors({ field: [] })`, an `updateState` patch of either error
52
+ channel, and `restore()` kept empty lists as entries, where `setError`
53
+ and `addErrors` dropped them, so one state read valid to `useIsValid`,
54
+ errored to `useFormSteps`, and `[]` from `useField(...).error`. Every
55
+ writer now drops an empty list.
56
+ - A throwing `onInvalid` resolved `{ kind: "error" }` without calling
57
+ `onError`; it does now, like a throwing `onValid`.
58
+ - `persistForm`: unmounting inside the debounce window lost the last
59
+ edits, because `dispose()` cancelled the pending write. It writes the
60
+ draft first now.
61
+ - `persistForm`: `clear()` followed by `reset()` (the usual after-submit
62
+ pair) wrote the fresh baseline straight back as a draft, which the
63
+ next visit then adopted over whatever initial values the app had
64
+ meanwhile computed. After `clear()`, a rebase that leaves the form
65
+ pristine no longer writes; the next real edit does.
66
+ - `persistForm`: a draft stored before the schema gained a key erased
67
+ that key's initial value from `values` and `initialValues`, so
68
+ `reset()` could not bring it back and the user saw zod's generic
69
+ message instead of yours. Required keys the draft lacks are now filled
70
+ from the initial values (nested objects included); optional keys stay
71
+ absent, since an optional the user cleared looks the same.
72
+ - `persistForm`'s shape guard refused legitimate drafts: `z.coerce.number()`
73
+ behind a `""` initial value, and unions whose variants shape the same
74
+ key differently. The guard now asks the schema whether a kind change
75
+ is legitimate at the path before refusing, and a dev build logs why a
76
+ draft that was present got ignored (version mismatch, shape conflict
77
+ and its path, corrupt JSON), where `load()` used to return a silent
78
+ `false`.
79
+ - `usePersistForm` ignored a change of `options.storage` and kept writing
80
+ to the first storage it saw; it resubscribes on it, as it does for
81
+ `key`.
82
+ - `DateField` and `dateInputProps` threw `value.getTime is not a
83
+ function` at render after a persisted draft loaded a `Date` back as
84
+ the string JSON made of it (persist does not revive Dates, by design),
85
+ and the rewritten draft made the crash stick across visits. The input
86
+ now shows the string's calendar date; the schema still rejects it at
87
+ validation.
88
+ - `useFormSteps.goTo(NaN)` (a `Number("")` from an empty option)
89
+ recursed without bound and froze the tab. A target that is not a
90
+ finite number now resolves the current index.
91
+ - `parseNumberText`, behind `NumberField`, `numberInputProps` and
92
+ `useNumberInput`, accepted every JavaScript number literal, so typing
93
+ `0x10` stored 16. It reads plain decimal notation only.
94
+ - `useMaskedInput` cleared a required string field to `undefined` when
95
+ its key was omitted from the initial values, because the initial
96
+ value's type was the only signal. The current value counts too, so the
97
+ field clears to `""` and reports your message instead of zod's.
98
+ - `useField`'s `debounceMs` also delayed the blur validation. Blur now
99
+ drops a pending timer and validates at once.
100
+ - `useFields` returned a fresh object, `fields` array and `onBlur` on
101
+ every render while its sibling hooks memoize; it keeps its identity
102
+ until one of its fields changes. A paths tuple that changes length now
103
+ throws the hook's own message, ahead of React's hooks-count error.
104
+ - `FormstandDevtools` labelled a server error as "(showing)" or "(behind
105
+ a schema error)" by walking the flat schema-error map as a path, so a
106
+ root verdict always read as behind and a nested key always as
107
+ showing. It reads the key directly now.
108
+ - `FormstandDevtools` threw on a `bigint` value (`z.bigint()`), in the
109
+ value preview and in the diff; a bigint renders as its literal
110
+ spelling (`10n`).
111
+ - `FormstandDevtools` walked every leaf through `getFieldState` and ran
112
+ `diff()` on every store write while collapsed; a collapsed panel now
113
+ keeps only its store subscription.
114
+
3
115
  ## 0.25.0 — 2026-11-12
4
116
 
5
117
  ### Added
@@ -0,0 +1,22 @@
1
+ import { useStore } from 'zustand/react';
2
+ import { useShallow } from 'zustand/react/shallow';
3
+
4
+ // src/react/useFormSelector.ts
5
+ function useFormSelector(form, selector) {
6
+ return useStore(form.store, selector);
7
+ }
8
+ function useFormSelectorShallow(form, selector) {
9
+ return useStore(form.store, useShallow(selector));
10
+ }
11
+
12
+ // src/core/env.ts
13
+ var isDevBuild = () => typeof process === "undefined" || process.env?.["NODE_ENV"] !== "production";
14
+ var isDevToolsBuild = () => {
15
+ if (typeof process === "undefined") return false;
16
+ const env = process.env?.["NODE_ENV"];
17
+ return typeof env === "string" && env !== "production";
18
+ };
19
+
20
+ export { isDevBuild, isDevToolsBuild, useFormSelector, useFormSelectorShallow };
21
+ //# sourceMappingURL=chunk-XJ6W5CKB.js.map
22
+ //# sourceMappingURL=chunk-XJ6W5CKB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/useFormSelector.ts","../src/core/env.ts"],"names":[],"mappings":";;;;AAiCO,SAAS,eAAA,CACd,MACA,QAAA,EACG;AACH,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,KAAA,EAAO,QAAQ,CAAA;AACtC;AAcO,SAAS,sBAAA,CACd,MACA,QAAA,EACG;AACH,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,KAAA,EAAO,UAAA,CAAW,QAAQ,CAAC,CAAA;AAClD;;;AC/CO,IAAM,UAAA,GAAa,MACxB,OAAO,OAAA,KAAY,eACnB,OAAA,CAAQ,GAAA,GAAM,UAAU,CAAA,KAAM;AAWzB,IAAM,kBAAkB,MAAe;AAC5C,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,EAAa,OAAO,KAAA;AAC3C,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,GAAM,UAAU,CAAA;AACpC,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,YAAA;AAC5C","file":"chunk-XJ6W5CKB.js","sourcesContent":["import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type FormStateApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n}>;\n\nexport function useFormSelector<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above. Without\n// it, Form<TSchema> would structurally satisfy FormStateApi too and a\n// bad selector could silently widen to FormState<unknown>.\nexport function useFormSelector<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelector<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, selector);\n}\n\nexport function useFormSelectorShallow<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, useShallow(selector));\n}\n","// The dev-build test the library consults before emitting a console\n// warning. Bundlers that define NODE_ENV fold it to a constant and drop the\n// dev-only branches; the `typeof process` guard keeps the SAME expression\n// from throwing in a runtime that defines no `process` at all (a CDN/ESM\n// consumer, a test runner without the define). That last case matters most\n// on the submit path: handleSubmit promises never to reject, and the\n// warning that fires only when a save failed was the one line that could\n// break the promise exactly on the failure path. It FAILS OPEN on purpose:\n// an unknowable environment gets the warnings, which cost nothing but a\n// console line.\nexport const isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\n\n// The gate for the two sites that EXPOSE form state: the FormstandDevtools\n// panel (renders every value and error into the page) and the zustand\n// devtools middleware (streams every write to the Redux extension). These\n// must FAIL CLOSED: isDevBuild's \"no process means dev\" reading let a\n// CDN/ESM, Deno, or worker production build mount the panel and keep the\n// middleware live for any end user with the extension installed. Only a\n// readable NODE_ENV that is a string other than \"production\" counts as\n// development; no process, no env, or an unset NODE_ENV all read as\n// production here.\nexport const isDevToolsBuild = (): boolean => {\n if (typeof process === \"undefined\") return false;\n const env = process.env?.[\"NODE_ENV\"];\n return typeof env === \"string\" && env !== \"production\";\n};\n"]}
@@ -130,6 +130,7 @@ type SubmitHandler<TSchema extends z.ZodType> = (data: z.output<TSchema>) => voi
130
130
  type InvalidSubmitHandler = (errors: ErrorMap) => void;
131
131
  type SubmitOptions = Readonly<{
132
132
  force?: boolean;
133
+ onInvalid?: InvalidSubmitHandler;
133
134
  onError?: (error: unknown) => void;
134
135
  }>;
135
136
  type SubmitResult<TOutput> = Readonly<{
@@ -152,7 +153,9 @@ type ResetOptions = Readonly<{
152
153
  }>;
153
154
  type FieldSnapshot<TValue> = Readonly<{
154
155
  value: TValue;
156
+ initialValue: TValue;
155
157
  error: readonly string[] | undefined;
158
+ firstError: string | undefined;
156
159
  touched: boolean;
157
160
  dirty: boolean;
158
161
  isValidating: boolean;
@@ -188,15 +191,23 @@ type Form<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = R
188
191
  validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;
189
192
  validateFieldAsync: (path: ErrorPath<z.input<TSchema>, D>) => Promise<SettledFieldValidationResult>;
190
193
  validateFieldsAsync: (paths: readonly FieldPath<z.input<TSchema>, D>[]) => Promise<SettledFieldsValidationResult>;
191
- submit: (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions) => Promise<SubmitResult<z.output<TSchema>>>;
194
+ submit: {
195
+ (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions): Promise<SubmitResult<z.output<TSchema>>>;
196
+ (onValid: SubmitHandler<TSchema>, options: SubmitOptions): Promise<SubmitResult<z.output<TSchema>>>;
197
+ };
192
198
  arrayPush: <P extends ArrayFieldPath<z.input<TSchema>, D>>(path: P, item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>) => void;
193
199
  arrayRemove: (path: ArrayFieldPath<z.input<TSchema>, D>, index: number) => void;
194
200
  arrayInsert: <P extends ArrayFieldPath<z.input<TSchema>, D>>(path: P, index: number, item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>) => void;
195
201
  arrayMove: (path: ArrayFieldPath<z.input<TSchema>, D>, from: number, to: number) => void;
196
202
  arraySwap: (path: ArrayFieldPath<z.input<TSchema>, D>, a: number, b: number) => void;
197
- handleSubmit: (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions) => (event?: {
198
- preventDefault: () => void;
199
- }) => Promise<SubmitResult<z.output<TSchema>>>;
203
+ handleSubmit: {
204
+ (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions): (event?: {
205
+ preventDefault: () => void;
206
+ }) => Promise<SubmitResult<z.output<TSchema>>>;
207
+ (onValid: SubmitHandler<TSchema>, options: SubmitOptions): (event?: {
208
+ preventDefault: () => void;
209
+ }) => Promise<SubmitResult<z.output<TSchema>>>;
210
+ };
200
211
  diff: () => Readonly<Record<string, unknown>>;
201
212
  dirtyFields: () => readonly string[];
202
213
  snapshot: () => FormState<z.input<TSchema>>;
@@ -204,5 +215,5 @@ type Form<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = R
204
215
  }>;
205
216
  declare const createForm: <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(schema: TSchema, options: CreateFormOptions<TSchema, D>) => Form<TSchema, NoInfer<D>>;
206
217
 
207
- export { createForm as p, emptyValueForSchema as q, flattenIssues as r, isAsyncRequiredError as s, isClearableSchema as t, shouldValidateOn as u, validateAsync as v, validateSync as w };
208
- export type { ArrayFieldPath as A, BoolMap as B, CreateFormOptions as C, DefaultPathDepth as D, ErrorMap as E, Form as F, InvalidSubmitHandler as I, PathDepth as P, ReadonlyStoreApi as R, SettledFieldValidationResult as S, ValidationMode as V, FormState as a, FieldValidationResult as b, FieldPath as c, FieldValue as d, ArrayItemOf as e, FieldSnapshot as f, FieldsValidationResult as g, ResetOptions as h, SettledFieldsValidationResult as i, SettledValidationResult as j, SubmitHandler as k, SubmitOptions as l, SubmitResult as m, ValidationResult as n, ValidationTrigger as o };
218
+ export { createForm as q, emptyValueForSchema as r, flattenIssues as s, isAsyncRequiredError as t, isClearableSchema as u, shouldValidateOn as v, validateAsync as w, validateSync as x };
219
+ export type { ArrayFieldPath as A, BoolMap as B, CreateFormOptions as C, DefaultPathDepth as D, ErrorMap as E, Form as F, InvalidSubmitHandler as I, PathDepth as P, ReadonlyStoreApi as R, SettledFieldValidationResult as S, ValidationMode as V, FormState as a, FieldValidationResult as b, FieldPath as c, FieldValue as d, ArrayItemOf as e, ErrorPath as f, FieldSnapshot as g, FieldsValidationResult as h, ResetOptions as i, SettledFieldsValidationResult as j, SettledValidationResult as k, SubmitHandler as l, SubmitOptions as m, SubmitResult as n, ValidationResult as o, ValidationTrigger as p };
@@ -130,6 +130,7 @@ type SubmitHandler<TSchema extends z.ZodType> = (data: z.output<TSchema>) => voi
130
130
  type InvalidSubmitHandler = (errors: ErrorMap) => void;
131
131
  type SubmitOptions = Readonly<{
132
132
  force?: boolean;
133
+ onInvalid?: InvalidSubmitHandler;
133
134
  onError?: (error: unknown) => void;
134
135
  }>;
135
136
  type SubmitResult<TOutput> = Readonly<{
@@ -152,7 +153,9 @@ type ResetOptions = Readonly<{
152
153
  }>;
153
154
  type FieldSnapshot<TValue> = Readonly<{
154
155
  value: TValue;
156
+ initialValue: TValue;
155
157
  error: readonly string[] | undefined;
158
+ firstError: string | undefined;
156
159
  touched: boolean;
157
160
  dirty: boolean;
158
161
  isValidating: boolean;
@@ -188,15 +191,23 @@ type Form<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = R
188
191
  validateAsync: () => Promise<SettledValidationResult<z.output<TSchema>>>;
189
192
  validateFieldAsync: (path: ErrorPath<z.input<TSchema>, D>) => Promise<SettledFieldValidationResult>;
190
193
  validateFieldsAsync: (paths: readonly FieldPath<z.input<TSchema>, D>[]) => Promise<SettledFieldsValidationResult>;
191
- submit: (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions) => Promise<SubmitResult<z.output<TSchema>>>;
194
+ submit: {
195
+ (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions): Promise<SubmitResult<z.output<TSchema>>>;
196
+ (onValid: SubmitHandler<TSchema>, options: SubmitOptions): Promise<SubmitResult<z.output<TSchema>>>;
197
+ };
192
198
  arrayPush: <P extends ArrayFieldPath<z.input<TSchema>, D>>(path: P, item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>) => void;
193
199
  arrayRemove: (path: ArrayFieldPath<z.input<TSchema>, D>, index: number) => void;
194
200
  arrayInsert: <P extends ArrayFieldPath<z.input<TSchema>, D>>(path: P, index: number, item: ArrayItemOf<FieldValue<z.input<TSchema>, P>>) => void;
195
201
  arrayMove: (path: ArrayFieldPath<z.input<TSchema>, D>, from: number, to: number) => void;
196
202
  arraySwap: (path: ArrayFieldPath<z.input<TSchema>, D>, a: number, b: number) => void;
197
- handleSubmit: (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions) => (event?: {
198
- preventDefault: () => void;
199
- }) => Promise<SubmitResult<z.output<TSchema>>>;
203
+ handleSubmit: {
204
+ (onValid: SubmitHandler<TSchema>, onInvalid?: InvalidSubmitHandler, options?: SubmitOptions): (event?: {
205
+ preventDefault: () => void;
206
+ }) => Promise<SubmitResult<z.output<TSchema>>>;
207
+ (onValid: SubmitHandler<TSchema>, options: SubmitOptions): (event?: {
208
+ preventDefault: () => void;
209
+ }) => Promise<SubmitResult<z.output<TSchema>>>;
210
+ };
200
211
  diff: () => Readonly<Record<string, unknown>>;
201
212
  dirtyFields: () => readonly string[];
202
213
  snapshot: () => FormState<z.input<TSchema>>;
@@ -204,5 +215,5 @@ type Form<TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth> = R
204
215
  }>;
205
216
  declare const createForm: <TSchema extends z.ZodType, D extends PathDepth = DefaultPathDepth>(schema: TSchema, options: CreateFormOptions<TSchema, D>) => Form<TSchema, NoInfer<D>>;
206
217
 
207
- export { createForm as p, emptyValueForSchema as q, flattenIssues as r, isAsyncRequiredError as s, isClearableSchema as t, shouldValidateOn as u, validateAsync as v, validateSync as w };
208
- export type { ArrayFieldPath as A, BoolMap as B, CreateFormOptions as C, DefaultPathDepth as D, ErrorMap as E, Form as F, InvalidSubmitHandler as I, PathDepth as P, ReadonlyStoreApi as R, SettledFieldValidationResult as S, ValidationMode as V, FormState as a, FieldValidationResult as b, FieldPath as c, FieldValue as d, ArrayItemOf as e, FieldSnapshot as f, FieldsValidationResult as g, ResetOptions as h, SettledFieldsValidationResult as i, SettledValidationResult as j, SubmitHandler as k, SubmitOptions as l, SubmitResult as m, ValidationResult as n, ValidationTrigger as o };
218
+ export { createForm as q, emptyValueForSchema as r, flattenIssues as s, isAsyncRequiredError as t, isClearableSchema as u, shouldValidateOn as v, validateAsync as w, validateSync as x };
219
+ export type { ArrayFieldPath as A, BoolMap as B, CreateFormOptions as C, DefaultPathDepth as D, ErrorMap as E, Form as F, InvalidSubmitHandler as I, PathDepth as P, ReadonlyStoreApi as R, SettledFieldValidationResult as S, ValidationMode as V, FormState as a, FieldValidationResult as b, FieldPath as c, FieldValue as d, ArrayItemOf as e, ErrorPath as f, FieldSnapshot as g, FieldsValidationResult as h, ResetOptions as i, SettledFieldsValidationResult as j, SettledValidationResult as k, SubmitHandler as l, SubmitOptions as m, SubmitResult as n, ValidationResult as o, ValidationTrigger as p };
@@ -13,40 +13,6 @@ var isDevToolsBuild = () => {
13
13
  const env = process.env?.["NODE_ENV"];
14
14
  return typeof env === "string" && env !== "production";
15
15
  };
16
-
17
- // src/core/path.ts
18
- var isIndexSegment = (s) => {
19
- const n = Number(s);
20
- return Number.isInteger(n) && n >= 0 && String(n) === s;
21
- };
22
- var PARSE_CACHE_MAX = 4096;
23
- var parseCache = /* @__PURE__ */ new Map();
24
- var parsePath = (path) => {
25
- const cached = parseCache.get(path);
26
- if (cached !== void 0) {
27
- parseCache.delete(path);
28
- parseCache.set(path, cached);
29
- return cached;
30
- }
31
- const segments = Object.freeze(
32
- path === "" ? [] : path.split(".").map((s) => isIndexSegment(s) ? Number(s) : s)
33
- );
34
- if (parseCache.size >= PARSE_CACHE_MAX) {
35
- const oldest = parseCache.keys().next().value;
36
- if (oldest !== void 0) parseCache.delete(oldest);
37
- }
38
- parseCache.set(path, segments);
39
- return segments;
40
- };
41
- var isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
42
- var readSegment = (obj, segment) => {
43
- if (obj == null) return void 0;
44
- if (Array.isArray(obj)) {
45
- return typeof segment === "number" ? obj[segment] : void 0;
46
- }
47
- return isPlainRecord(obj) && Object.hasOwn(obj, String(segment)) ? obj[String(segment)] : void 0;
48
- };
49
- var getAtPath = (obj, path) => parsePath(path).reduce(readSegment, obj);
50
16
  function useFormSelectorShallow(form, selector) {
51
17
  return react$1.useStore(form.store, shallow.useShallow(selector));
52
18
  }
@@ -163,10 +129,12 @@ var styles = {
163
129
  cursor: "pointer"
164
130
  }
165
131
  };
132
+ var jsonReplacer = (_key, value) => typeof value === "bigint" ? `${String(value)}n` : value;
166
133
  var preview = (value) => {
167
134
  if (value === void 0) return "undefined";
168
135
  if (value instanceof Date) return value.toISOString();
169
- const json = JSON.stringify(value);
136
+ if (typeof value === "bigint") return `${String(value)}n`;
137
+ const json = JSON.stringify(value, jsonReplacer);
170
138
  return json === void 0 ? String(value) : json.length > 60 ? `${json.slice(0, 57)}\u2026` : json;
171
139
  };
172
140
  var flags = (row) => [
@@ -193,14 +161,12 @@ var Section = ({
193
161
  /* @__PURE__ */ jsxRuntime.jsx("p", { style: styles.sectionTitle, children: title }),
194
162
  children
195
163
  ] });
196
- var DevtoolsPanel = ({
164
+ var OpenPanel = ({
197
165
  form,
198
- position = "bottom-right",
199
- defaultOpen = false,
200
- label = "formstand"
166
+ state,
167
+ label,
168
+ onClose
201
169
  }) => {
202
- const state = useDevtoolsState(form);
203
- const [open, setOpen] = react.useState(defaultOpen);
204
170
  const [held, setHeld] = react.useState(null);
205
171
  const rows = leafPaths(state.values).map((path) => {
206
172
  const field = form.getFieldState(path);
@@ -218,7 +184,7 @@ var DevtoolsPanel = ({
218
184
  rows.map((row) => row.path)
219
185
  );
220
186
  const diff = form.diff();
221
- return /* @__PURE__ */ jsxRuntime.jsx("div", { style: { ...styles.root, ...anchorFor(position) }, children: open ? /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.panel, children: [
187
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.panel, children: [
222
188
  /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.header, children: [
223
189
  /* @__PURE__ */ jsxRuntime.jsx("strong", { children: label }),
224
190
  /* @__PURE__ */ jsxRuntime.jsxs("span", { style: styles.muted, children: [
@@ -227,15 +193,7 @@ var DevtoolsPanel = ({
227
193
  state.isValidatingForm ? " \xB7 validating" : "",
228
194
  state.submitCount > 0 ? ` \xB7 submits ${state.submitCount}` : ""
229
195
  ] }),
230
- /* @__PURE__ */ jsxRuntime.jsx(
231
- "button",
232
- {
233
- type: "button",
234
- style: styles.button,
235
- onClick: () => setOpen(false),
236
- children: "close"
237
- }
238
- )
196
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", style: styles.button, onClick: onClose, children: "close" })
239
197
  ] }),
240
198
  /* @__PURE__ */ jsxRuntime.jsx(Section, { title: `fields (${rows.length})`, children: /* @__PURE__ */ jsxRuntime.jsxs("table", { style: styles.table, children: [
241
199
  /* @__PURE__ */ jsxRuntime.jsx("thead", { children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
@@ -274,10 +232,10 @@ var DevtoolsPanel = ({
274
232
  " ",
275
233
  /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.error, children: messages.join(", ") }),
276
234
  " ",
277
- /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.muted, children: getAtPath(state.schemaErrors, key) === void 0 ? "(showing)" : "(behind a schema error)" })
235
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.muted, children: Object.hasOwn(state.schemaErrors, key) ? "(behind a schema error)" : "(showing)" })
278
236
  ] }, key))
279
237
  ] }),
280
- /* @__PURE__ */ jsxRuntime.jsx(Section, { title: "diff vs initial", children: /* @__PURE__ */ jsxRuntime.jsx("pre", { style: styles.pre, children: Object.keys(diff).length === 0 ? "clean" : JSON.stringify(diff, null, 2) }) }),
238
+ /* @__PURE__ */ jsxRuntime.jsx(Section, { title: "diff vs initial", children: /* @__PURE__ */ jsxRuntime.jsx("pre", { style: styles.pre, children: Object.keys(diff).length === 0 ? "clean" : JSON.stringify(diff, jsonReplacer, 2) }) }),
281
239
  /* @__PURE__ */ jsxRuntime.jsxs(Section, { title: "time travel", children: [
282
240
  /* @__PURE__ */ jsxRuntime.jsx(
283
241
  "button",
@@ -304,7 +262,25 @@ var DevtoolsPanel = ({
304
262
  " ",
305
263
  /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.muted, children: held === null ? "nothing held" : "snapshot held" })
306
264
  ] })
307
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(
265
+ ] });
266
+ };
267
+ var DevtoolsPanel = ({
268
+ form,
269
+ position = "bottom-right",
270
+ defaultOpen = false,
271
+ label = "formstand"
272
+ }) => {
273
+ const state = useDevtoolsState(form);
274
+ const [open, setOpen] = react.useState(defaultOpen);
275
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { style: { ...styles.root, ...anchorFor(position) }, children: open ? /* @__PURE__ */ jsxRuntime.jsx(
276
+ OpenPanel,
277
+ {
278
+ form,
279
+ state,
280
+ label,
281
+ onClose: () => setOpen(false)
282
+ }
283
+ ) : /* @__PURE__ */ jsxRuntime.jsxs(
308
284
  "button",
309
285
  {
310
286
  type: "button",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/env.ts","../../src/core/path.ts","../../src/react/useFormSelector.ts","../../src/devtools/paths.ts","../../src/devtools/styles.ts","../../src/devtools/FormstandDevtools.tsx"],"names":["useStore","useShallow","jsxs","jsx","useState"],"mappings":";;;;;;;;;;AAuBO,IAAM,kBAAkB,MAAe;AAC5C,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,EAAa,OAAO,KAAA;AAC3C,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,GAAM,UAAU,CAAA;AACpC,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,YAAA;AAC5C,CAAA;;;ACRA,IAAM,cAAA,GAAiB,CAAC,CAAA,KAAuB;AAC7C,EAAA,MAAM,CAAA,GAAI,OAAO,CAAC,CAAA;AAClB,EAAA,OAAO,MAAA,CAAO,UAAU,CAAC,CAAA,IAAK,KAAK,CAAA,IAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA;AACxD,CAAA;AAWA,IAAM,eAAA,GAAkB,IAAA;AACxB,IAAM,UAAA,uBAAiB,GAAA,EAAoC;AAEpD,IAAM,SAAA,GAAY,CAAC,IAAA,KAAyC;AACjE,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,GAAA,CAAI,IAAI,CAAA;AAClC,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,UAAA,CAAW,OAAO,IAAI,CAAA;AACtB,IAAA,UAAA,CAAW,GAAA,CAAI,MAAM,MAAM,CAAA;AAC3B,IAAA,OAAO,MAAA;AAAA,EACT;AAMA,EAAA,MAAM,WAAW,MAAA,CAAO,MAAA;AAAA,IACtB,SAAS,EAAA,GACL,EAAC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cesContent":["// The dev-build test the library consults before emitting a console\n// warning. Bundlers that define NODE_ENV fold it to a constant and drop the\n// dev-only branches; the `typeof process` guard keeps the SAME expression\n// from throwing in a runtime that defines no `process` at all (a CDN/ESM\n// consumer, a test runner without the define). That last case matters most\n// on the submit path: handleSubmit promises never to reject, and the\n// warning that fires only when a save failed was the one line that could\n// break the promise exactly on the failure path. It FAILS OPEN on purpose:\n// an unknowable environment gets the warnings, which cost nothing but a\n// console line.\nexport const isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\n\n// The gate for the two sites that EXPOSE form state: the FormstandDevtools\n// panel (renders every value and error into the page) and the zustand\n// devtools middleware (streams every write to the Redux extension). These\n// must FAIL CLOSED: isDevBuild's \"no process means dev\" reading let a\n// CDN/ESM, Deno, or worker production build mount the panel and keep the\n// middleware live for any end user with the extension installed. Only a\n// readable NODE_ENV that is a string other than \"production\" counts as\n// development; no process, no env, or an unset NODE_ENV all read as\n// production here.\nexport const isDevToolsBuild = (): boolean => {\n if (typeof process === \"undefined\") return false;\n const env = process.env?.[\"NODE_ENV\"];\n return typeof env === \"string\" && env !== \"production\";\n};\n","import { isPlainObject } from \"./equality\";\n\nexport type PathSegment = string | number;\n\n// What setAtPath creates at an ABSENT slot. The segment type alone cannot\n// tell a z.record keyed by numeric strings from an array (both read\n// \"lookup.0\"), so a caller that knows the schema hands in a resolver; it\n// answers for the dotted prefix being created and returns null where it\n// has no opinion, which falls back to the segment-type rule.\nexport type ContainerKind = \"array\" | \"record\";\nexport type ContainerKindAt = (prefix: string) => ContainerKind | null;\n\n// Segment keys containing \".\" are not addressable (paths are split on dots);\n// use nested objects or index-free keys instead.\n\n// Writes above this index are refused — a typo'd path like \"items.4294967296\"\n// must not allocate a multi-gigabyte array.\nconst MAX_ARRAY_INDEX = 100_000;\n\nconst isIndexSegment = (s: string): boolean => {\n const n = Number(s);\n return Number.isInteger(n) && n >= 0 && String(n) === s;\n};\n\n// Hot path: every field subscription re-resolves its path on every store\n// notification (getAtPath in selectors), so parsing is memoized — a form's\n// paths are a small fixed set. Bounded as an LRU over Map insertion order:\n// a hit re-inserts its key (moving it to the back) and an overflow evicts\n// the front, so an app whose LIVE path set exceeds the cap keeps its hot\n// paths cached instead of re-parsing every one of them after each reset\n// (the old wholesale clear). Eviction only costs re-parsing, never\n// correctness. Same delete-then-set recency idiom as useFieldArray's\n// per-path id cache.\nconst PARSE_CACHE_MAX = 4096;\nconst parseCache = new Map<string, readonly PathSegment[]>();\n\nexport const parsePath = (path: string): readonly PathSegment[] => {\n const cached = parseCache.get(path);\n if (cached !== undefined) {\n parseCache.delete(path);\n parseCache.set(path, cached);\n return cached;\n }\n // Frozen because the array is now SHARED across every caller (and cached):\n // parsePath is a public export, and pre-cache each call returned a private\n // array that was safe to mutate. Freezing enforces the `readonly` type at\n // runtime so an external `.sort()`/`.reverse()`/`.push()` throws instead of\n // silently corrupting the cache for every later lookup of this path.\n const segments = Object.freeze(\n path === \"\"\n ? []\n : path.split(\".\").map((s) => (isIndexSegment(s) ? Number(s) : s)),\n );\n if (parseCache.size >= PARSE_CACHE_MAX) {\n const oldest = parseCache.keys().next().value;\n if (oldest !== undefined) parseCache.delete(oldest);\n }\n parseCache.set(path, segments);\n return segments;\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n// The existing container decides how a segment is interpreted: arrays take\n// numeric segments as indices, records take any segment as a string key (so a\n// z.record keyed \"0\" reads/writes the record key, not an array index). Only\n// when the container is absent does the segment type pick what gets created.\nconst readSegment = (obj: unknown, segment: PathSegment): unknown => {\n if (obj == null) return undefined;\n if (Array.isArray(obj)) {\n return typeof segment === \"number\" ? obj[segment] : undefined;\n }\n // Own properties only: a runtime-built path like \"lookup.constructor\" on a\n // z.record must read as absent, not leak Object.prototype members as field\n // values.\n return isPlainRecord(obj) && Object.hasOwn(obj, String(segment))\n ? obj[String(segment)]\n : undefined;\n};\n\nexport const getAtPath = (obj: unknown, path: string): unknown =>\n parsePath(path).reduce<unknown>(readSegment, obj);\n\nexport type SlotAtPath =\n | Readonly<{ exists: true; value: unknown }>\n | Readonly<{ exists: false }>;\n\n// Resolve `path` while checking that every segment is read from a real\n// container: an in-range array index, or a key on a plain record (containers\n// decide, mirroring readSegment). A segment into an absent or non-container\n// value addresses no slot at all — a full-form parse would key that error at\n// the missing ANCESTOR, not here, so field-scoped validation must skip it\n// rather than parse the leaf's subschema against undefined (which would\n// fabricate a spurious \"required\" error the full pass never produces). Note\n// this checks the CONTAINER, not the value: a leaf that is undefined at the\n// FINAL step through a real record is still an addressable (legitimately\n// empty) slot. Returns the resolved value so callers don't walk twice.\nexport const slotAtPath = (obj: unknown, path: string): SlotAtPath => {\n const walked = parsePath(path).reduce<\n Readonly<{ ok: boolean; current: unknown }>\n >(\n (acc, segment) => {\n const container = acc.current;\n const addressable =\n typeof segment === \"number\"\n ? Array.isArray(container)\n ? segment < container.length\n : isPlainRecord(container)\n : isPlainRecord(container);\n return !acc.ok || !addressable\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n );\n return walked.ok ? { exists: true, value: walked.current } : { exists: false };\n};\n\n// Whether the path addresses an OWN slot: every step reads a real\n// container's own key / in-range array index, the final segment included.\n// This is stricter than slotAtPath, which treats a MISSING final key on a\n// real record as an addressable (legitimately empty) slot — here it reads\n// false. The consumer is setValue's identity guard: writing `undefined`\n// over an ABSENT key is NOT a no-op (it creates the key, a real state\n// change — key-count dirtiness, persisted shape), while writing it over a\n// key that exists holding undefined is.\nexport const hasOwnSlot = (obj: unknown, path: string): boolean =>\n parsePath(path).reduce<Readonly<{ ok: boolean; current: unknown }>>(\n (acc, segment) => {\n const container = acc.current;\n const owns = Array.isArray(container)\n ? typeof segment === \"number\" && segment < container.length\n : isPlainRecord(container) && Object.hasOwn(container, String(segment));\n return !acc.ok || !owns\n ? { ok: false, current: undefined }\n : { ok: true, current: readSegment(container, segment) };\n },\n { ok: true, current: obj },\n ).ok;\n\nconst writeIntoArray = (\n arr: readonly unknown[],\n index: number,\n rest: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): readonly unknown[] => {\n const length = Math.max(arr.length, index + 1);\n return Array.from({ length }, (_, i) =>\n i === index\n ? writeSegments(arr[i], rest, value, kindAt, [...prefix, index])\n : arr[i],\n );\n};\n\nconst refusesHugeIndex = (index: number): boolean => {\n if (index > MAX_ARRAY_INDEX) {\n console.warn(\n `[formstand] refusing to write array index ${index} (max ${MAX_ARRAY_INDEX}); value left unchanged.`,\n );\n return true;\n }\n return false;\n};\n\nconst writeSegments = (\n obj: unknown,\n segments: readonly PathSegment[],\n value: unknown,\n kindAt: ContainerKindAt | undefined,\n prefix: readonly PathSegment[],\n): unknown => {\n const [head, ...rest] = segments;\n if (head === undefined) return value;\n\n if (Array.isArray(obj)) {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray(obj, head, rest, value, kindAt, prefix);\n }\n\n // Records take any segment as a string key (mirroring readSegment), so a\n // z.record keyed by a large numeric id is writable — the array-index cap\n // only applies where an array actually exists or would be created.\n if (isPlainRecord(obj)) {\n // Spreading is only safe for PLAIN objects: spreading a Date/Map/Set or\n // class instance keeps own enumerable props but drops the prototype (and\n // for Map/Set, every entry) — the original would be silently destroyed.\n // Refuse, like the other unwritable shapes above.\n if (!isPlainObject(obj)) {\n console.warn(\n `[formstand] cannot write key \"${String(head)}\" through a non-plain object (Date/Map/Set/class instance); value left unchanged.`,\n );\n return obj;\n }\n const key = String(head);\n return {\n ...obj,\n [key]: writeSegments(obj[key], rest, value, kindAt, [...prefix, key]),\n };\n }\n\n // Absent (or non-container) value: create a container. The schema's\n // answer for this slot wins when the caller supplied one (a z.record\n // keyed \"0\" must not become an array, and a z.array must not become a\n // record); otherwise the segment type decides, as the docs state.\n const kind =\n kindAt?.(prefix.map(String).join(\".\")) ??\n (typeof head === \"number\" ? \"array\" : \"record\");\n if (kind === \"array\") {\n if (typeof head !== \"number\") {\n console.warn(\n `[formstand] cannot write string key \"${head}\" into an array; value left unchanged.`,\n );\n return obj;\n }\n if (refusesHugeIndex(head)) return obj;\n return writeIntoArray([], head, rest, value, kindAt, prefix);\n }\n const key = String(head);\n return { [key]: writeSegments(undefined, rest, value, kindAt, [...prefix, key]) };\n};\n\n// `containerKindAt` is optional so the bare utility keeps its segment-type\n// rule; createForm passes the schema-derived resolver from validation.ts.\nexport const setAtPath = <T>(\n obj: T,\n path: string,\n value: unknown,\n containerKindAt?: ContainerKindAt,\n): T => writeSegments(obj, parsePath(path), value, containerKindAt, []) as T;\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type FormStateApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n}>;\n\nexport function useFormSelector<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above. Without\n// it, Form<TSchema> would structurally satisfy FormStateApi too and a\n// bad selector could silently widen to FormState<unknown>.\nexport function useFormSelector<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelector<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, selector);\n}\n\nexport function useFormSelectorShallow<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, useShallow(selector));\n}\n","// Walking a values object into the list of paths the panel shows.\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n // A Date is a leaf, not a container to recurse into: its own keys are\n // methods, and useField binds the Date itself.\n !(value instanceof Date);\n\n// The addressable leaf paths of a values object, in declaration order.\n// Arrays contribute one path per ROW rather than one for the array, because\n// that is what a field binds to; the array's own path still shows up in the\n// panel via the error map, which is where `z.array().min(1)` lands.\n//\n// An empty object or array is itself a leaf here. It has no children to\n// describe, and dropping it would hide a field that exists in the schema.\nexport const leafPaths = (value: unknown, base = \"\"): readonly string[] => {\n const join = (key: string | number): string =>\n base === \"\" ? String(key) : `${base}.${String(key)}`;\n\n if (Array.isArray(value)) {\n return value.length === 0\n ? [base]\n : value.flatMap((item, index) => leafPaths(item, join(index)));\n }\n if (isPlainObject(value)) {\n const keys = Object.keys(value);\n return keys.length === 0\n ? [base]\n : keys.flatMap((key) => leafPaths(value[key], join(key)));\n }\n return [base];\n};\n\n// Error keys that no leaf path covers: the root \"\" key (a schema-wide\n// refine), array-level messages keyed at the container, and server verdicts\n// written at a path that holds no value yet. Without this the panel would\n// silently drop exactly the errors that are hardest to debug.\nexport const unmatchedErrorKeys = (\n errorKeys: readonly string[],\n leaves: readonly string[],\n): readonly string[] => {\n const covered = new Set(leaves);\n return errorKeys.filter((key) => !covered.has(key));\n};\n","import type { CSSProperties } from \"react\";\n\n// Inline styles on purpose: a devtools panel that needs the consumer to\n// import a stylesheet is a devtools panel that renders unstyled the first\n// time someone tries it. Inline also means nothing here can leak into or be\n// overridden by the host app's CSS, which matters when the whole job is\n// showing you the truth about your form.\n\nexport type DevtoolsPosition =\n | \"bottom-right\"\n | \"bottom-left\"\n | \"top-right\"\n | \"top-left\";\n\nconst ANCHOR: Readonly<Record<DevtoolsPosition, CSSProperties>> = {\n \"bottom-right\": { bottom: 12, right: 12 },\n \"bottom-left\": { bottom: 12, left: 12 },\n \"top-right\": { top: 12, right: 12 },\n \"top-left\": { top: 12, left: 12 },\n};\n\nconst MONO =\n 'ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace';\n\nexport const anchorFor = (position: DevtoolsPosition): CSSProperties =>\n ANCHOR[position];\n\nexport const styles = {\n root: {\n position: \"fixed\",\n zIndex: 2147483000,\n fontFamily: MONO,\n fontSize: 11,\n lineHeight: 1.45,\n color: \"#e6e6e6\",\n colorScheme: \"dark\",\n } satisfies CSSProperties,\n toggle: {\n background: \"#1b1b1f\",\n border: \"1px solid #3a3a42\",\n color: \"#e6e6e6\",\n borderRadius: 6,\n padding: \"6px 10px\",\n font: \"inherit\",\n cursor: \"pointer\",\n } satisfies CSSProperties,\n panel: {\n width: \"min(440px, calc(100vw - 24px))\",\n maxHeight: \"min(60vh, 520px)\",\n overflow: \"auto\",\n background: \"#141417\",\n border: \"1px solid #3a3a42\",\n borderRadius: 8,\n boxShadow: \"0 12px 32px rgba(0,0,0,0.45)\",\n } satisfies CSSProperties,\n header: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n gap: 8,\n padding: \"8px 10px\",\n borderBottom: \"1px solid #2a2a31\",\n position: \"sticky\",\n top: 0,\n background: \"#141417\",\n } satisfies CSSProperties,\n section: { padding: \"8px 10px\", borderBottom: \"1px solid #23232a\" },\n sectionTitle: {\n color: \"#9aa0aa\",\n textTransform: \"uppercase\",\n letterSpacing: \"0.06em\",\n fontSize: 10,\n margin: \"0 0 6px\",\n } satisfies CSSProperties,\n table: {\n width: \"100%\",\n borderCollapse: \"collapse\",\n tableLayout: \"fixed\",\n } satisfies CSSProperties,\n th: {\n textAlign: \"left\",\n color: \"#9aa0aa\",\n fontWeight: 400,\n padding: \"2px 4px\",\n borderBottom: \"1px solid #2a2a31\",\n } satisfies CSSProperties,\n td: {\n padding: \"2px 4px\",\n verticalAlign: \"top\",\n wordBreak: \"break-word\",\n } satisfies CSSProperties,\n path: { color: \"#c8b6ff\" } satisfies CSSProperties,\n error: { color: \"#ff8f8f\" } satisfies CSSProperties,\n muted: { color: \"#7d838d\" } satisfies CSSProperties,\n flag: { color: \"#7ddca4\" } satisfies CSSProperties,\n pre: {\n margin: 0,\n whiteSpace: \"pre-wrap\",\n wordBreak: \"break-word\",\n } satisfies CSSProperties,\n button: {\n background: \"#22222a\",\n border: \"1px solid #3a3a42\",\n color: \"#e6e6e6\",\n borderRadius: 5,\n padding: \"3px 8px\",\n font: \"inherit\",\n cursor: \"pointer\",\n } satisfies CSSProperties,\n} as const;\n","import { type ReactNode, useState } from \"react\";\nimport { isDevToolsBuild } from \"../core/env\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n PathDepth,\n} from \"../core/fieldPath\";\nimport { getAtPath } from \"../core/path\";\nimport type { FormState } from \"../core/types\";\nimport { useFormSelectorShallow } from \"../react/useFormSelector\";\nimport { leafPaths, unmatchedErrorKeys } from \"./paths\";\nimport { type DevtoolsPosition, anchorFor, styles } from \"./styles\";\n\n// D (the form's typed-path depth budget) is carried so a `pathDepth: 12`\n// form is accepted: Form<S, 12> is deliberately not assignable to Form<S, 9>,\n// so the depth-less prop type rejected every widened form (TS2375).\nexport type FormstandDevtoolsProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n position?: DevtoolsPosition;\n defaultOpen?: boolean;\n /** Shown on the toggle, for telling two mounted panels apart. */\n label?: string;\n /**\n * Overrides the build gate. Unset, the panel renders only where NODE_ENV\n * is readable and not \"production\", which is what an app wants. `true`\n * mounts it regardless, for the one place where showing the form state\n * IS the page's purpose (a demo, an internal tool shipped in production\n * mode); `false` hides it in development without unmounting the form.\n */\n enabled?: boolean;\n}>;\n\ntype FieldRow = Readonly<{\n path: string;\n value: unknown;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// Non-production only, matching createForm's own devtools gate: the panel is\n// a debugging affordance, and shipping it to end users would leak the whole\n// form state into the page. Bundlers that define NODE_ENV drop the panel\n// entirely. The gate fails CLOSED (isDevToolsBuild): a runtime with no\n// readable NODE_ENV at all (a CDN/ESM consumer, Deno, a worker) renders\n// nothing rather than assuming it is a dev build the way the console\n// warnings may.\n\nconst preview = (value: unknown): string => {\n if (value === undefined) return \"undefined\";\n if (value instanceof Date) return value.toISOString();\n const json = JSON.stringify(value);\n // Long strings and big row objects would push the value column past the\n // panel; the full value is one expand away in the Values section.\n return json === undefined\n ? String(value)\n : json.length > 60\n ? `${json.slice(0, 57)}…`\n : json;\n};\n\nconst flags = (row: FieldRow): string =>\n [\n row.touched ? \"touched\" : \"\",\n row.dirty ? \"dirty\" : \"\",\n row.isValidating ? \"validating\" : \"\",\n ]\n .filter((flag) => flag !== \"\")\n .join(\" \");\n\n// Reads every slice the panel renders in ONE shallow-compared subscription.\n// Each member is a stored reference the form replaces on write, so shallow\n// equality is stable — deriving anything fresh (an array from dirtyFields())\n// inside the selector would hand the store a new reference every pass and\n// loop it (React #185).\nconst useDevtoolsState = <TSchema extends z.ZodType, D extends PathDepth>(\n form: Form<TSchema, D>,\n) =>\n useFormSelectorShallow(form, (state) => ({\n values: state.values,\n errors: state.errors,\n schemaErrors: state.schemaErrors,\n serverErrors: state.serverErrors,\n touched: state.touched,\n isValidating: state.isValidating,\n isSubmitting: state.isSubmitting,\n isValidatingForm: state.isValidatingForm,\n submitCount: state.submitCount,\n mode: state.mode,\n }));\n\nconst Section = ({\n title,\n children,\n}: Readonly<{ title: string; children: ReactNode }>) => (\n <div style={styles.section}>\n <p style={styles.sectionTitle}>{title}</p>\n {children}\n </div>\n);\n\nconst DevtoolsPanel = <TSchema extends z.ZodType, D extends PathDepth>({\n form,\n position = \"bottom-right\",\n defaultOpen = false,\n label = \"formstand\",\n}: FormstandDevtoolsProps<TSchema, D>) => {\n const state = useDevtoolsState(form);\n const [open, setOpen] = useState(defaultOpen);\n const [held, setHeld] = useState<FormState<z.input<TSchema>> | null>(null);\n\n // Computed every render rather than memoized. getFieldState and diff() read\n // through `form`, not through anything in a dependency array, so a memo\n // would need deps the linter can't see and would go stale the moment one\n // was missed. This component only re-renders when the subscription above\n // reports a real change, so recomputing is both cheap and always right.\n const rows: readonly FieldRow[] = leafPaths(state.values).map((path) => {\n // Runtime-built strings need the cast the typed surface documents.\n // getFieldState rather than re-deriving dirty here, so the panel reports\n // the library's own comparison rules (Dates by timestamp, deep for\n // containers) instead of offering a second opinion.\n const field = form.getFieldState(path as FieldPath<z.input<TSchema>, D>);\n return {\n path,\n value: field.value,\n error: field.error,\n touched: field.touched,\n dirty: field.dirty,\n isValidating: field.isValidating,\n };\n });\n\n const orphanErrors = unmatchedErrorKeys(\n Object.keys(state.errors),\n rows.map((row) => row.path),\n );\n\n const diff = form.diff();\n\n return (\n <div style={{ ...styles.root, ...anchorFor(position) }}>\n {open ? (\n <div style={styles.panel}>\n <div style={styles.header}>\n <strong>{label}</strong>\n <span style={styles.muted}>\n {state.mode}\n {state.isSubmitting ? \" · submitting\" : \"\"}\n {state.isValidatingForm ? \" · validating\" : \"\"}\n {state.submitCount > 0 ? ` · submits ${state.submitCount}` : \"\"}\n </span>\n <button\n type=\"button\"\n style={styles.button}\n onClick={() => setOpen(false)}\n >\n close\n </button>\n </div>\n\n <Section title={`fields (${rows.length})`}>\n <table style={styles.table}>\n <thead>\n <tr>\n <th style={{ ...styles.th, width: \"38%\" }}>path</th>\n <th style={styles.th}>value</th>\n <th style={{ ...styles.th, width: \"26%\" }}>state</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((row) => (\n <tr key={row.path}>\n <td style={{ ...styles.td, ...styles.path }}>{row.path}</td>\n <td style={styles.td}>\n {preview(row.value)}\n {row.error === undefined ? null : (\n <div style={styles.error}>{row.error.join(\", \")}</div>\n )}\n </td>\n <td style={{ ...styles.td, ...styles.flag }}>\n {flags(row)}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </Section>\n\n {orphanErrors.length === 0 ? null : (\n // Errors with no field of their own: the root \"\" key, array-level\n // messages, server verdicts on paths that hold no value yet.\n <Section title=\"errors without a field\">\n {orphanErrors.map((key) => (\n <div key={key}>\n <span style={styles.path}>{key === \"\" ? \"(root)\" : key}</span>{\" \"}\n <span style={styles.error}>\n {(state.errors[key] ?? []).join(\", \")}\n </span>\n </div>\n ))}\n </Section>\n )}\n\n <Section title=\"error channels\">\n <div style={styles.muted}>\n schema {Object.keys(state.schemaErrors).length} · server{\" \"}\n {Object.keys(state.serverErrors).length}\n </div>\n {Object.entries(state.serverErrors).map(([key, messages]) => (\n <div key={key}>\n <span style={styles.path}>{key === \"\" ? \"(root)\" : key}</span>{\" \"}\n <span style={styles.error}>{messages.join(\", \")}</span>{\" \"}\n <span style={styles.muted}>\n {getAtPath(state.schemaErrors, key) === undefined\n ? \"(showing)\"\n : \"(behind a schema error)\"}\n </span>\n </div>\n ))}\n </Section>\n\n <Section title=\"diff vs initial\">\n <pre style={styles.pre}>\n {Object.keys(diff).length === 0\n ? \"clean\"\n : JSON.stringify(diff, null, 2)}\n </pre>\n </Section>\n\n <Section title=\"time travel\">\n <button\n type=\"button\"\n style={styles.button}\n onClick={() => setHeld(form.snapshot())}\n >\n snapshot\n </button>{\" \"}\n <button\n type=\"button\"\n style={styles.button}\n disabled={held === null}\n onClick={() => {\n if (held !== null) form.restore(held);\n }}\n >\n restore\n </button>{\" \"}\n <span style={styles.muted}>\n {held === null ? \"nothing held\" : \"snapshot held\"}\n </span>\n </Section>\n </div>\n ) : (\n <button\n type=\"button\"\n style={styles.toggle}\n onClick={() => setOpen(true)}\n >\n {label}\n {Object.keys(state.errors).length > 0\n ? ` · ${String(Object.keys(state.errors).length)} err`\n : \"\"}\n </button>\n )}\n </div>\n );\n};\n\n/**\n * A form-aware debugging panel: every field's value, error, and flags, the\n * two error channels shown separately, the live diff against initial values,\n * and snapshot/restore time travel.\n *\n * Renders nothing in production builds, and nothing wherever NODE_ENV is not\n * readable (no `process` global, or one without NODE_ENV): the panel exposes\n * the whole form state, so an unknowable environment is treated as shipped.\n */\nexport const FormstandDevtools = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>({\n enabled,\n ...props\n}: FormstandDevtoolsProps<TSchema, D>) =>\n (enabled ?? isDevToolsBuild()) ? <DevtoolsPanel {...props} /> : null;\n"]}
1
+ {"version":3,"sources":["../../src/core/env.ts","../../src/react/useFormSelector.ts","../../src/devtools/paths.ts","../../src/devtools/styles.ts","../../src/devtools/FormstandDevtools.tsx"],"names":["useStore","useShallow","jsxs","jsx","useState"],"mappings":";;;;;;;;;;AAuBO,IAAM,kBAAkB,MAAe;AAC5C,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,EAAa,OAAO,KAAA;AAC3C,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,GAAM,UAAU,CAAA;AACpC,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,YAAA;AAC5C,CAAA;ACyBO,SAAS,sBAAA,CACd,MACA,QAAA,EACG;AACH,EAAA,OAAOA,gBAAA,CAAS,IAAA,CAAK,KAAA,EAAOC,kBAAA,CAAW,QAAQ,CAAC,CAAA;AAClD;;;ACvDA,IAAM,aAAA,GAAgB,CAAC,KAAA,KACrB,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACV,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAAA;AAGpB,EAAE,KAAA,YAAiB,IAAA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AAM,MAAA,CAAO,MAAA,CAAO,KAAK,KAAA,CAAM,MAAM,CAAA,CAAE,MAAM,CAAC,CAAA,IAAA,CAAA,GAC9C;AAAA;AAAA;AAAA,GACN,EAEJ,CAAA;AAEJ,CAAA;AAWO,IAAM,oBAAoB,CAG/B;AAAA,EACA,OAAA;AAAA,EACA,GAAG;AACL,CAAA,KACG,WAAW,eAAA,EAAgB,kCAAM,aAAA,EAAA,EAAe,GAAG,OAAO,CAAA,GAAK","file":"index.cjs","sourcesContent":["// The dev-build test the library consults before emitting a console\n// warning. Bundlers that define NODE_ENV fold it to a constant and drop the\n// dev-only branches; the `typeof process` guard keeps the SAME expression\n// from throwing in a runtime that defines no `process` at all (a CDN/ESM\n// consumer, a test runner without the define). That last case matters most\n// on the submit path: handleSubmit promises never to reject, and the\n// warning that fires only when a save failed was the one line that could\n// break the promise exactly on the failure path. It FAILS OPEN on purpose:\n// an unknowable environment gets the warnings, which cost nothing but a\n// console line.\nexport const isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\n\n// The gate for the two sites that EXPOSE form state: the FormstandDevtools\n// panel (renders every value and error into the page) and the zustand\n// devtools middleware (streams every write to the Redux extension). These\n// must FAIL CLOSED: isDevBuild's \"no process means dev\" reading let a\n// CDN/ESM, Deno, or worker production build mount the panel and keep the\n// middleware live for any end user with the extension installed. Only a\n// readable NODE_ENV that is a string other than \"production\" counts as\n// development; no process, no env, or an unset NODE_ENV all read as\n// production here.\nexport const isDevToolsBuild = (): boolean => {\n if (typeof process === \"undefined\") return false;\n const env = process.env?.[\"NODE_ENV\"];\n return typeof env === \"string\" && env !== \"production\";\n};\n","import type { z } from \"zod\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand/react\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { Form } from \"../core/createForm\";\nimport type { DefaultPathDepth, PathDepth } from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\n\ntype ReadonlyStore<T> = Pick<\n StoreApi<T>,\n \"getState\" | \"getInitialState\" | \"subscribe\"\n>;\n\nexport type FormStateApi = Readonly<{\n store: ReadonlyStore<FormState<unknown>>;\n}>;\n\nexport function useFormSelector<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\n// The `schema?: undefined` brand forces Form<TSchema> (which has a real\n// `schema` property) to bind only the typed overload above. Without\n// it, Form<TSchema> would structurally satisfy FormStateApi too and a\n// bad selector could silently widen to FormState<unknown>.\nexport function useFormSelector<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelector<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, selector);\n}\n\nexport function useFormSelectorShallow<\n TSchema extends z.ZodType,\n U,\n D extends PathDepth = DefaultPathDepth,\n>(\n form: Form<TSchema, D>,\n selector: (state: FormState<z.input<TSchema>>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi & { readonly schema?: undefined },\n selector: (state: FormState<unknown>) => U,\n): U;\nexport function useFormSelectorShallow<U>(\n form: FormStateApi,\n selector: (state: FormState<unknown>) => U,\n): U {\n return useStore(form.store, useShallow(selector));\n}\n","// Walking a values object into the list of paths the panel shows.\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n // A Date is a leaf, not a container to recurse into: its own keys are\n // methods, and useField binds the Date itself.\n !(value instanceof Date);\n\n// The addressable leaf paths of a values object, in declaration order.\n// Arrays contribute one path per ROW rather than one for the array, because\n// that is what a field binds to; the array's own path still shows up in the\n// panel via the error map, which is where `z.array().min(1)` lands.\n//\n// An empty object or array is itself a leaf here. It has no children to\n// describe, and dropping it would hide a field that exists in the schema.\nexport const leafPaths = (value: unknown, base = \"\"): readonly string[] => {\n const join = (key: string | number): string =>\n base === \"\" ? String(key) : `${base}.${String(key)}`;\n\n if (Array.isArray(value)) {\n return value.length === 0\n ? [base]\n : value.flatMap((item, index) => leafPaths(item, join(index)));\n }\n if (isPlainObject(value)) {\n const keys = Object.keys(value);\n return keys.length === 0\n ? [base]\n : keys.flatMap((key) => leafPaths(value[key], join(key)));\n }\n return [base];\n};\n\n// Error keys that no leaf path covers: the root \"\" key (a schema-wide\n// refine), array-level messages keyed at the container, and server verdicts\n// written at a path that holds no value yet. Without this the panel would\n// silently drop exactly the errors that are hardest to debug.\nexport const unmatchedErrorKeys = (\n errorKeys: readonly string[],\n leaves: readonly string[],\n): readonly string[] => {\n const covered = new Set(leaves);\n return errorKeys.filter((key) => !covered.has(key));\n};\n","import type { CSSProperties } from \"react\";\n\n// Inline styles on purpose: a devtools panel that needs the consumer to\n// import a stylesheet is a devtools panel that renders unstyled the first\n// time someone tries it. Inline also means nothing here can leak into or be\n// overridden by the host app's CSS, which matters when the whole job is\n// showing you the truth about your form.\n\nexport type DevtoolsPosition =\n | \"bottom-right\"\n | \"bottom-left\"\n | \"top-right\"\n | \"top-left\";\n\nconst ANCHOR: Readonly<Record<DevtoolsPosition, CSSProperties>> = {\n \"bottom-right\": { bottom: 12, right: 12 },\n \"bottom-left\": { bottom: 12, left: 12 },\n \"top-right\": { top: 12, right: 12 },\n \"top-left\": { top: 12, left: 12 },\n};\n\nconst MONO =\n 'ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace';\n\nexport const anchorFor = (position: DevtoolsPosition): CSSProperties =>\n ANCHOR[position];\n\nexport const styles = {\n root: {\n position: \"fixed\",\n zIndex: 2147483000,\n fontFamily: MONO,\n fontSize: 11,\n lineHeight: 1.45,\n color: \"#e6e6e6\",\n colorScheme: \"dark\",\n } satisfies CSSProperties,\n toggle: {\n background: \"#1b1b1f\",\n border: \"1px solid #3a3a42\",\n color: \"#e6e6e6\",\n borderRadius: 6,\n padding: \"6px 10px\",\n font: \"inherit\",\n cursor: \"pointer\",\n } satisfies CSSProperties,\n panel: {\n width: \"min(440px, calc(100vw - 24px))\",\n maxHeight: \"min(60vh, 520px)\",\n overflow: \"auto\",\n background: \"#141417\",\n border: \"1px solid #3a3a42\",\n borderRadius: 8,\n boxShadow: \"0 12px 32px rgba(0,0,0,0.45)\",\n } satisfies CSSProperties,\n header: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n gap: 8,\n padding: \"8px 10px\",\n borderBottom: \"1px solid #2a2a31\",\n position: \"sticky\",\n top: 0,\n background: \"#141417\",\n } satisfies CSSProperties,\n section: { padding: \"8px 10px\", borderBottom: \"1px solid #23232a\" },\n sectionTitle: {\n color: \"#9aa0aa\",\n textTransform: \"uppercase\",\n letterSpacing: \"0.06em\",\n fontSize: 10,\n margin: \"0 0 6px\",\n } satisfies CSSProperties,\n table: {\n width: \"100%\",\n borderCollapse: \"collapse\",\n tableLayout: \"fixed\",\n } satisfies CSSProperties,\n th: {\n textAlign: \"left\",\n color: \"#9aa0aa\",\n fontWeight: 400,\n padding: \"2px 4px\",\n borderBottom: \"1px solid #2a2a31\",\n } satisfies CSSProperties,\n td: {\n padding: \"2px 4px\",\n verticalAlign: \"top\",\n wordBreak: \"break-word\",\n } satisfies CSSProperties,\n path: { color: \"#c8b6ff\" } satisfies CSSProperties,\n error: { color: \"#ff8f8f\" } satisfies CSSProperties,\n muted: { color: \"#7d838d\" } satisfies CSSProperties,\n flag: { color: \"#7ddca4\" } satisfies CSSProperties,\n pre: {\n margin: 0,\n whiteSpace: \"pre-wrap\",\n wordBreak: \"break-word\",\n } satisfies CSSProperties,\n button: {\n background: \"#22222a\",\n border: \"1px solid #3a3a42\",\n color: \"#e6e6e6\",\n borderRadius: 5,\n padding: \"3px 8px\",\n font: \"inherit\",\n cursor: \"pointer\",\n } satisfies CSSProperties,\n} as const;\n","import { type ReactNode, useState } from \"react\";\nimport { isDevToolsBuild } from \"../core/env\";\nimport type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type {\n DefaultPathDepth,\n FieldPath,\n PathDepth,\n} from \"../core/fieldPath\";\nimport type { FormState } from \"../core/types\";\nimport { useFormSelectorShallow } from \"../react/useFormSelector\";\nimport { leafPaths, unmatchedErrorKeys } from \"./paths\";\nimport { type DevtoolsPosition, anchorFor, styles } from \"./styles\";\n\n// D (the form's typed-path depth budget) is carried so a `pathDepth: 12`\n// form is accepted: Form<S, 12> is deliberately not assignable to Form<S, 9>,\n// so the depth-less prop type rejected every widened form (TS2375).\nexport type FormstandDevtoolsProps<\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n> = Readonly<{\n form: Form<TSchema, D>;\n position?: DevtoolsPosition;\n defaultOpen?: boolean;\n /** Shown on the toggle, for telling two mounted panels apart. */\n label?: string;\n /**\n * Overrides the build gate. Unset, the panel renders only where NODE_ENV\n * is readable and not \"production\", which is what an app wants. `true`\n * mounts it regardless, for the one place where showing the form state\n * IS the page's purpose (a demo, an internal tool shipped in production\n * mode); `false` hides it in development without unmounting the form.\n */\n enabled?: boolean;\n}>;\n\ntype FieldRow = Readonly<{\n path: string;\n value: unknown;\n error: readonly string[] | undefined;\n touched: boolean;\n dirty: boolean;\n isValidating: boolean;\n}>;\n\n// Non-production only, matching createForm's own devtools gate: the panel is\n// a debugging affordance, and shipping it to end users would leak the whole\n// form state into the page. Bundlers that define NODE_ENV drop the panel\n// entirely. The gate fails CLOSED (isDevToolsBuild): a runtime with no\n// readable NODE_ENV at all (a CDN/ESM consumer, Deno, a worker) renders\n// nothing rather than assuming it is a dev build the way the console\n// warnings may.\n\n// JSON.stringify throws on a bigint (a z.bigint() field), which took the\n// whole panel down with it; a bigint renders as its literal spelling.\nconst jsonReplacer = (_key: string, value: unknown): unknown =>\n typeof value === \"bigint\" ? `${String(value)}n` : value;\n\nconst preview = (value: unknown): string => {\n if (value === undefined) return \"undefined\";\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"bigint\") return `${String(value)}n`;\n const json = JSON.stringify(value, jsonReplacer);\n // Long strings and big row objects would push the value column past the\n // panel; the full value is one expand away in the Values section.\n return json === undefined\n ? String(value)\n : json.length > 60\n ? `${json.slice(0, 57)}…`\n : json;\n};\n\nconst flags = (row: FieldRow): string =>\n [\n row.touched ? \"touched\" : \"\",\n row.dirty ? \"dirty\" : \"\",\n row.isValidating ? \"validating\" : \"\",\n ]\n .filter((flag) => flag !== \"\")\n .join(\" \");\n\n// Reads every slice the panel renders in ONE shallow-compared subscription.\n// Each member is a stored reference the form replaces on write, so shallow\n// equality is stable — deriving anything fresh (an array from dirtyFields())\n// inside the selector would hand the store a new reference every pass and\n// loop it (React #185).\nconst useDevtoolsState = <TSchema extends z.ZodType, D extends PathDepth>(\n form: Form<TSchema, D>,\n) =>\n useFormSelectorShallow(form, (state) => ({\n values: state.values,\n errors: state.errors,\n schemaErrors: state.schemaErrors,\n serverErrors: state.serverErrors,\n touched: state.touched,\n isValidating: state.isValidating,\n isSubmitting: state.isSubmitting,\n isValidatingForm: state.isValidatingForm,\n submitCount: state.submitCount,\n mode: state.mode,\n }));\n\ntype DevtoolsState<TValues> = ReturnType<\n typeof useDevtoolsState<z.ZodType<TValues>, PathDepth>\n>;\n\nconst Section = ({\n title,\n children,\n}: Readonly<{ title: string; children: ReactNode }>) => (\n <div style={styles.section}>\n <p style={styles.sectionTitle}>{title}</p>\n {children}\n </div>\n);\n\ntype OpenPanelProps<TSchema extends z.ZodType, D extends PathDepth> = Readonly<{\n form: Form<TSchema, D>;\n state: DevtoolsState<z.input<TSchema>>;\n label: string;\n onClose: () => void;\n}>;\n\n// The expanded panel. Rows and the diff are derived HERE, inside the open\n// branch, so a collapsed panel costs its store subscription and nothing\n// else: it used to walk every leaf through getFieldState and run diff() on\n// every store write while showing only the toggle.\nconst OpenPanel = <TSchema extends z.ZodType, D extends PathDepth>({\n form,\n state,\n label,\n onClose,\n}: OpenPanelProps<TSchema, D>) => {\n const [held, setHeld] = useState<FormState<z.input<TSchema>> | null>(null);\n\n // Computed every render rather than memoized. getFieldState and diff() read\n // through `form`, not through anything in a dependency array, so a memo\n // would need deps the linter can't see and would go stale the moment one\n // was missed. This component only re-renders when the subscription above\n // reports a real change, so recomputing is both cheap and always right.\n const rows: readonly FieldRow[] = leafPaths(state.values).map((path) => {\n // Runtime-built strings need the cast the typed surface documents.\n // getFieldState rather than re-deriving dirty here, so the panel reports\n // the library's own comparison rules (Dates by timestamp, deep for\n // containers) instead of offering a second opinion.\n const field = form.getFieldState(path as FieldPath<z.input<TSchema>, D>);\n return {\n path,\n value: field.value,\n error: field.error,\n touched: field.touched,\n dirty: field.dirty,\n isValidating: field.isValidating,\n };\n });\n\n const orphanErrors = unmatchedErrorKeys(\n Object.keys(state.errors),\n rows.map((row) => row.path),\n );\n\n const diff = form.diff();\n\n return (\n <div style={styles.panel}>\n <div style={styles.header}>\n <strong>{label}</strong>\n <span style={styles.muted}>\n {state.mode}\n {state.isSubmitting ? \" · submitting\" : \"\"}\n {state.isValidatingForm ? \" · validating\" : \"\"}\n {state.submitCount > 0 ? ` · submits ${state.submitCount}` : \"\"}\n </span>\n <button type=\"button\" style={styles.button} onClick={onClose}>\n close\n </button>\n </div>\n\n <Section title={`fields (${rows.length})`}>\n <table style={styles.table}>\n <thead>\n <tr>\n <th style={{ ...styles.th, width: \"38%\" }}>path</th>\n <th style={styles.th}>value</th>\n <th style={{ ...styles.th, width: \"26%\" }}>state</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((row) => (\n <tr key={row.path}>\n <td style={{ ...styles.td, ...styles.path }}>{row.path}</td>\n <td style={styles.td}>\n {preview(row.value)}\n {row.error === undefined ? null : (\n <div style={styles.error}>{row.error.join(\", \")}</div>\n )}\n </td>\n <td style={{ ...styles.td, ...styles.flag }}>{flags(row)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </Section>\n\n {orphanErrors.length === 0 ? null : (\n // Errors with no field of their own: the root \"\" key, array-level\n // messages, server verdicts on paths that hold no value yet.\n <Section title=\"errors without a field\">\n {orphanErrors.map((key) => (\n <div key={key}>\n <span style={styles.path}>{key === \"\" ? \"(root)\" : key}</span>{\" \"}\n <span style={styles.error}>\n {(state.errors[key] ?? []).join(\", \")}\n </span>\n </div>\n ))}\n </Section>\n )}\n\n <Section title=\"error channels\">\n <div style={styles.muted}>\n schema {Object.keys(state.schemaErrors).length} · server{\" \"}\n {Object.keys(state.serverErrors).length}\n </div>\n {Object.entries(state.serverErrors).map(([key, messages]) => (\n <div key={key}>\n <span style={styles.path}>{key === \"\" ? \"(root)\" : key}</span>{\" \"}\n <span style={styles.error}>{messages.join(\", \")}</span>{\" \"}\n <span style={styles.muted}>\n {/* The channels are FLAT maps keyed by path string: an own-key\n read, not a path walk, decides whether the schema speaks\n at this key. Walking the map as a path read the root \"\"\n as the whole map (always \"behind\") and split a nested key\n into segments it never had (always \"showing\"). */}\n {Object.hasOwn(state.schemaErrors, key)\n ? \"(behind a schema error)\"\n : \"(showing)\"}\n </span>\n </div>\n ))}\n </Section>\n\n <Section title=\"diff vs initial\">\n <pre style={styles.pre}>\n {Object.keys(diff).length === 0\n ? \"clean\"\n : JSON.stringify(diff, jsonReplacer, 2)}\n </pre>\n </Section>\n\n <Section title=\"time travel\">\n <button\n type=\"button\"\n style={styles.button}\n onClick={() => setHeld(form.snapshot())}\n >\n snapshot\n </button>{\" \"}\n <button\n type=\"button\"\n style={styles.button}\n disabled={held === null}\n onClick={() => {\n if (held !== null) form.restore(held);\n }}\n >\n restore\n </button>{\" \"}\n <span style={styles.muted}>\n {held === null ? \"nothing held\" : \"snapshot held\"}\n </span>\n </Section>\n </div>\n );\n};\n\nconst DevtoolsPanel = <TSchema extends z.ZodType, D extends PathDepth>({\n form,\n position = \"bottom-right\",\n defaultOpen = false,\n label = \"formstand\",\n}: FormstandDevtoolsProps<TSchema, D>) => {\n const state = useDevtoolsState(form);\n const [open, setOpen] = useState(defaultOpen);\n\n return (\n <div style={{ ...styles.root, ...anchorFor(position) }}>\n {open ? (\n <OpenPanel\n form={form}\n state={state}\n label={label}\n onClose={() => setOpen(false)}\n />\n ) : (\n <button\n type=\"button\"\n style={styles.toggle}\n onClick={() => setOpen(true)}\n >\n {label}\n {Object.keys(state.errors).length > 0\n ? ` · ${String(Object.keys(state.errors).length)} err`\n : \"\"}\n </button>\n )}\n </div>\n );\n};\n\n/**\n * A form-aware debugging panel: every field's value, error, and flags, the\n * two error channels shown separately, the live diff against initial values,\n * and snapshot/restore time travel.\n *\n * Renders nothing in production builds, and nothing wherever NODE_ENV is not\n * readable (no `process` global, or one without NODE_ENV): the panel exposes\n * the whole form state, so an unknowable environment is treated as shipped.\n */\nexport const FormstandDevtools = <\n TSchema extends z.ZodType,\n D extends PathDepth = DefaultPathDepth,\n>({\n enabled,\n ...props\n}: FormstandDevtoolsProps<TSchema, D>) =>\n (enabled ?? isDevToolsBuild()) ? <DevtoolsPanel {...props} /> : null;\n"]}