formstand 0.12.0 → 0.14.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.
@@ -0,0 +1,313 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var react$1 = require('zustand/react');
5
+ var shallow = require('zustand/react/shallow');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ // src/devtools/FormstandDevtools.tsx
9
+
10
+ // src/core/path.ts
11
+ var isIndexSegment = (s) => {
12
+ const n = Number(s);
13
+ return Number.isInteger(n) && n >= 0 && String(n) === s;
14
+ };
15
+ var PARSE_CACHE_MAX = 4096;
16
+ var parseCache = /* @__PURE__ */ new Map();
17
+ var parsePath = (path) => {
18
+ const cached = parseCache.get(path);
19
+ if (cached !== void 0) return cached;
20
+ const segments = Object.freeze(
21
+ path === "" ? [] : path.split(".").map((s) => isIndexSegment(s) ? Number(s) : s)
22
+ );
23
+ if (parseCache.size >= PARSE_CACHE_MAX) parseCache.clear();
24
+ parseCache.set(path, segments);
25
+ return segments;
26
+ };
27
+ var isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
28
+ var readSegment = (obj, segment) => {
29
+ if (obj == null) return void 0;
30
+ if (Array.isArray(obj)) {
31
+ return typeof segment === "number" ? obj[segment] : void 0;
32
+ }
33
+ return isPlainRecord(obj) && Object.hasOwn(obj, String(segment)) ? obj[String(segment)] : void 0;
34
+ };
35
+ var getAtPath = (obj, path) => parsePath(path).reduce(readSegment, obj);
36
+ function useFormSelectorShallow(form, selector) {
37
+ return react$1.useStore(form.store, shallow.useShallow(selector));
38
+ }
39
+
40
+ // src/devtools/paths.ts
41
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && // A Date is a leaf, not a container to recurse into: its own keys are
42
+ // methods, and useField binds the Date itself.
43
+ !(value instanceof Date);
44
+ var leafPaths = (value, base = "") => {
45
+ const join = (key) => base === "" ? String(key) : `${base}.${String(key)}`;
46
+ if (Array.isArray(value)) {
47
+ return value.length === 0 ? [base] : value.flatMap((item, index) => leafPaths(item, join(index)));
48
+ }
49
+ if (isPlainObject(value)) {
50
+ const keys = Object.keys(value);
51
+ return keys.length === 0 ? [base] : keys.flatMap((key) => leafPaths(value[key], join(key)));
52
+ }
53
+ return [base];
54
+ };
55
+ var unmatchedErrorKeys = (errorKeys, leaves) => {
56
+ const covered = new Set(leaves);
57
+ return errorKeys.filter((key) => !covered.has(key));
58
+ };
59
+
60
+ // src/devtools/styles.ts
61
+ var ANCHOR = {
62
+ "bottom-right": { bottom: 12, right: 12 },
63
+ "bottom-left": { bottom: 12, left: 12 },
64
+ "top-right": { top: 12, right: 12 },
65
+ "top-left": { top: 12, left: 12 }
66
+ };
67
+ var MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
68
+ var anchorFor = (position) => ANCHOR[position];
69
+ var styles = {
70
+ root: {
71
+ position: "fixed",
72
+ zIndex: 2147483e3,
73
+ fontFamily: MONO,
74
+ fontSize: 11,
75
+ lineHeight: 1.45,
76
+ color: "#e6e6e6",
77
+ colorScheme: "dark"
78
+ },
79
+ toggle: {
80
+ background: "#1b1b1f",
81
+ border: "1px solid #3a3a42",
82
+ color: "#e6e6e6",
83
+ borderRadius: 6,
84
+ padding: "6px 10px",
85
+ font: "inherit",
86
+ cursor: "pointer"
87
+ },
88
+ panel: {
89
+ width: "min(440px, calc(100vw - 24px))",
90
+ maxHeight: "min(60vh, 520px)",
91
+ overflow: "auto",
92
+ background: "#141417",
93
+ border: "1px solid #3a3a42",
94
+ borderRadius: 8,
95
+ boxShadow: "0 12px 32px rgba(0,0,0,0.45)"
96
+ },
97
+ header: {
98
+ display: "flex",
99
+ alignItems: "center",
100
+ justifyContent: "space-between",
101
+ gap: 8,
102
+ padding: "8px 10px",
103
+ borderBottom: "1px solid #2a2a31",
104
+ position: "sticky",
105
+ top: 0,
106
+ background: "#141417"
107
+ },
108
+ section: { padding: "8px 10px", borderBottom: "1px solid #23232a" },
109
+ sectionTitle: {
110
+ color: "#9aa0aa",
111
+ textTransform: "uppercase",
112
+ letterSpacing: "0.06em",
113
+ fontSize: 10,
114
+ margin: "0 0 6px"
115
+ },
116
+ table: {
117
+ width: "100%",
118
+ borderCollapse: "collapse",
119
+ tableLayout: "fixed"
120
+ },
121
+ th: {
122
+ textAlign: "left",
123
+ color: "#9aa0aa",
124
+ fontWeight: 400,
125
+ padding: "2px 4px",
126
+ borderBottom: "1px solid #2a2a31"
127
+ },
128
+ td: {
129
+ padding: "2px 4px",
130
+ verticalAlign: "top",
131
+ wordBreak: "break-word"
132
+ },
133
+ path: { color: "#c8b6ff" },
134
+ error: { color: "#ff8f8f" },
135
+ muted: { color: "#7d838d" },
136
+ flag: { color: "#7ddca4" },
137
+ pre: {
138
+ margin: 0,
139
+ whiteSpace: "pre-wrap",
140
+ wordBreak: "break-word"
141
+ },
142
+ button: {
143
+ background: "#22222a",
144
+ border: "1px solid #3a3a42",
145
+ color: "#e6e6e6",
146
+ borderRadius: 5,
147
+ padding: "3px 8px",
148
+ font: "inherit",
149
+ cursor: "pointer"
150
+ }
151
+ };
152
+ var isDevBuild = () => typeof process === "undefined" || process.env?.["NODE_ENV"] !== "production";
153
+ var preview = (value) => {
154
+ if (value === void 0) return "undefined";
155
+ if (value instanceof Date) return value.toISOString();
156
+ const json = JSON.stringify(value);
157
+ return json === void 0 ? String(value) : json.length > 60 ? `${json.slice(0, 57)}\u2026` : json;
158
+ };
159
+ var flags = (row) => [
160
+ row.touched ? "touched" : "",
161
+ row.dirty ? "dirty" : "",
162
+ row.isValidating ? "validating" : ""
163
+ ].filter((flag) => flag !== "").join(" ");
164
+ var useDevtoolsState = (form) => useFormSelectorShallow(form, (state) => ({
165
+ values: state.values,
166
+ errors: state.errors,
167
+ schemaErrors: state.schemaErrors,
168
+ serverErrors: state.serverErrors,
169
+ touched: state.touched,
170
+ isValidating: state.isValidating,
171
+ isSubmitting: state.isSubmitting,
172
+ isValidatingForm: state.isValidatingForm,
173
+ submitCount: state.submitCount,
174
+ mode: state.mode
175
+ }));
176
+ var Section = ({
177
+ title,
178
+ children
179
+ }) => /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.section, children: [
180
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: styles.sectionTitle, children: title }),
181
+ children
182
+ ] });
183
+ var DevtoolsPanel = ({
184
+ form,
185
+ position = "bottom-right",
186
+ defaultOpen = false,
187
+ label = "formstand"
188
+ }) => {
189
+ const state = useDevtoolsState(form);
190
+ const [open, setOpen] = react.useState(defaultOpen);
191
+ const [held, setHeld] = react.useState(null);
192
+ const rows = leafPaths(state.values).map((path) => {
193
+ const field = form.getFieldState(path);
194
+ return {
195
+ path,
196
+ value: field.value,
197
+ error: field.error,
198
+ touched: field.touched,
199
+ dirty: field.dirty,
200
+ isValidating: field.isValidating
201
+ };
202
+ });
203
+ const orphanErrors = unmatchedErrorKeys(
204
+ Object.keys(state.errors),
205
+ rows.map((row) => row.path)
206
+ );
207
+ const diff = form.diff();
208
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { style: { ...styles.root, ...anchorFor(position) }, children: open ? /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.panel, children: [
209
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.header, children: [
210
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: label }),
211
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { style: styles.muted, children: [
212
+ state.mode,
213
+ state.isSubmitting ? " \xB7 submitting" : "",
214
+ state.isValidatingForm ? " \xB7 validating" : "",
215
+ state.submitCount > 0 ? ` \xB7 submits ${state.submitCount}` : ""
216
+ ] }),
217
+ /* @__PURE__ */ jsxRuntime.jsx(
218
+ "button",
219
+ {
220
+ type: "button",
221
+ style: styles.button,
222
+ onClick: () => setOpen(false),
223
+ children: "close"
224
+ }
225
+ )
226
+ ] }),
227
+ /* @__PURE__ */ jsxRuntime.jsx(Section, { title: `fields (${rows.length})`, children: /* @__PURE__ */ jsxRuntime.jsxs("table", { style: styles.table, children: [
228
+ /* @__PURE__ */ jsxRuntime.jsx("thead", { children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
229
+ /* @__PURE__ */ jsxRuntime.jsx("th", { style: { ...styles.th, width: "38%" }, children: "path" }),
230
+ /* @__PURE__ */ jsxRuntime.jsx("th", { style: styles.th, children: "value" }),
231
+ /* @__PURE__ */ jsxRuntime.jsx("th", { style: { ...styles.th, width: "26%" }, children: "state" })
232
+ ] }) }),
233
+ /* @__PURE__ */ jsxRuntime.jsx("tbody", { children: rows.map((row) => /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
234
+ /* @__PURE__ */ jsxRuntime.jsx("td", { style: { ...styles.td, ...styles.path }, children: row.path }),
235
+ /* @__PURE__ */ jsxRuntime.jsxs("td", { style: styles.td, children: [
236
+ preview(row.value),
237
+ row.error === void 0 ? null : /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.error, children: row.error.join(", ") })
238
+ ] }),
239
+ /* @__PURE__ */ jsxRuntime.jsx("td", { style: { ...styles.td, ...styles.flag }, children: flags(row) })
240
+ ] }, row.path)) })
241
+ ] }) }),
242
+ orphanErrors.length === 0 ? null : (
243
+ // Errors with no field of their own: the root "" key, array-level
244
+ // messages, server verdicts on paths that hold no value yet.
245
+ /* @__PURE__ */ jsxRuntime.jsx(Section, { title: "errors without a field", children: orphanErrors.map((key) => /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
246
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.path, children: key === "" ? "(root)" : key }),
247
+ " ",
248
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.error, children: (state.errors[key] ?? []).join(", ") })
249
+ ] }, key)) })
250
+ ),
251
+ /* @__PURE__ */ jsxRuntime.jsxs(Section, { title: "error channels", children: [
252
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.muted, children: [
253
+ "schema ",
254
+ Object.keys(state.schemaErrors).length,
255
+ " \xB7 server",
256
+ " ",
257
+ Object.keys(state.serverErrors).length
258
+ ] }),
259
+ Object.entries(state.serverErrors).map(([key, messages]) => /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
260
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.path, children: key === "" ? "(root)" : key }),
261
+ " ",
262
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.error, children: messages.join(", ") }),
263
+ " ",
264
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.muted, children: getAtPath(state.schemaErrors, key) === void 0 ? "(showing)" : "(behind a schema error)" })
265
+ ] }, key))
266
+ ] }),
267
+ /* @__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) }) }),
268
+ /* @__PURE__ */ jsxRuntime.jsxs(Section, { title: "time travel", children: [
269
+ /* @__PURE__ */ jsxRuntime.jsx(
270
+ "button",
271
+ {
272
+ type: "button",
273
+ style: styles.button,
274
+ onClick: () => setHeld(form.snapshot()),
275
+ children: "snapshot"
276
+ }
277
+ ),
278
+ " ",
279
+ /* @__PURE__ */ jsxRuntime.jsx(
280
+ "button",
281
+ {
282
+ type: "button",
283
+ style: styles.button,
284
+ disabled: held === null,
285
+ onClick: () => {
286
+ if (held !== null) form.restore(held);
287
+ },
288
+ children: "restore"
289
+ }
290
+ ),
291
+ " ",
292
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.muted, children: held === null ? "nothing held" : "snapshot held" })
293
+ ] })
294
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(
295
+ "button",
296
+ {
297
+ type: "button",
298
+ style: styles.toggle,
299
+ onClick: () => setOpen(true),
300
+ children: [
301
+ label,
302
+ Object.keys(state.errors).length > 0 ? ` \xB7 ${String(Object.keys(state.errors).length)} err` : ""
303
+ ]
304
+ }
305
+ ) });
306
+ };
307
+ var FormstandDevtools = (props) => isDevBuild() ? /* @__PURE__ */ jsxRuntime.jsx(DevtoolsPanel, { ...props }) : null;
308
+
309
+ exports.FormstandDevtools = FormstandDevtools;
310
+ exports.leafPaths = leafPaths;
311
+ exports.unmatchedErrorKeys = unmatchedErrorKeys;
312
+ //# sourceMappingURL=index.cjs.map
313
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../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":";;;;;;;;;;AAWA,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;AAOA,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,MAAA,KAAW,QAAW,OAAO,MAAA;AAMjC,EAAA,MAAM,WAAW,MAAA,CAAO,MAAA;AAAA,IACtB,SAAS,EAAA,GACL,EAAC,GACD,IAAA,CAAK,MAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,MAAO,cAAA,CAAe,CAAC,IAAI,MAAA,CAAO,CAAC,IAAI,CAAE;AAAA,GACpE;AACA,EAAA,IAAI,UAAA,CAAW,IAAA,IAAQ,eAAA,EAAiB,UAAA,CAAW,KAAA,EAAM;AACzD,EAAA,UAAA,CAAW,GAAA,CAAI,MAAM,QAAQ,CAAA;AAC7B,EAAA,OAAO,QAAA;AACT,CA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AAA,KAAS,IAAA,EAAM,IAAA,CAAK,OAAA,CAAQ,IAAI,CAAA;AAAA,UACtC,CAAA;AAAA,UACD,QAAA,EAAA;AAAA;AAAA,OAED;AAAA,MAAU,GAAA;AAAA,sBACVA,cAAA,CAAC,UAAK,KAAA,EAAO,MAAA,CAAO,OACjB,QAAA,EAAA,IAAA,KAAS,IAAA,GAAO,iBAAiB,eAAA,EACpC;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA,mBAEAD,eAAA;AAAA,IAAC,QAAA;AAAA,IAAA;AAAA,MACC,IAAA,EAAK,QAAA;AAAA,MACL,OAAO,MAAA,CAAO,MAAA;AAAA,MACd,OAAA,EAAS,MAAM,OAAA,CAAQ,IAAI,CAAA;AAAA,MAE1B,QAAA,EAAA;AAAA,QAAA,KAAA;AAAA,QACA,OAAO,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA,CAAE,SAAS,CAAA,GAChC,CAAA,MAAA,EAAM,MAAA,CAAO,MAAA,CAAO,KAAK,KAAA,CAAM,MAAM,CAAA,CAAE,MAAM,CAAC,CAAA,IAAA,CAAA,GAC9C;AAAA;AAAA;AAAA,GACN,EAEJ,CAAA;AAEJ,CAAA;AASO,IAAM,iBAAA,GAAoB,CAC/B,KAAA,KACI,UAAA,qBAAeC,cAAA,CAAC,aAAA,EAAA,EAAe,GAAG,KAAA,EAAO,CAAA,GAAK","file":"index.cjs","sourcesContent":["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\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 like equality's dirtyCache: a\n// pathological unbounded key set resets the cache instead of growing it\n// forever (the reset only costs re-parsing, never correctness).\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) return cached;\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) parseCache.clear();\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): 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 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 type { z } from \"zod\";\nimport type { Form } from \"../core/createForm\";\nimport type { FieldPath } 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\nexport type FormstandDevtoolsProps<TSchema extends z.ZodType> = Readonly<{\n form: Form<TSchema>;\n position?: DevtoolsPosition;\n defaultOpen?: boolean;\n /** Shown on the toggle, for telling two mounted panels apart. */\n label?: string;\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 `typeof process` guard keeps it from throwing in runtimes\n// that define no process at all.\nconst isDevBuild = (): boolean =>\n typeof process === \"undefined\" ||\n process.env?.[\"NODE_ENV\"] !== \"production\";\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>(form: Form<TSchema>) =>\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>({\n form,\n position = \"bottom-right\",\n defaultOpen = false,\n label = \"formstand\",\n}: FormstandDevtoolsProps<TSchema>) => {\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>>);\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.\n */\nexport const FormstandDevtools = <TSchema extends z.ZodType>(\n props: FormstandDevtoolsProps<TSchema>,\n) => (isDevBuild() ? <DevtoolsPanel {...props} /> : null);\n"]}
@@ -0,0 +1,27 @@
1
+ import * as react from 'react';
2
+ import { z } from 'zod';
3
+ import { F as Form } from '../createForm-C9hZffCQ.cjs';
4
+ import 'zustand/vanilla';
5
+
6
+ type DevtoolsPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
7
+
8
+ type FormstandDevtoolsProps<TSchema extends z.ZodType> = Readonly<{
9
+ form: Form<TSchema>;
10
+ position?: DevtoolsPosition;
11
+ defaultOpen?: boolean;
12
+ /** Shown on the toggle, for telling two mounted panels apart. */
13
+ label?: string;
14
+ }>;
15
+ /**
16
+ * A form-aware debugging panel: every field's value, error, and flags, the
17
+ * two error channels shown separately, the live diff against initial values,
18
+ * and snapshot/restore time travel.
19
+ *
20
+ * Renders nothing in production builds.
21
+ */
22
+ declare const FormstandDevtools: <TSchema extends z.ZodType>(props: FormstandDevtoolsProps<TSchema>) => react.JSX.Element | null;
23
+
24
+ declare const leafPaths: (value: unknown, base?: string) => readonly string[];
25
+ declare const unmatchedErrorKeys: (errorKeys: readonly string[], leaves: readonly string[]) => readonly string[];
26
+
27
+ export { type DevtoolsPosition, FormstandDevtools, type FormstandDevtoolsProps, leafPaths, unmatchedErrorKeys };
@@ -0,0 +1,27 @@
1
+ import * as react from 'react';
2
+ import { z } from 'zod';
3
+ import { F as Form } from '../createForm-C9hZffCQ.js';
4
+ import 'zustand/vanilla';
5
+
6
+ type DevtoolsPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
7
+
8
+ type FormstandDevtoolsProps<TSchema extends z.ZodType> = Readonly<{
9
+ form: Form<TSchema>;
10
+ position?: DevtoolsPosition;
11
+ defaultOpen?: boolean;
12
+ /** Shown on the toggle, for telling two mounted panels apart. */
13
+ label?: string;
14
+ }>;
15
+ /**
16
+ * A form-aware debugging panel: every field's value, error, and flags, the
17
+ * two error channels shown separately, the live diff against initial values,
18
+ * and snapshot/restore time travel.
19
+ *
20
+ * Renders nothing in production builds.
21
+ */
22
+ declare const FormstandDevtools: <TSchema extends z.ZodType>(props: FormstandDevtoolsProps<TSchema>) => react.JSX.Element | null;
23
+
24
+ declare const leafPaths: (value: unknown, base?: string) => readonly string[];
25
+ declare const unmatchedErrorKeys: (errorKeys: readonly string[], leaves: readonly string[]) => readonly string[];
26
+
27
+ export { type DevtoolsPosition, FormstandDevtools, type FormstandDevtoolsProps, leafPaths, unmatchedErrorKeys };