@formkit/zod 0.17.0-3cd8a0a

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present FormKit, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ <p align="center"><a href="https://www.formkit.com" target="_blank" rel="noopener noreferrer"><img width="200" src="https://cdn.formk.it/brand-assets/formkit-logo.png" alt="FormKit Logo"></a></p>
2
+
3
+ # @formkit/zod
4
+
5
+ The official FormKit Zod plugin. Read the [documentation](https://www.formkit.com/essentials/zod) for usage instructions.
package/dist/index.cjs ADDED
@@ -0,0 +1,187 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var core = require('@formkit/core');
6
+
7
+ function createMessageName(node) {
8
+ if (typeof node.props.validationLabel === 'function') {
9
+ return node.props.validationLabel(node);
10
+ }
11
+ return (node.props.validationLabel ||
12
+ node.props.label ||
13
+ node.props.name ||
14
+ String(node.name));
15
+ }
16
+ /**
17
+ * Creates a new Zod schema plugin for form validation.
18
+ *
19
+ * @param zodSchema - A Zod schema to validate the form against.
20
+ * @param submitCallback - A callback to run when the form is submitted and it passes validation.
21
+ *
22
+ * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.
23
+ *
24
+ * @public
25
+ */
26
+ function createZodPlugin(zodSchema, submitCallback) {
27
+ const zodValidationSet = new Set();
28
+ const zodValidationListeners = new Map();
29
+ // The Zod plugin — maps zod schema to validation rules on
30
+ // matching FormKit nodes.
31
+ const zodPlugin = (node) => {
32
+ if (node.props.type !== 'form')
33
+ return false;
34
+ node.ledger.count('existingValidation', (message) => {
35
+ if (message.type === 'validation' || message.type === 'error') {
36
+ return !message.key.endsWith(':zod');
37
+ }
38
+ return false;
39
+ });
40
+ node.on('created', () => {
41
+ node.extend('setZodErrors', {
42
+ get: (node) => async (zodError) => {
43
+ if (!zodError)
44
+ return;
45
+ await node.settled;
46
+ const [formErrors, fieldErrors] = zodErrorToFormKitErrors(zodError, node);
47
+ node.setErrors(fieldErrors, formErrors);
48
+ },
49
+ set: false,
50
+ });
51
+ });
52
+ node.on('destroyed', () => {
53
+ zodValidationSet.clear();
54
+ zodValidationListeners.clear();
55
+ });
56
+ let commitTimout = 0;
57
+ let start = Date.now();
58
+ node.on('commit', ({ payload }) => {
59
+ clearTimeout(commitTimout);
60
+ const now = Date.now();
61
+ // perform at least every 600ms
62
+ if (now - start > 600) {
63
+ start = now;
64
+ performZodValidation(payload, node);
65
+ }
66
+ // also perform after 150ms of no commits
67
+ commitTimout = setTimeout(() => {
68
+ performZodValidation(payload, node);
69
+ }, 150);
70
+ });
71
+ node.on('message-added', (message) => {
72
+ if (message.payload.type === 'state' &&
73
+ message.payload.key === 'submitted') {
74
+ // perform validation on submit so that check
75
+ // for form level errors can be done
76
+ performZodValidation(node.value, node);
77
+ }
78
+ });
79
+ return false;
80
+ };
81
+ function performZodValidation(payload, node) {
82
+ // block submission while validation is running
83
+ node.store.set(core.createMessage({
84
+ type: 'state',
85
+ blocking: true,
86
+ visible: false,
87
+ value: true,
88
+ key: 'validating:zod',
89
+ }));
90
+ const zodResults = zodSchema.safeParse(payload);
91
+ if (!zodResults.success) {
92
+ setFormValidations(zodResults.error, node);
93
+ }
94
+ else {
95
+ zodValidationSet.forEach((node) => {
96
+ node.store.remove(`${node.address.slice(1).join('.')}:zod`);
97
+ const receipt = zodValidationListeners.get(node);
98
+ node.off(receipt);
99
+ zodValidationListeners.delete(node);
100
+ });
101
+ zodValidationSet.clear();
102
+ }
103
+ // unblock submission
104
+ node.store.remove('validating:zod');
105
+ }
106
+ // The submit handler — validates the payload against the zod schema
107
+ // and then passes the data to the user's submit callback.
108
+ async function submitHandler(payload, node) {
109
+ const zodResults = await zodSchema.safeParseAsync(payload);
110
+ if (!zodResults.success) {
111
+ setFormValidations(zodResults.error, node);
112
+ }
113
+ else {
114
+ await submitCallback(payload, node);
115
+ }
116
+ }
117
+ // Sets the form errors on the correct nodes.
118
+ function setFormValidations(zodErrors, node) {
119
+ var _a;
120
+ if (!node)
121
+ return;
122
+ const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node);
123
+ const oldZodValidationSet = new Set(zodValidationSet);
124
+ Object.entries(InputErrors).map((issue) => {
125
+ const [path, message] = issue;
126
+ const targetNode = node.at(path);
127
+ if (targetNode) {
128
+ oldZodValidationSet.delete(targetNode);
129
+ const existingValidationCount = targetNode.ledger.value('existingValidation');
130
+ if (existingValidationCount === 0) {
131
+ if (!targetNode.store[`${path}:zod`]) {
132
+ const validationListener = targetNode.on('unsettled:existingValidation', () => {
133
+ targetNode.store.remove(`${path}:zod`);
134
+ zodValidationSet.delete(targetNode);
135
+ });
136
+ zodValidationListeners.set(targetNode, validationListener);
137
+ }
138
+ targetNode.store.set(core.createMessage({
139
+ blocking: true,
140
+ type: 'validation',
141
+ key: `${path}:zod`,
142
+ value: message,
143
+ meta: {
144
+ i18nArgs: [
145
+ {
146
+ node: targetNode,
147
+ name: createMessageName(targetNode),
148
+ args: [issue],
149
+ },
150
+ ],
151
+ messageKey: 'zod',
152
+ },
153
+ }));
154
+ zodValidationSet.add(targetNode);
155
+ }
156
+ }
157
+ });
158
+ // on submit, all remaining errors are global errors
159
+ if ((_a = node === null || node === void 0 ? void 0 : node.context) === null || _a === void 0 ? void 0 : _a.state.submitted) {
160
+ node.setErrors([], formErrors);
161
+ }
162
+ oldZodValidationSet.forEach((node) => {
163
+ node.store.remove(`${node.address.slice(1).join('.')}:zod`);
164
+ zodValidationSet.delete(node);
165
+ });
166
+ }
167
+ function zodErrorToFormKitErrors(zodError, node) {
168
+ const fieldErrors = {};
169
+ const formErrors = [];
170
+ zodError.errors.forEach((error) => {
171
+ const path = error.path.join('.');
172
+ const targetNode = node.at(path);
173
+ if (targetNode) {
174
+ if (!fieldErrors[path]) {
175
+ fieldErrors[path] = error.message;
176
+ }
177
+ }
178
+ else {
179
+ formErrors.push(`${path}: ${error.message}`);
180
+ }
181
+ });
182
+ return [formErrors, fieldErrors];
183
+ }
184
+ return [zodPlugin, submitHandler];
185
+ }
186
+
187
+ exports.createZodPlugin = createZodPlugin;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The first-party zod package/plugin for FormKit. Read the
3
+ * {@link https://formkit.com/essentials/zod |
4
+ * documentation} for usage instructions.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+
9
+ import { FormKitNode } from '@formkit/core';
10
+ import { FormKitPlugin } from '@formkit/core';
11
+ import { z } from 'zod';
12
+
13
+ /**
14
+ * Creates a new Zod schema plugin for form validation.
15
+ *
16
+ * @param zodSchema - A Zod schema to validate the form against.
17
+ * @param submitCallback - A callback to run when the form is submitted and it passes validation.
18
+ *
19
+ * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.
20
+ *
21
+ * @public
22
+ */
23
+ export declare function createZodPlugin<Z extends z.ZodTypeAny>(zodSchema: Z, submitCallback: (payload: z.infer<typeof zodSchema>, node: FormKitNode | undefined) => void | Promise<void>): [FormKitPlugin, (payload: any, node: FormKitNode | undefined) => void];
24
+
25
+
26
+ /**
27
+ * Extend FormKitNode with setZodErrors.
28
+ */
29
+ declare module '@formkit/core' {
30
+ interface FormKitNodeExtensions {
31
+ setZodErrors(zodError: z.ZodError | undefined): FormKitNode
32
+ }
33
+ }
34
+
package/dist/index.mjs ADDED
@@ -0,0 +1,183 @@
1
+ import { createMessage } from '@formkit/core';
2
+
3
+ function createMessageName(node) {
4
+ if (typeof node.props.validationLabel === 'function') {
5
+ return node.props.validationLabel(node);
6
+ }
7
+ return (node.props.validationLabel ||
8
+ node.props.label ||
9
+ node.props.name ||
10
+ String(node.name));
11
+ }
12
+ /**
13
+ * Creates a new Zod schema plugin for form validation.
14
+ *
15
+ * @param zodSchema - A Zod schema to validate the form against.
16
+ * @param submitCallback - A callback to run when the form is submitted and it passes validation.
17
+ *
18
+ * @returns A tuple of a {@link @formkit/core#FormKitPlugin | FormKitPlugin} and a submit handler.
19
+ *
20
+ * @public
21
+ */
22
+ function createZodPlugin(zodSchema, submitCallback) {
23
+ const zodValidationSet = new Set();
24
+ const zodValidationListeners = new Map();
25
+ // The Zod plugin — maps zod schema to validation rules on
26
+ // matching FormKit nodes.
27
+ const zodPlugin = (node) => {
28
+ if (node.props.type !== 'form')
29
+ return false;
30
+ node.ledger.count('existingValidation', (message) => {
31
+ if (message.type === 'validation' || message.type === 'error') {
32
+ return !message.key.endsWith(':zod');
33
+ }
34
+ return false;
35
+ });
36
+ node.on('created', () => {
37
+ node.extend('setZodErrors', {
38
+ get: (node) => async (zodError) => {
39
+ if (!zodError)
40
+ return;
41
+ await node.settled;
42
+ const [formErrors, fieldErrors] = zodErrorToFormKitErrors(zodError, node);
43
+ node.setErrors(fieldErrors, formErrors);
44
+ },
45
+ set: false,
46
+ });
47
+ });
48
+ node.on('destroyed', () => {
49
+ zodValidationSet.clear();
50
+ zodValidationListeners.clear();
51
+ });
52
+ let commitTimout = 0;
53
+ let start = Date.now();
54
+ node.on('commit', ({ payload }) => {
55
+ clearTimeout(commitTimout);
56
+ const now = Date.now();
57
+ // perform at least every 600ms
58
+ if (now - start > 600) {
59
+ start = now;
60
+ performZodValidation(payload, node);
61
+ }
62
+ // also perform after 150ms of no commits
63
+ commitTimout = setTimeout(() => {
64
+ performZodValidation(payload, node);
65
+ }, 150);
66
+ });
67
+ node.on('message-added', (message) => {
68
+ if (message.payload.type === 'state' &&
69
+ message.payload.key === 'submitted') {
70
+ // perform validation on submit so that check
71
+ // for form level errors can be done
72
+ performZodValidation(node.value, node);
73
+ }
74
+ });
75
+ return false;
76
+ };
77
+ function performZodValidation(payload, node) {
78
+ // block submission while validation is running
79
+ node.store.set(createMessage({
80
+ type: 'state',
81
+ blocking: true,
82
+ visible: false,
83
+ value: true,
84
+ key: 'validating:zod',
85
+ }));
86
+ const zodResults = zodSchema.safeParse(payload);
87
+ if (!zodResults.success) {
88
+ setFormValidations(zodResults.error, node);
89
+ }
90
+ else {
91
+ zodValidationSet.forEach((node) => {
92
+ node.store.remove(`${node.address.slice(1).join('.')}:zod`);
93
+ const receipt = zodValidationListeners.get(node);
94
+ node.off(receipt);
95
+ zodValidationListeners.delete(node);
96
+ });
97
+ zodValidationSet.clear();
98
+ }
99
+ // unblock submission
100
+ node.store.remove('validating:zod');
101
+ }
102
+ // The submit handler — validates the payload against the zod schema
103
+ // and then passes the data to the user's submit callback.
104
+ async function submitHandler(payload, node) {
105
+ const zodResults = await zodSchema.safeParseAsync(payload);
106
+ if (!zodResults.success) {
107
+ setFormValidations(zodResults.error, node);
108
+ }
109
+ else {
110
+ await submitCallback(payload, node);
111
+ }
112
+ }
113
+ // Sets the form errors on the correct nodes.
114
+ function setFormValidations(zodErrors, node) {
115
+ var _a;
116
+ if (!node)
117
+ return;
118
+ const [formErrors, InputErrors] = zodErrorToFormKitErrors(zodErrors, node);
119
+ const oldZodValidationSet = new Set(zodValidationSet);
120
+ Object.entries(InputErrors).map((issue) => {
121
+ const [path, message] = issue;
122
+ const targetNode = node.at(path);
123
+ if (targetNode) {
124
+ oldZodValidationSet.delete(targetNode);
125
+ const existingValidationCount = targetNode.ledger.value('existingValidation');
126
+ if (existingValidationCount === 0) {
127
+ if (!targetNode.store[`${path}:zod`]) {
128
+ const validationListener = targetNode.on('unsettled:existingValidation', () => {
129
+ targetNode.store.remove(`${path}:zod`);
130
+ zodValidationSet.delete(targetNode);
131
+ });
132
+ zodValidationListeners.set(targetNode, validationListener);
133
+ }
134
+ targetNode.store.set(createMessage({
135
+ blocking: true,
136
+ type: 'validation',
137
+ key: `${path}:zod`,
138
+ value: message,
139
+ meta: {
140
+ i18nArgs: [
141
+ {
142
+ node: targetNode,
143
+ name: createMessageName(targetNode),
144
+ args: [issue],
145
+ },
146
+ ],
147
+ messageKey: 'zod',
148
+ },
149
+ }));
150
+ zodValidationSet.add(targetNode);
151
+ }
152
+ }
153
+ });
154
+ // on submit, all remaining errors are global errors
155
+ if ((_a = node === null || node === void 0 ? void 0 : node.context) === null || _a === void 0 ? void 0 : _a.state.submitted) {
156
+ node.setErrors([], formErrors);
157
+ }
158
+ oldZodValidationSet.forEach((node) => {
159
+ node.store.remove(`${node.address.slice(1).join('.')}:zod`);
160
+ zodValidationSet.delete(node);
161
+ });
162
+ }
163
+ function zodErrorToFormKitErrors(zodError, node) {
164
+ const fieldErrors = {};
165
+ const formErrors = [];
166
+ zodError.errors.forEach((error) => {
167
+ const path = error.path.join('.');
168
+ const targetNode = node.at(path);
169
+ if (targetNode) {
170
+ if (!fieldErrors[path]) {
171
+ fieldErrors[path] = error.message;
172
+ }
173
+ }
174
+ else {
175
+ formErrors.push(`${path}: ${error.message}`);
176
+ }
177
+ });
178
+ return [formErrors, fieldErrors];
179
+ }
180
+ return [zodPlugin, submitHandler];
181
+ }
182
+
183
+ export { createZodPlugin };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@formkit/zod",
3
+ "version": "0.17.0-3cd8a0a",
4
+ "type": "module",
5
+ "description": "Zod validation for FormKit.",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ "./package.json": "./package.json",
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "keywords": [
18
+ "zod",
19
+ "forms",
20
+ "inputs",
21
+ "validation"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/formkit/zod.git",
26
+ "directory": "packages/zod"
27
+ },
28
+ "contributors": [
29
+ "Andrew Boyd <andrew@formkit.com>",
30
+ "Justin Schroeder <justin@formkit.com>"
31
+ ],
32
+ "license": "MIT",
33
+ "scripts": {
34
+ "test": "jest"
35
+ },
36
+ "dependencies": {
37
+ "@formkit/core": "0.17.0-3cd8a0a"
38
+ },
39
+ "devDependencies": {},
40
+ "peerDependencies": {
41
+ "zod": "^3.0.0"
42
+ }
43
+ }