@formkit/zod 1.7.0-d6a1f02 → 1.7.0-dev.4f55c07
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/CLAUDE.md +122 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.dev.mjs.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/CLAUDE.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# @formkit/zod
|
|
2
|
+
|
|
3
|
+
Zod schema validation plugin for FormKit forms. Bridges Zod's type-safe validation with FormKit's error display system.
|
|
4
|
+
|
|
5
|
+
## Architecture
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
src/
|
|
9
|
+
index.ts # Re-exports createZodPlugin
|
|
10
|
+
zod.ts # Plugin implementation (~215 lines)
|
|
11
|
+
__tests__/
|
|
12
|
+
zod.spec.ts # Vitest tests with Vue mounting
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Key Abstractions
|
|
16
|
+
|
|
17
|
+
### Public API
|
|
18
|
+
|
|
19
|
+
- **`createZodPlugin(zodSchema, submitCallback)`**: Factory function returning `[FormKitPlugin, submitHandler]` tuple
|
|
20
|
+
- `zodSchema`: Any Zod schema (`z.ZodTypeAny`)
|
|
21
|
+
- `submitCallback`: `(payload: z.infer<typeof zodSchema>, node: FormKitNode | undefined) => void | Promise<void>`
|
|
22
|
+
- Returns: Tuple of plugin and submit handler to use with `@submit`
|
|
23
|
+
|
|
24
|
+
### Node Extension
|
|
25
|
+
|
|
26
|
+
- **`node.setZodErrors(zodError)`**: Method added to form nodes via `node.extend()`. Hydrates FormKit errors from a `z.ZodError` object. Useful for server-side validation.
|
|
27
|
+
|
|
28
|
+
### Internal Functions
|
|
29
|
+
|
|
30
|
+
- `performZodValidation()`: Runs `safeParse` and maps errors to nodes
|
|
31
|
+
- `setFormValidations()`: Distributes errors to matching nodes or form-level
|
|
32
|
+
- `zodErrorToFormKitErrors()`: Converts `z.ZodError` to `[formErrors[], fieldErrors{}]`
|
|
33
|
+
- `createMessageName()`: Resolves display name from `validationLabel > label > name`
|
|
34
|
+
|
|
35
|
+
## How It Works
|
|
36
|
+
|
|
37
|
+
1. Plugin attaches to `type="form"` nodes only (returns `false` for non-forms)
|
|
38
|
+
2. Creates ledger counter `existingValidation` to track native FormKit validation
|
|
39
|
+
3. On `commit` event: Debounced validation (150ms) with 600ms max interval
|
|
40
|
+
4. On `message-added` with `submitted` state: Immediate validation
|
|
41
|
+
5. Errors set as blocking validation messages with key pattern `{path}:zod`
|
|
42
|
+
6. When native validation appears (`existingValidation` unsettles), zod errors clear for that field
|
|
43
|
+
|
|
44
|
+
## Integration Points
|
|
45
|
+
|
|
46
|
+
- **Depends on**: `@formkit/core` (FormKitNode, FormKitPlugin, createMessage)
|
|
47
|
+
- **Peer dependency**: `zod ^3.0.0`
|
|
48
|
+
- **Dev dependency**: `@formkit/vue` (testing only)
|
|
49
|
+
- **Depended on by**: None (leaf package)
|
|
50
|
+
- **Root CLAUDE.md section**: "Addons" category
|
|
51
|
+
|
|
52
|
+
## Usage Pattern
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { createZodPlugin } from '@formkit/zod'
|
|
56
|
+
import { z } from 'zod'
|
|
57
|
+
|
|
58
|
+
const schema = z.object({
|
|
59
|
+
email: z.string().email(),
|
|
60
|
+
name: z.string().min(3)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const [zodPlugin, submitHandler] = createZodPlugin(schema, async (data) => {
|
|
64
|
+
// data is typed as z.infer<typeof schema>
|
|
65
|
+
await api.submit(data)
|
|
66
|
+
})
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```vue
|
|
70
|
+
<FormKit type="form" :plugins="[zodPlugin]" @submit="submitHandler">
|
|
71
|
+
<FormKit name="email" />
|
|
72
|
+
<FormKit name="name" />
|
|
73
|
+
</FormKit>
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Modification Guide
|
|
77
|
+
|
|
78
|
+
### Adding Features
|
|
79
|
+
|
|
80
|
+
- All logic lives in `src/zod.ts`
|
|
81
|
+
- Follow existing pattern: functions inside `createZodPlugin` closure for access to `zodValidationSet` and `zodValidationListeners`
|
|
82
|
+
- New node methods: Add via `node.extend()` in the `created` event handler
|
|
83
|
+
- New TypeScript types: Extend `FormKitNodeExtensions` interface in `@formkit/core` module declaration
|
|
84
|
+
|
|
85
|
+
### Adding Tests
|
|
86
|
+
|
|
87
|
+
- Location: `__tests__/zod.spec.ts`
|
|
88
|
+
- Pattern: Mount Vue components with `@vue/test-utils`, trigger form submission, assert on DOM or spy calls
|
|
89
|
+
- Helper: `nextTick(timeout?)` for async settling
|
|
90
|
+
- Run: `pnpm test` from monorepo root
|
|
91
|
+
|
|
92
|
+
### Breaking Changes
|
|
93
|
+
|
|
94
|
+
- Changing `createZodPlugin` signature or return type
|
|
95
|
+
- Changing `setZodErrors` method signature
|
|
96
|
+
- Altering error message key format (`{path}:zod`)
|
|
97
|
+
- Modifying timing behavior (debounce/throttle values)
|
|
98
|
+
|
|
99
|
+
## Error Mapping Logic
|
|
100
|
+
|
|
101
|
+
1. Zod errors parsed via `zodError.issues`
|
|
102
|
+
2. Each issue's `path` joined with `.` (e.g., `personalInfo.firstName`)
|
|
103
|
+
3. `node.at(path)` locates target FormKit node
|
|
104
|
+
4. If node found: Error added to that node's store
|
|
105
|
+
5. If node not found: Error added to form-level errors (only on submit)
|
|
106
|
+
|
|
107
|
+
## Auto-Update Triggers
|
|
108
|
+
|
|
109
|
+
Update this CLAUDE.md when:
|
|
110
|
+
- New export added to `src/index.ts`
|
|
111
|
+
- New method added to `FormKitNodeExtensions`
|
|
112
|
+
- Validation timing logic changes
|
|
113
|
+
- Error mapping behavior changes
|
|
114
|
+
- Dependencies updated in `package.json`
|
|
115
|
+
|
|
116
|
+
## Deep Dive References
|
|
117
|
+
|
|
118
|
+
- Zod plugin implementation: `src/zod.ts`
|
|
119
|
+
- FormKit node API: `packages/core/src/node.ts`
|
|
120
|
+
- Ledger system: `packages/core/src/ledger.ts`
|
|
121
|
+
- Message creation: `packages/core/src/store.ts`
|
|
122
|
+
- Example usage: `examples/src/vue/examples/Zod.vue`
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AACA,SAAS,qBAAqB;AAY9B,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;AACpD,WAAO,KAAK,MAAM,gBAAgB,IAAI;AAAA,EACxC;AACA,SACE,KAAK,MAAM,mBACX,KAAK,MAAM,SACX,KAAK,MAAM,QACX,OAAO,KAAK,IAAI;AAEpB;AAYO,SAAS,gBACd,WACA,gBAIwE;AACxE,QAAM,mBAAmB,oBAAI,IAAiB;AAC9C,QAAM,yBAAyB,oBAAI,IAAyB;AAG5D,QAAM,YAAY,CAAC,SAAsB;AACvC,QAAI,KAAK,MAAM,SAAS;AAAQ,aAAO;AAEvC,SAAK,OAAO,MAAM,sBAAsB,CAAC,YAAY;AACnD,UAAI,QAAQ,SAAS,gBAAgB,QAAQ,SAAS,SAAS;AAC7D,eAAO,CAAC,QAAQ,IAAI,SAAS,MAAM;AAAA,MACrC;AACA,aAAO;AAAA,IACT,CAAC;AAED,SAAK,GAAG,WAAW,MAAM;AACvB,WAAK,OAAO,gBAAgB;AAAA,QAC1B,KAAK,CAACA,UAAS,OAAO,aAAyB;AAC7C,cAAI,CAAC;AAAU;AACf,gBAAMA,MAAK;AACX,gBAAM,CAAC,YAAY,WAAW,IAAI;AAAA,YAChC;AAAA,YACAA;AAAA,UACF;AACA,UAAAA,MAAK,UAAU,aAAa,UAAU;AAAA,QACxC;AAAA,QACA,KAAK;AAAA,MACP,CAAC;AAAA,IACH,CAAC;AAED,SAAK,GAAG,aAAa,MAAM;AACzB,uBAAiB,MAAM;AACvB,6BAAuB,MAAM;AAAA,IAC/B,CAAC;A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AAA,EACH;AAEA,WAAS,wBACP,UACA,MACoC;AACpC,UAAM,cAAsC,CAAC;AAC7C,UAAM,aAAuB,CAAC;AAC9B,aAAS,OAAO,QAAQ,CAAC,UAAU;AACjC,YAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAChC,YAAM,aAAa,KAAK,GAAG,IAAI;AAC/B,UAAI,YAAY;AACd,YAAI,CAAC,YAAY,IAAI,GAAG;AACtB,sBAAY,IAAI,IAAI,MAAM;AAAA,QAC5B;AAAA,MACF,OAAO;AACL,mBAAW,KAAK,GAAG,IAAI,KAAK,MAAM,OAAO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import type { FormKitNode, FormKitPlugin } from '@formkit/core'\nimport { createMessage } from '@formkit/core'\nimport type { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AAAA,SAAqC,qBAAqB;AAY1D,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;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AAW,KAAK,GAAG,IAAI,KAAK,MAAM,OAAO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import { FormKitNode, FormKitPlugin, createMessage } from '@formkit/core'\nimport { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
package/dist/index.dev.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AACA,SAAS,qBAAqB;AAY9B,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;AACpD,WAAO,KAAK,MAAM,gBAAgB,IAAI;AAAA,EACxC;AACA,SACE,KAAK,MAAM,mBACX,KAAK,MAAM,SACX,KAAK,MAAM,QACX,OAAO,KAAK,IAAI;AAEpB;AAYO,SAAS,gBACd,WACA,gBAIwE;AACxE,QAAM,mBAAmB,oBAAI,IAAiB;AAC9C,QAAM,yBAAyB,oBAAI,IAAyB;AAG5D,QAAM,YAAY,CAAC,SAAsB;AACvC,QAAI,KAAK,MAAM,SAAS;A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AA,cACV,MAAM;AAAA,cACN,KAAK,GAAG,IAAI;AAAA,cACZ,OAAO;AAAA,cACP,MAAM;AAAA,gBACJ,UAAU;AAAA,kBACR;AAAA,oBACE,MAAM;AAAA,oBACN,MAAM,kBAAkB,UAAU;AAAA,oBAClC,MAAM,CAAC,KAAK;AAAA,kBACd;AAAA,gBACF;AAAA,gBACA,YAAY;AAAA,cACd;AAAA,YACF,CAAC;AAAA,UACH;AACA,2BAAiB,IAAI,UAAU;AAAA,QACjC;AAAA,MACF;AAAA,IACF,CAAC;AAGD,QAAI,MAAM,SAAS,MAAM,WAAW;AAClC,WAAK,UAAU,CAAC,GAAG,UAAU;AAAA,IAC/B;AAEA,wBAAoB,QAAQ,CAACA,UAAS;AACpC,MAAAA,MAAK,MAAM,OAAO,GAAGA,MAAK,QAAQ,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC,MAAM;AAC1D,uBAAiB,OAAOA,KAAI;AAAA,IAC9B,CAAC;AAAA,EACH;AAEA,WAAS,wBACP,UACA,MACoC;AACpC,UAAM,cAAsC,CAAC;AAC7C,UAAM,aAAuB,CAAC;AAC9B,aAAS,OAAO,QAAQ,CAAC,UAAU;AACjC,YAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAChC,YAAM,aAAa,KAAK,GAAG,IAAI;AAC/B,UAAI,YAAY;AACd,YAAI,CAAC,YAAY,IAAI,GAAG;AACtB,sBAAY,IAAI,IAAI,MAAM;AAAA,QAC5B;AAAA,MACF,OAAO;AACL,mBAAW,KAAK,GAAG,IAAI,KAAK,MAAM,OAAO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import type { FormKitNode, FormKitPlugin } from '@formkit/core'\nimport { createMessage } from '@formkit/core'\nimport type { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AAAA,SAAqC,qBAAqB;AAY1D,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;AACpD,WAAO,KAAK,MAAM,gBAAgB,IAAI;AAAA,EACxC;AACA,SACE,KAAK,MAAM,mBACX,KAAK,MAAM,SACX,KAAK,MAAM,QACX,OAAO,KAAK,IAAI;AAEpB;AAYO,SAAS,gBACd,WACA,gBAIwE;AACxE,QAAM,mBAAmB,oBAAI,IAAiB;AAC9C,QAAM,yBAAyB,oBAAI,IAAyB;AAG5D,QAAM,YAAY,CAAC,SAAsB;AACvC,QAAI,KAAK,MAAM,SAAS;AAAQ,aAAO;AAEvC,SAAK,OAAO,MAAM,sBAAsB,CAAC,YAAY;AACnD,UAAI,QAAQ,SAAS,gBAAgB,QAAQ,SAAS,SAAS;AAC7D,eAAO,CAAC,QAAQ,IAAI,SAAS,MAAM;AAAA,MACrC;AACA,aAAO;AAAA,IACT,CAAC;AAED,SAAK,GAAG,WAAW,MAAM;AACvB,WAAK,OAAO,gBAAgB;AAAA,QAC1B,KAAK,CAACA,UAAS,OAAO,aAAyB;AAC7C,cAAI,CAAC;AAAU;AACf,gBAA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,CAAC;AAGD,QAAI,MAAM,SAAS,MAAM,WAAW;AAClC,WAAK,UAAU,CAAC,GAAG,UAAU;AAAA,IAC/B;AAEA,wBAAoB,QAAQ,CAACA,UAAS;AACpC,MAAAA,MAAK,MAAM,OAAO,GAAGA,MAAK,QAAQ,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC,MAAM;AAC1D,uBAAiB,OAAOA,KAAI;AAAA,IAC9B,CAAC;AAAA,EACH;AAEA,WAAS,wBACP,UACA,MACoC;AACpC,UAAM,cAAsC,CAAC;AAC7C,UAAM,aAAuB,CAAC;AAC9B,aAAS,OAAO,QAAQ,CAAC,UAAU;AACjC,YAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAChC,YAAM,aAAa,KAAK,GAAG,IAAI;AAC/B,UAAI,YAAY;AACd,YAAI,CAAC,YAAY,IAAI,GAAG;AACtB,sBAAY,IAAI,IAAI,MAAM;AAAA,QAC5B;AAAA,MACF,OAAO;AACL,mBAAW,KAAK,GAAG,IAAI,KAAK,MAAM,OAAO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import { FormKitNode, FormKitPlugin, createMessage } from '@formkit/core'\nimport { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AACA,SAAS,qBAAqB;AAY9B,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;AACpD,WAAO,KAAK,MAAM,gBAAgB,IAAI;AAAA,EACxC;AACA,SACE,KAAK,MAAM,mBACX,KAAK,MAAM,SACX,KAAK,MAAM,QACX,OAAO,KAAK,IAAI;AAEpB;AAYO,SAAS,gBACd,WACA,gBAIwE;AACxE,QAAM,mBAAmB,oBAAI,IAAiB;AAC9C,QAAM,yBAAyB,oBAAI,IAAyB;AAG5D,QAAM,YAAY,CAAC,SAAsB;AACvC,QAAI,KAAK,MAAM,SAAS;AAAQ,aAAO;AAEvC,SAAK,OAAO,MAAM,sBAAsB,CAAC,YAAY;AACnD,UAAI,QAAQ,SAAS,gBAAgB,QAAQ,SAAS,SAAS;AAC7D,eAAO,CAAC,QAAQ,IAAI,SAAS,MAAM;AAAA,MACrC;AACA,aAAO;AAAA,IACT,CAAC;AAED,SAAK,GAAG,WAAW,MAAM;AACvB,WAAK,OAAO,gBAAgB;AAAA,QAC1B,KAAK,CAACA,UAAS,OAAO,aAAyB;AAC7C,cAAI,CAAC;AAAU;AACf,gBAAMA,MAAK;AACX,gBAAM,CAAC,YAAY,WAAW,IAAI;AAAA,YAChC;AAAA,YACAA;AAAA,UACF;AACA,UAAAA,MAAK,UAAU,aAAa,UAAU;AAAA,QACxC;AAAA,QACA,KAAK;AAAA,MACP,CAAC;AAAA,IACH,CAAC;AAED,SAAK,GAAG,aAAa,MAAM;AACzB,uBAAiB,MAAM;AACvB,6BAAuB,MAAM;AAAA,IAC/B,CAAC;AAED,QAAI,eAAuD;AAC3D,QAAI,QAAQ,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;AACpC,UAAM,cAAsC,CAAC;AAC7C,UAAM,aAAuB,CAAC;AAC9B,aAAS,OAAO,QAAQ,CAAC,UAAU;AACjC,YAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAChC,YAAM,aAAa,KAAK,GAAG,IAAI;AAC/B,UAAI,YAAY;AACd,YAAI,CAAC,YAAY,IAAI,GAAG;AACtB,sBAAY,IAAI,IAAI,MAAM;AAAA,QAC5B;AAAA,MACF,OAAO;AACL,mBAAW,KAAK,GAAG,IAAI,KAAK,MAAM,OAAO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import type { FormKitNode, FormKitPlugin } from '@formkit/core'\nimport { createMessage } from '@formkit/core'\nimport type { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/zod.ts"],"names":["node"],"mappings":";AAAA,SAAqC,qBAAqB;AAY1D,SAAS,kBAAkB,MAA2B;AACpD,MAAI,OAAO,KAAK,MAAM,oBAAoB,YAAY;AACpD,WAAO,KAAK,MAAM,gBAAgB,IAAI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AO,EAAE;AAAA,MAC7C;AAAA,IACF,CAAC;AACD,WAAO,CAAC,YAAY,WAAW;AAAA,EACjC;AAEA,SAAO,CAAC,WAAW,aAAa;AAClC","sourcesContent":["import { FormKitNode, FormKitPlugin, createMessage } from '@formkit/core'\nimport { z } from 'zod'\n\n/**\n * Extend FormKitNode with setZodErrors.\n */\ndeclare module '@formkit/core' {\n interface FormKitNodeExtensions {\n setZodErrors(zodError: z.ZodError | undefined): FormKitNode\n }\n}\n\nfunction createMessageName(node: FormKitNode): string {\n if (typeof node.props.validationLabel === 'function') {\n return node.props.validationLabel(node)\n }\n return (\n node.props.validationLabel ||\n node.props.label ||\n node.props.name ||\n String(node.name)\n )\n}\n\n/**\n * Creates a new Zod schema plugin for form validation.\n *\n * @param zodSchema - A Zod schema to validate the form against.\n * @param submitCallback - A callback to run when the form is submitted and it passes validation.\n *\n * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.\n *\n * @public\n */\nexport function createZodPlugin<Z extends z.ZodTypeAny>(\n zodSchema: Z,\n submitCallback: (\n payload: z.infer<typeof zodSchema>,\n node: FormKitNode | undefined\n ) => void | Promise<void>\n): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void] {\n const zodValidationSet = new Set<FormKitNode>()\n const zodValidationListeners = new Map<FormKitNode, string>()\n // The Zod plugin — maps zod schema to validation rules on\n // matching FormKit nodes.\n const zodPlugin = (node: FormKitNode) => {\n if (node.props.type !== 'form') return false\n\n node.ledger.count('existingValidation', (message) => {\n if (message.type === 'validation' || message.type === 'error') {\n return !message.key.endsWith(':zod')\n }\n return false\n })\n\n node.on('created', () => {\n node.extend('setZodErrors', {\n get: (node) => async (zodError: z.ZodError) => {\n if (!zodError) return\n await node.settled\n const [formErrors, fieldErrors] = zodErrorToFormKitErrors(\n zodError,\n node\n )\n node.setErrors(fieldErrors, formErrors)\n },\n set: false,\n })\n })\n\n node.on('destroyed', () => {\n zodValidationSet.clear()\n zodValidationListeners.clear()\n })\n\n let commitTimout: ReturnType<typeof setTimeout> | number = 0\n let start = Date.now()\n node.on('commit', ({ payload }) => {\n clearTimeout(commitTimout)\n const now = Date.now()\n // perform at least every 600ms\n if (now - start > 600) {\n start = now\n performZodValidation(payload, node)\n }\n // also perform after 150ms of no commits\n commitTimout = setTimeout(() => {\n performZodValidation(payload, node)\n }, 150)\n })\n\n node.on('message-added', (message) => {\n if (\n message.payload.type === 'state' &&\n message.payload.key === 'submitted'\n ) {\n // perform validation on submit so that check\n // for form level errors can be done\n performZodValidation(node.value, node)\n }\n })\n\n return false\n }\n\n function performZodValidation(payload: any, node: FormKitNode) {\n const zodResults = zodSchema.safeParse(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n zodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n const receipt = zodValidationListeners.get(node)\n node.off(receipt as string)\n zodValidationListeners.delete(node)\n })\n zodValidationSet.clear()\n }\n }\n\n // The submit handler — validates the payload against the zod schema\n // and then passes the data to the user's submit callback.\n async function submitHandler(payload: any, node?: FormKitNode | undefined) {\n const zodResults = await zodSchema.safeParseAsync(payload)\n if (!zodResults.success) {\n setFormValidations(zodResults.error, node)\n } else {\n await submitCallback(zodResults.data, node)\n }\n }\n\n // Sets the form errors on the correct nodes.\n function setFormValidations(\n zodErrors: z.ZodError,\n node?: FormKitNode | undefined\n ) {\n if (!node) return\n const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node)\n const oldZodValidationSet = new Set(zodValidationSet)\n Object.entries(InputErrors).map((issue) => {\n const [path, message] = issue\n const targetNode = node.at(path)\n if (targetNode) {\n oldZodValidationSet.delete(targetNode)\n const existingValidationCount =\n targetNode.ledger.value('existingValidation')\n if (existingValidationCount === 0) {\n if (!targetNode.store[`${path}:zod`]) {\n const validationListener = targetNode.on(\n 'unsettled:existingValidation',\n () => {\n targetNode.store.remove(`${path}:zod`)\n zodValidationSet.delete(targetNode)\n }\n )\n zodValidationListeners.set(targetNode, validationListener)\n }\n\n targetNode.store.set(\n /* #__PURE__ */ createMessage({\n blocking: true,\n type: 'validation',\n key: `${path}:zod`,\n value: message,\n meta: {\n i18nArgs: [\n {\n node: targetNode,\n name: createMessageName(targetNode),\n args: [issue],\n },\n ],\n messageKey: 'zod',\n },\n })\n )\n zodValidationSet.add(targetNode)\n }\n }\n })\n\n // on submit, all remaining errors are global errors\n if (node?.context?.state.submitted) {\n node.setErrors([], formErrors)\n }\n\n oldZodValidationSet.forEach((node) => {\n node.store.remove(`${node.address.slice(1).join('.')}:zod`)\n zodValidationSet.delete(node)\n })\n }\n\n function zodErrorToFormKitErrors(\n zodError: z.ZodError,\n node: FormKitNode\n ): [string[], Record<string, string>] {\n const fieldErrors: Record<string, string> = {}\n const formErrors: string[] = []\n zodError.issues.forEach((error) => {\n const path = error.path.join('.')\n const targetNode = node.at(path)\n if (targetNode) {\n if (!fieldErrors[path]) {\n fieldErrors[path] = error.message\n }\n } else {\n formErrors.push(`${path}: ${error.message}`)\n }\n })\n return [formErrors, fieldErrors]\n }\n\n return [zodPlugin, submitHandler]\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@formkit/zod",
|
|
3
|
-
"version": "1.7.0-
|
|
3
|
+
"version": "1.7.0-dev.4f55c07",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Zod validation for FormKit.",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"repository": {
|
|
29
29
|
"type": "git",
|
|
30
|
-
"url": "https://github.com/formkit/
|
|
30
|
+
"url": "https://github.com/formkit/formkit.git",
|
|
31
31
|
"directory": "packages/zod"
|
|
32
32
|
},
|
|
33
33
|
"contributors": [
|
|
@@ -35,16 +35,16 @@
|
|
|
35
35
|
"Justin Schroeder <justin@formkit.com>"
|
|
36
36
|
],
|
|
37
37
|
"license": "MIT",
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "jest"
|
|
40
|
+
},
|
|
38
41
|
"dependencies": {
|
|
39
|
-
"@formkit/core": "1.7.0-
|
|
42
|
+
"@formkit/core": "1.7.0-dev.4f55c07"
|
|
40
43
|
},
|
|
41
44
|
"devDependencies": {
|
|
42
|
-
"@formkit/vue": "
|
|
45
|
+
"@formkit/vue": "workspace:^"
|
|
43
46
|
},
|
|
44
47
|
"peerDependencies": {
|
|
45
48
|
"zod": "^3.0.0"
|
|
46
|
-
},
|
|
47
|
-
"scripts": {
|
|
48
|
-
"test": "jest"
|
|
49
49
|
}
|
|
50
50
|
}
|