@form-instant/react-resolver-zod 0.0.0-alpha
Sign up to get free protection for your applications and to get access to all the features.
- package/LICENSE +21 -0
- package/README.md +160 -0
- package/dist/context.d.ts +2 -0
- package/dist/element.d.ts +4 -0
- package/dist/funcs/default-values.d.ts +4 -0
- package/dist/funcs/field-config.d.ts +5 -0
- package/dist/funcs/field-type-inference.d.ts +3 -0
- package/dist/funcs/schema-parser.d.ts +2 -0
- package/dist/funcs/types.d.ts +19 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +8 -0
- package/dist/provider.d.ts +4 -0
- package/dist/react-resolver-zod.cjs.development.js +194 -0
- package/dist/react-resolver-zod.cjs.development.js.map +1 -0
- package/dist/react-resolver-zod.cjs.production.min.js +2 -0
- package/dist/react-resolver-zod.cjs.production.min.js.map +1 -0
- package/dist/react-resolver-zod.esm.js +192 -0
- package/dist/react-resolver-zod.esm.js.map +1 -0
- package/dist/type.d.ts +2 -0
- package/dist/useSchema.d.ts +3 -0
- package/package.json +79 -0
- package/src/context.tsx +4 -0
- package/src/element.tsx +30 -0
- package/src/funcs/default-values.ts +30 -0
- package/src/funcs/field-config.ts +38 -0
- package/src/funcs/field-type-inference.ts +25 -0
- package/src/funcs/schema-parser.ts +71 -0
- package/src/funcs/types.ts +32 -0
- package/src/global.d.ts +13 -0
- package/src/index.ts +18 -0
- package/src/provider.tsx +7 -0
- package/src/type.ts +6 -0
- package/src/useSchema.tsx +15 -0
package/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2024 leomerida15
|
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,160 @@
|
|
1
|
+
# DTS React User Guide
|
2
|
+
|
3
|
+
Congrats! You just saved yourself hours of work by bootstrapping this project with DTS. Let’s get you oriented with what’s here and how to use it.
|
4
|
+
|
5
|
+
> This DTS setup is meant for developing React component libraries (not apps!) that can be published to NPM. If you’re looking to build a React-based app, you should use `create-react-app`, `razzle`, `nextjs`, `gatsby`, or `react-static`.
|
6
|
+
|
7
|
+
> If you’re new to TypeScript and React, checkout [this handy cheatsheet](https://github.com/sw-yx/react-typescript-cheatsheet/)
|
8
|
+
|
9
|
+
## Commands
|
10
|
+
|
11
|
+
DTS scaffolds your new library inside `/src`, and also sets up a [Vite-based](https://vitejs.dev) playground for it inside `/example`.
|
12
|
+
|
13
|
+
The recommended workflow is to run DTS in one terminal:
|
14
|
+
|
15
|
+
```bash
|
16
|
+
npm start # or yarn start
|
17
|
+
```
|
18
|
+
|
19
|
+
This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`.
|
20
|
+
|
21
|
+
Then run the example inside another:
|
22
|
+
|
23
|
+
```bash
|
24
|
+
cd example
|
25
|
+
npm i # or yarn to install dependencies
|
26
|
+
npm start # or yarn start
|
27
|
+
```
|
28
|
+
|
29
|
+
The default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure DTS is running in watch mode like we recommend above.
|
30
|
+
|
31
|
+
To do a one-off build, use `npm run build` or `yarn build`.
|
32
|
+
|
33
|
+
To run tests, use `npm test` or `yarn test`.
|
34
|
+
|
35
|
+
## Configuration
|
36
|
+
|
37
|
+
Code quality is set up for you with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields in `package.json` accordingly.
|
38
|
+
|
39
|
+
### Jest
|
40
|
+
|
41
|
+
Jest tests are set up to run with `npm test` or `yarn test`.
|
42
|
+
|
43
|
+
### Bundle analysis
|
44
|
+
|
45
|
+
Calculates the real cost of your library using [size-limit](https://github.com/ai/size-limit) with `npm run size` and visulize it with `npm run analyze`.
|
46
|
+
|
47
|
+
#### Setup Files
|
48
|
+
|
49
|
+
This is the folder structure we set up for you:
|
50
|
+
|
51
|
+
```txt
|
52
|
+
/example
|
53
|
+
index.html
|
54
|
+
index.tsx # test your component here in a demo app
|
55
|
+
package.json
|
56
|
+
tsconfig.json
|
57
|
+
/src
|
58
|
+
index.tsx # EDIT THIS
|
59
|
+
/test
|
60
|
+
index.test.tsx # EDIT THIS
|
61
|
+
.gitignore
|
62
|
+
package.json
|
63
|
+
README.md # EDIT THIS
|
64
|
+
tsconfig.json
|
65
|
+
```
|
66
|
+
|
67
|
+
#### React Testing Library
|
68
|
+
|
69
|
+
We do not set up `react-testing-library` for you yet, we welcome contributions and documentation on this.
|
70
|
+
|
71
|
+
### Rollup
|
72
|
+
|
73
|
+
DTS uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details.
|
74
|
+
|
75
|
+
### TypeScript
|
76
|
+
|
77
|
+
`tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your needs.
|
78
|
+
|
79
|
+
## Continuous Integration
|
80
|
+
|
81
|
+
### GitHub Actions
|
82
|
+
|
83
|
+
Two actions are added by default:
|
84
|
+
|
85
|
+
- `main` which installs deps w/ cache, lints, tests, and builds on all pushes against a Node and OS matrix
|
86
|
+
- `size` which comments cost comparison of your library on every pull request using [`size-limit`](https://github.com/ai/size-limit)
|
87
|
+
|
88
|
+
## Optimizations
|
89
|
+
|
90
|
+
Please see the main `dts` [optimizations docs](https://github.com/weiran-zsd/dts-cli#optimizations). In particular, know that you can take advantage of development-only optimizations:
|
91
|
+
|
92
|
+
```js
|
93
|
+
// ./types/index.d.ts
|
94
|
+
declare var __DEV__: boolean;
|
95
|
+
|
96
|
+
// inside your code...
|
97
|
+
if (__DEV__) {
|
98
|
+
console.log('foo');
|
99
|
+
}
|
100
|
+
```
|
101
|
+
|
102
|
+
You can also choose to install and use [invariant](https://github.com/weiran-zsd/dts-cli#invariant) and [warning](https://github.com/weiran-zsd/dts-cli#warning) functions.
|
103
|
+
|
104
|
+
## Module Formats
|
105
|
+
|
106
|
+
CJS, ESModules, and UMD module formats are supported.
|
107
|
+
|
108
|
+
The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found.
|
109
|
+
|
110
|
+
## Deploying the Example Playground
|
111
|
+
|
112
|
+
The Playground is just a simple [Vite](https://vitejs.dev) app, you can deploy it anywhere you would normally deploy that. Here are some guidelines for **manually** deploying with the Netlify CLI (`npm i -g netlify-cli`):
|
113
|
+
|
114
|
+
```bash
|
115
|
+
cd example # if not already in the example folder
|
116
|
+
npm run build # builds to dist
|
117
|
+
netlify deploy # deploy the dist folder
|
118
|
+
```
|
119
|
+
|
120
|
+
Alternatively, if you already have a git repo connected, you can set up continuous deployment with Netlify:
|
121
|
+
|
122
|
+
```bash
|
123
|
+
netlify init
|
124
|
+
# build command: yarn build && cd example && yarn && yarn build
|
125
|
+
# directory to deploy: example/dist
|
126
|
+
# pick yes for netlify.toml
|
127
|
+
```
|
128
|
+
|
129
|
+
## Named Exports
|
130
|
+
|
131
|
+
Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library.
|
132
|
+
|
133
|
+
## Including Styles
|
134
|
+
|
135
|
+
There are many ways to ship styles, including with CSS-in-JS. DTS has no opinion on this, configure how you like.
|
136
|
+
|
137
|
+
For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so that it can be imported separately by your users and run through their bundler's loader.
|
138
|
+
|
139
|
+
## Publishing to NPM
|
140
|
+
|
141
|
+
We recommend using [np](https://github.com/sindresorhus/np).
|
142
|
+
|
143
|
+
## Usage with Lerna
|
144
|
+
|
145
|
+
When creating a new package with DTS within a project set up with Lerna, you might encounter a `Cannot resolve dependency` error when trying to run the `example` project. To fix that you will need to make changes to the `package.json` file _inside the `example` directory_.
|
146
|
+
|
147
|
+
The problem is that due to the nature of how dependencies are installed in Lerna projects, the aliases in the example project's `package.json` might not point to the right place, as those dependencies might have been installed in the root of your Lerna project.
|
148
|
+
|
149
|
+
Change the `alias` to point to where those packages are actually installed. This depends on the directory structure of your Lerna project, so the actual path might be different from the diff below.
|
150
|
+
|
151
|
+
```diff
|
152
|
+
"alias": {
|
153
|
+
- "react": "../node_modules/react",
|
154
|
+
- "react-dom": "../node_modules/react-dom"
|
155
|
+
+ "react": "../../../node_modules/react",
|
156
|
+
+ "react-dom": "../../../node_modules/react-dom"
|
157
|
+
},
|
158
|
+
```
|
159
|
+
|
160
|
+
An alternative to fixing this problem would be to remove aliases altogether and define the dependencies referenced as aliases as dev dependencies instead. [However, that might cause other problems.](https://github.com/formium/tsdx/issues/64)
|
@@ -0,0 +1,5 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
import { FieldConfig, SuperRefineFunction } from "./types";
|
3
|
+
export declare const FIELD_CONFIG_SYMBOL: unique symbol;
|
4
|
+
export declare function fieldConfig<AdditionalRenderable = null, FieldTypes = string>(config: FieldConfig<AdditionalRenderable, FieldTypes>): SuperRefineFunction;
|
5
|
+
export declare function getFieldConfigInZodStack(schema: z.ZodTypeAny): FieldConfig;
|
@@ -0,0 +1,19 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
export type ZodObjectOrWrapped = z.ZodObject<any, any> | z.ZodEffects<z.ZodObject<any, any>>;
|
3
|
+
export interface ParsedField<AdditionalRenderable, FieldTypes = string> {
|
4
|
+
key: string;
|
5
|
+
type: string;
|
6
|
+
required: boolean;
|
7
|
+
default?: any;
|
8
|
+
fieldConfig?: FieldConfig<AdditionalRenderable, FieldTypes>;
|
9
|
+
options?: [string, string][];
|
10
|
+
schema?: ParsedField<AdditionalRenderable, FieldTypes>[];
|
11
|
+
}
|
12
|
+
export interface ParsedSchema<AdditionalRenderable = null, FieldTypes = string> {
|
13
|
+
fields: Record<string, ParsedField<AdditionalRenderable, FieldTypes>>;
|
14
|
+
}
|
15
|
+
export type SuperRefineFunction = () => unknown;
|
16
|
+
export type Renderable<AdditionalRenderable = null> = string | number | boolean | null | undefined | AdditionalRenderable;
|
17
|
+
export type FieldConfig<AdditionalRenderable = {}, FieldTypes = string> = {
|
18
|
+
fieldType?: FieldTypes;
|
19
|
+
} & AdditionalRenderable;
|
package/dist/index.d.ts
ADDED
@@ -0,0 +1,11 @@
|
|
1
|
+
export * from './type';
|
2
|
+
import { FieldConfig } from './funcs/types';
|
3
|
+
export declare const ZodSchemaResolver: <AdditionalRenderable = null, FieldTypes = string>() => {
|
4
|
+
useSchema: () => import("zod").ZodObject<never, never> | import("zod").ZodEffects<never, never>;
|
5
|
+
useFields: <S extends Record<string, any>>(key: keyof S) => import("./funcs/types").ParsedField<null, string>;
|
6
|
+
fieldConfig: (config: FieldConfig<AdditionalRenderable, FieldTypes>) => import("./funcs/types").SuperRefineFunction;
|
7
|
+
FormInstantProvider: FCC<{
|
8
|
+
schema: import("./type").zodResolverProps;
|
9
|
+
}>;
|
10
|
+
FormInstantElement: <S extends Record<string, any>>({ name, }: import("./element").ElementProps<S>) => import("react/jsx-runtime").JSX.Element;
|
11
|
+
};
|
package/dist/index.js
ADDED
@@ -0,0 +1,194 @@
|
|
1
|
+
'use strict';
|
2
|
+
|
3
|
+
var jsxRuntime = require('react/jsx-runtime');
|
4
|
+
var react = require('react');
|
5
|
+
var reactInputMapping = require('@form-instant/react-input-mapping');
|
6
|
+
var useContextSelector = require('use-context-selector');
|
7
|
+
var zod = require('zod');
|
8
|
+
|
9
|
+
function _extends() {
|
10
|
+
return _extends = Object.assign ? Object.assign.bind() : function (n) {
|
11
|
+
for (var e = 1; e < arguments.length; e++) {
|
12
|
+
var t = arguments[e];
|
13
|
+
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
|
14
|
+
}
|
15
|
+
return n;
|
16
|
+
}, _extends.apply(null, arguments);
|
17
|
+
}
|
18
|
+
function _objectWithoutPropertiesLoose(r, e) {
|
19
|
+
if (null == r) return {};
|
20
|
+
var t = {};
|
21
|
+
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
|
22
|
+
if (e.includes(n)) continue;
|
23
|
+
t[n] = r[n];
|
24
|
+
}
|
25
|
+
return t;
|
26
|
+
}
|
27
|
+
|
28
|
+
var ZodResolverContext = /*#__PURE__*/useContextSelector.createContext({});
|
29
|
+
|
30
|
+
function getDefaultValueInZodStack(schema) {
|
31
|
+
if (schema instanceof zod.z.ZodDefault) {
|
32
|
+
return schema._def.defaultValue();
|
33
|
+
}
|
34
|
+
if (schema instanceof zod.z.ZodEffects) {
|
35
|
+
return getDefaultValueInZodStack(schema.innerType());
|
36
|
+
}
|
37
|
+
return undefined;
|
38
|
+
}
|
39
|
+
|
40
|
+
var FIELD_CONFIG_SYMBOL = /*#__PURE__*/Symbol("GetFieldConfig");
|
41
|
+
function fieldConfig(config) {
|
42
|
+
var refinementFunction = function refinementFunction() {
|
43
|
+
// Do nothing.
|
44
|
+
};
|
45
|
+
// @ts-expect-error This is a symbol and not a real value.
|
46
|
+
refinementFunction[FIELD_CONFIG_SYMBOL] = config;
|
47
|
+
return refinementFunction;
|
48
|
+
}
|
49
|
+
function getFieldConfigInZodStack(schema) {
|
50
|
+
var typedSchema = schema;
|
51
|
+
if (typedSchema._def.typeName === "ZodEffects") {
|
52
|
+
var effect = typedSchema._def.effect;
|
53
|
+
var refinementFunction = effect.refinement;
|
54
|
+
if (FIELD_CONFIG_SYMBOL in refinementFunction) {
|
55
|
+
return refinementFunction[FIELD_CONFIG_SYMBOL];
|
56
|
+
}
|
57
|
+
}
|
58
|
+
if ("innerType" in typedSchema._def) {
|
59
|
+
return getFieldConfigInZodStack(typedSchema._def.innerType);
|
60
|
+
}
|
61
|
+
if ("schema" in typedSchema._def) {
|
62
|
+
return getFieldConfigInZodStack(typedSchema._def.schema);
|
63
|
+
}
|
64
|
+
return {};
|
65
|
+
}
|
66
|
+
|
67
|
+
function inferFieldType(schema, fieldType) {
|
68
|
+
if (fieldType) {
|
69
|
+
return fieldType;
|
70
|
+
}
|
71
|
+
var type = schema._def.typeName;
|
72
|
+
var zodToInputType = new Map([["ZodObject", "object"], ["ZodString", "string"], ["ZodNumber", "number"], ["ZodBoolean", "boolean"], ["ZodDate", "date"], ["ZodEnum", "select"], ["ZodNativeEnum", "select"], ["ZodArray", "array"]]);
|
73
|
+
var match = zodToInputType.get(type);
|
74
|
+
return match || "string"; // Default to string for unknown types
|
75
|
+
}
|
76
|
+
|
77
|
+
var _excluded$1 = ["fieldType"];
|
78
|
+
function parseField(key, schema) {
|
79
|
+
var baseSchema = getBaseSchema(schema);
|
80
|
+
var _getFieldConfigInZodS = getFieldConfigInZodStack(schema),
|
81
|
+
fieldType = _getFieldConfigInZodS.fieldType,
|
82
|
+
fieldConfig = _objectWithoutPropertiesLoose(_getFieldConfigInZodS, _excluded$1);
|
83
|
+
var type = inferFieldType(baseSchema, fieldType);
|
84
|
+
var defaultValue = getDefaultValueInZodStack(schema);
|
85
|
+
// Enums
|
86
|
+
var options = baseSchema._def.values;
|
87
|
+
var optionValues = [];
|
88
|
+
if (options) {
|
89
|
+
if (!Array.isArray(options)) {
|
90
|
+
optionValues = Object.entries(options);
|
91
|
+
} else {
|
92
|
+
optionValues = options.map(function (value) {
|
93
|
+
return [value, value];
|
94
|
+
});
|
95
|
+
}
|
96
|
+
}
|
97
|
+
// Arrays and objects
|
98
|
+
var subSchema = [];
|
99
|
+
if (baseSchema instanceof zod.z.ZodObject) {
|
100
|
+
subSchema = Object.entries(baseSchema.shape).map(function (_ref) {
|
101
|
+
var key = _ref[0],
|
102
|
+
field = _ref[1];
|
103
|
+
return parseField(key, field);
|
104
|
+
});
|
105
|
+
}
|
106
|
+
if (baseSchema instanceof zod.z.ZodArray) {
|
107
|
+
subSchema = [parseField("0", baseSchema._def.type)];
|
108
|
+
}
|
109
|
+
var resp = {
|
110
|
+
key: key,
|
111
|
+
type: type,
|
112
|
+
required: !schema.isOptional(),
|
113
|
+
"default": defaultValue,
|
114
|
+
fieldConfig: fieldConfig,
|
115
|
+
options: optionValues,
|
116
|
+
schema: subSchema,
|
117
|
+
description: baseSchema.description
|
118
|
+
};
|
119
|
+
return resp;
|
120
|
+
}
|
121
|
+
function getBaseSchema(schema) {
|
122
|
+
if ("innerType" in schema._def) {
|
123
|
+
return getBaseSchema(schema._def.innerType);
|
124
|
+
}
|
125
|
+
if ("schema" in schema._def) {
|
126
|
+
return getBaseSchema(schema._def.schema);
|
127
|
+
}
|
128
|
+
return schema;
|
129
|
+
}
|
130
|
+
var parseSchema = function parseSchema(S) {
|
131
|
+
var objectSchema = S instanceof zod.z.ZodEffects ? S.innerType() : S;
|
132
|
+
var shape = objectSchema.shape;
|
133
|
+
var fields = Object.fromEntries(Object.entries(shape).map(function (_ref2) {
|
134
|
+
var key = _ref2[0],
|
135
|
+
field = _ref2[1];
|
136
|
+
return [key, parseField(key, field)];
|
137
|
+
}));
|
138
|
+
return {
|
139
|
+
fields: fields
|
140
|
+
};
|
141
|
+
};
|
142
|
+
|
143
|
+
var useSchema = function useSchema() {
|
144
|
+
return useContextSelector.useContext(ZodResolverContext);
|
145
|
+
};
|
146
|
+
var useFields = function useFields(key) {
|
147
|
+
var S = useSchema();
|
148
|
+
var _parseSchema = parseSchema(S),
|
149
|
+
fields = _parseSchema.fields;
|
150
|
+
return fields[key];
|
151
|
+
};
|
152
|
+
|
153
|
+
var _excluded = ["key"];
|
154
|
+
var Element = function Element(_ref) {
|
155
|
+
var name = _ref.name;
|
156
|
+
var InputMapping = reactInputMapping.useInputMapping();
|
157
|
+
var field = useFields(name);
|
158
|
+
var inputs = Object.values(field.schema);
|
159
|
+
var id = react.useId();
|
160
|
+
return jsxRuntime.jsx(jsxRuntime.Fragment, {
|
161
|
+
children: inputs.map(function (props) {
|
162
|
+
var Element = InputMapping.get(props.type);
|
163
|
+
var key = props.key,
|
164
|
+
prop = _objectWithoutPropertiesLoose(props, _excluded);
|
165
|
+
return react.createElement(Element, _extends({}, prop, {
|
166
|
+
key: key + "-" + id
|
167
|
+
}));
|
168
|
+
})
|
169
|
+
});
|
170
|
+
};
|
171
|
+
|
172
|
+
var Provider = function Provider(_ref) {
|
173
|
+
var children = _ref.children,
|
174
|
+
schema = _ref.schema;
|
175
|
+
return jsxRuntime.jsx(ZodResolverContext.Provider, {
|
176
|
+
value: schema,
|
177
|
+
children: children
|
178
|
+
});
|
179
|
+
};
|
180
|
+
|
181
|
+
var ZodSchemaResolver = function ZodSchemaResolver() {
|
182
|
+
return {
|
183
|
+
useSchema: useSchema,
|
184
|
+
useFields: useFields,
|
185
|
+
fieldConfig: function fieldConfig$1(config) {
|
186
|
+
return fieldConfig(config);
|
187
|
+
},
|
188
|
+
FormInstantProvider: Provider,
|
189
|
+
FormInstantElement: Element
|
190
|
+
};
|
191
|
+
};
|
192
|
+
|
193
|
+
exports.ZodSchemaResolver = ZodSchemaResolver;
|
194
|
+
//# sourceMappingURL=react-resolver-zod.cjs.development.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"react-resolver-zod.cjs.development.js","sources":["../src/context.tsx","../src/funcs/default-values.ts","../src/funcs/field-config.ts","../src/funcs/field-type-inference.ts","../src/funcs/schema-parser.ts","../src/useSchema.tsx","../src/element.tsx","../src/provider.tsx","../src/index.ts"],"sourcesContent":["import { createContext } from \"use-context-selector\";\nimport { zodResolverProps } from \"./type\";\n\nexport const ZodResolverContext = createContext<zodResolverProps>({} as zodResolverProps);\n","import { z } from \"zod\";\nimport { ZodObjectOrWrapped } from \"./types\";\n\nexport function getDefaultValueInZodStack(schema: z.ZodTypeAny): any {\n if (schema instanceof z.ZodDefault) {\n return schema._def.defaultValue();\n }\n\n if (schema instanceof z.ZodEffects) {\n return getDefaultValueInZodStack(schema.innerType());\n }\n\n return undefined;\n}\n\nexport function getDefaultValues(schema: ZodObjectOrWrapped): Record<string, any> {\n const objectSchema = schema instanceof z.ZodEffects ? schema.innerType() : schema;\n const shape = objectSchema.shape;\n\n const defaultValues: Record<string, any> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const defaultValue = getDefaultValueInZodStack(field as z.ZodTypeAny);\n if (defaultValue !== undefined) {\n defaultValues[key] = defaultValue;\n }\n }\n\n return defaultValues;\n}\n","import { RefinementEffect, z } from \"zod\";\nimport { FieldConfig, SuperRefineFunction } from \"./types\";\nexport const FIELD_CONFIG_SYMBOL = Symbol(\"GetFieldConfig\");\n\nexport function fieldConfig<AdditionalRenderable = null, FieldTypes = string>(\n config: FieldConfig<AdditionalRenderable, FieldTypes>,\n): SuperRefineFunction {\n const refinementFunction: SuperRefineFunction = () => {\n // Do nothing.\n };\n\n // @ts-expect-error This is a symbol and not a real value.\n refinementFunction[FIELD_CONFIG_SYMBOL] = config;\n\n return refinementFunction;\n}\n\nexport function getFieldConfigInZodStack(schema: z.ZodTypeAny): FieldConfig {\n const typedSchema = schema as unknown as z.ZodEffects<z.ZodNumber | z.ZodString>;\n\n if (typedSchema._def.typeName === \"ZodEffects\") {\n const effect = typedSchema._def.effect as RefinementEffect<any>;\n const refinementFunction = effect.refinement;\n\n if (FIELD_CONFIG_SYMBOL in refinementFunction) {\n return refinementFunction[FIELD_CONFIG_SYMBOL] as FieldConfig;\n }\n }\n\n if (\"innerType\" in typedSchema._def) {\n return getFieldConfigInZodStack(typedSchema._def.innerType as unknown as z.ZodAny);\n }\n if (\"schema\" in typedSchema._def) {\n return getFieldConfigInZodStack((typedSchema._def as any).schema as z.ZodAny);\n }\n\n return {};\n}\n","import { z } from \"zod\";\nimport { FieldConfig } from \"./types\";\n\nexport function inferFieldType(schema: z.ZodTypeAny, fieldType?: FieldConfig[\"fieldType\"]): string {\n if (fieldType) {\n return fieldType;\n }\n\n const type = schema._def.typeName;\n\n const zodToInputType = new Map([\n [\"ZodObject\", \"object\"],\n [\"ZodString\", \"string\"],\n [\"ZodNumber\", \"number\"],\n [\"ZodBoolean\", \"boolean\"],\n [\"ZodDate\", \"date\"],\n [\"ZodEnum\", \"select\"],\n [\"ZodNativeEnum\", \"select\"],\n [\"ZodArray\", \"array\"],\n ]);\n\n const match = zodToInputType.get(type);\n\n return match || \"string\"; // Default to string for unknown types\n}\n","import { z } from \"zod\";\nimport { getDefaultValueInZodStack } from \"./default-values\";\nimport { getFieldConfigInZodStack } from \"./field-config\";\nimport { inferFieldType } from \"./field-type-inference\";\nimport { ParsedField, ParsedSchema, ZodObjectOrWrapped } from \"./types\";\n\nfunction parseField(key: string, schema: z.ZodTypeAny): ParsedField<any> {\n const baseSchema = getBaseSchema(schema);\n const { fieldType, ...fieldConfig } = getFieldConfigInZodStack(schema);\n const type = inferFieldType(baseSchema, fieldType);\n const defaultValue = getDefaultValueInZodStack(schema);\n\n // Enums\n const options = baseSchema._def.values;\n let optionValues: [string, string][] = [];\n if (options) {\n if (!Array.isArray(options)) {\n optionValues = Object.entries(options);\n } else {\n optionValues = options.map((value) => [value, value]);\n }\n }\n\n // Arrays and objects\n let subSchema: ParsedField<any>[] = [];\n if (baseSchema instanceof z.ZodObject) {\n subSchema = Object.entries(baseSchema.shape).map(([key, field]) =>\n parseField(key, field as z.ZodTypeAny),\n );\n }\n if (baseSchema instanceof z.ZodArray) {\n subSchema = [parseField(\"0\", baseSchema._def.type)];\n }\n\n const resp = {\n key,\n type,\n required: !schema.isOptional(),\n default: defaultValue,\n fieldConfig,\n options: optionValues,\n schema: subSchema,\n description: baseSchema.description,\n };\n\n return resp;\n}\n\nfunction getBaseSchema<ChildType extends z.ZodAny | z.ZodTypeAny | z.AnyZodObject = z.ZodAny>(\n schema: ChildType | z.ZodEffects<ChildType>,\n): ChildType {\n if (\"innerType\" in schema._def) {\n return getBaseSchema(schema._def.innerType as ChildType);\n }\n if (\"schema\" in schema._def) {\n return getBaseSchema(schema._def.schema as ChildType);\n }\n\n return schema as ChildType;\n}\n\nexport const parseSchema = (S: ZodObjectOrWrapped): ParsedSchema => {\n const objectSchema = S instanceof z.ZodEffects ? S.innerType() : S;\n const shape = objectSchema.shape;\n\n const fields = Object.fromEntries(\n Object.entries(shape).map(([key, field]) => [key, parseField(key, field as z.ZodTypeAny)]),\n );\n\n return { fields };\n};\n","import { useContext } from \"use-context-selector\";\nimport { ZodEffects, ZodObject } from \"zod\";\nimport { ZodResolverContext } from \"./context\";\nimport { parseSchema } from \"./funcs/schema-parser\";\n\nexport const useSchema = () =>\n useContext(ZodResolverContext) as ZodObject<never, never> | ZodEffects<never, never>;\n\nexport const useFields = <S extends Record<string, any>>(key: keyof S) => {\n const S = useSchema();\n\n const { fields } = parseSchema(S);\n\n return fields[key as string];\n};\n","import { useInputMapping } from '@form-instant/react-input-mapping';\nimport { useId } from 'react';\nimport { useFields } from './useSchema';\n\nexport interface ElementProps<Schema extends Record<string, any>> {\n name: keyof Schema;\n}\n\nexport const Element = <S extends Record<string, any>>({\n name,\n}: ElementProps<S>) => {\n const InputMapping = useInputMapping();\n const field = useFields(name);\n\n const inputs = Object.values(field.schema!);\n\n const id = useId();\n\n return (\n <>\n {inputs.map((props) => {\n const Element = InputMapping.get(props.type)!;\n\n const { key, ...prop } = props;\n\n return <Element {...prop} key={`${key}-${id}`} />;\n })}\n </>\n );\n};\n","\"use client\";\nimport { ZodResolverContext } from \"./context\";\nimport { zodResolverProps } from \"./type\";\n\nexport const Provider: FCC<{ schema: zodResolverProps }> = ({ children, schema }) => {\n return <ZodResolverContext.Provider value={schema}>{children}</ZodResolverContext.Provider>;\n};\n","export * from './type';\nimport { Element } from './element';\nimport { fieldConfig } from './funcs/field-config';\nimport { FieldConfig } from './funcs/types';\nimport { Provider } from './provider';\nimport { useFields, useSchema } from './useSchema';\n\nexport const ZodSchemaResolver = <\n AdditionalRenderable = null,\n FieldTypes = string,\n>() => ({\n useSchema,\n useFields,\n fieldConfig: (config: FieldConfig<AdditionalRenderable, FieldTypes>) =>\n fieldConfig<AdditionalRenderable, FieldTypes>(config),\n FormInstantProvider: Provider,\n FormInstantElement: Element,\n});\n"],"names":["ZodResolverContext","createContext","getDefaultValueInZodStack","schema","z","ZodDefault","_def","defaultValue","ZodEffects","innerType","undefined","FIELD_CONFIG_SYMBOL","Symbol","fieldConfig","config","refinementFunction","getFieldConfigInZodStack","typedSchema","typeName","effect","refinement","inferFieldType","fieldType","type","zodToInputType","Map","match","get","parseField","key","baseSchema","getBaseSchema","_getFieldConfigInZodS","_objectWithoutPropertiesLoose","_excluded","options","values","optionValues","Array","isArray","Object","entries","map","value","subSchema","ZodObject","shape","_ref","field","ZodArray","resp","required","isOptional","description","parseSchema","S","objectSchema","fields","fromEntries","_ref2","useSchema","useContext","useFields","_parseSchema","Element","name","InputMapping","useInputMapping","inputs","id","useId","_jsx","props","prop","_createElement","_extends","Provider","children","ZodSchemaResolver","FormInstantProvider","FormInstantElement"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,kBAAkB,gBAAGC,gCAAa,CAAmB,EAAsB,CAAC;;ACAnF,SAAUC,yBAAyBA,CAACC,MAAoB,EAAA;AAC1D,EAAA,IAAIA,MAAM,YAAYC,KAAC,CAACC,UAAU,EAAE;AAChC,IAAA,OAAOF,MAAM,CAACG,IAAI,CAACC,YAAY,EAAE,CAAA;AACrC,GAAA;AAEA,EAAA,IAAIJ,MAAM,YAAYC,KAAC,CAACI,UAAU,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8B,QAAQ,GAAA9B,IAAA,CAAR8B,QAAQ;IAAE1E,MAAM,GAAA4C,IAAA,CAAN5C,MAAM,CAAA;AAC1E,EAAA,OAAOoE,cAAA,CAACvE,kBAAkB,CAAC4E,QAAQ,EAAA;AAACjC,IAAAA,KAAK,EAAExC,MAAM;AAAA0E,IAAAA,QAAA,EAAGA,QAAAA;AAAQ,GAAA,CAA+B,CAAA;AAC/F,CAAC;;ACCYC,IAAAA,iBAAiB,GAAG,SAApBA,iBAAiBA,GAAA;EAAA,OAGtB;AACNlB,IAAAA,SAAS,EAATA,SAAS;AACTE,IAAAA,SAAS,EAATA,SAAS;AACTjD,IAAAA,WAAW,EAAE,SAAbA,aAAWA,CAAGC,MAAqD,EAAA;MAAA,OACjED,WAAW,CAAmCC,MAAM,CAAC,CAAA;AAAA,KAAA;AACvDiE,IAAAA,mBAAmB,EAAEH,QAAQ;AAC7BI,IAAAA,kBAAkB,EAAEhB,OAAAA;GACrB,CAAA;AAAA;;;;"}
|
@@ -0,0 +1,2 @@
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),n=require("react"),r=require("@form-instant/react-input-mapping"),t=require("use-context-selector"),i=require("zod");function a(){return a=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];for(var t in r)({}).hasOwnProperty.call(r,t)&&(e[t]=r[t])}return e},a.apply(null,arguments)}function o(e,n){if(null==e)return{};var r={};for(var t in e)if({}.hasOwnProperty.call(e,t)){if(n.includes(t))continue;r[t]=e[t]}return r}var u=t.createContext({});function f(e){return e instanceof i.z.ZodDefault?e._def.defaultValue():e instanceof i.z.ZodEffects?f(e.innerType()):void 0}var c=Symbol("GetFieldConfig");function s(e){var n=e;if("ZodEffects"===n._def.typeName){var r=n._def.effect.refinement;if(c in r)return r[c]}return"innerType"in n._def?s(n._def.innerType):"schema"in n._def?s(n._def.schema):{}}var d=["fieldType"];function l(e,n){var r=p(n),t=s(n),a=t.fieldType,u=o(t,d),c=function(e,n){if(n)return n;var r=e._def.typeName;return new Map([["ZodObject","object"],["ZodString","string"],["ZodNumber","number"],["ZodBoolean","boolean"],["ZodDate","date"],["ZodEnum","select"],["ZodNativeEnum","select"],["ZodArray","array"]]).get(r)||"string"}(r,a),m=f(n),v=r._def.values,y=[];v&&(y=Array.isArray(v)?v.map((function(e){return[e,e]})):Object.entries(v));var h=[];return r instanceof i.z.ZodObject&&(h=Object.entries(r.shape).map((function(e){return l(e[0],e[1])}))),r instanceof i.z.ZodArray&&(h=[l("0",r._def.type)]),{key:e,type:c,required:!n.isOptional(),default:m,fieldConfig:u,options:y,schema:h,description:r.description}}function p(e){return"innerType"in e._def?p(e._def.innerType):"schema"in e._def?p(e._def.schema):e}var m=function(){return t.useContext(u)},v=function(e){var n,r,t=(r=(n=m())instanceof i.z.ZodEffects?n.innerType():n,{fields:Object.fromEntries(Object.entries(r.shape).map((function(e){var n=e[0];return[n,l(n,e[1])]})))});return t.fields[e]},y=["key"],h=function(t){var i=t.name,u=r.useInputMapping(),f=v(i),c=Object.values(f.schema),s=n.useId();return e.jsx(e.Fragment,{children:c.map((function(e){var r=u.get(e.type),t=e.key,i=o(e,y);return n.createElement(r,a({},i,{key:t+"-"+s}))}))})},b=function(n){return e.jsx(u.Provider,{value:n.schema,children:n.children})};exports.ZodSchemaResolver=function(){return{useSchema:m,useFields:v,fieldConfig:function(e){return function(e){var n=function(){};return n[c]=e,n}(e)},FormInstantProvider:b,FormInstantElement:h}};
|
2
|
+
//# sourceMappingURL=react-resolver-zod.cjs.production.min.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"react-resolver-zod.cjs.production.min.js","sources":["../src/context.tsx","../src/funcs/default-values.ts","../src/funcs/field-config.ts","../src/funcs/schema-parser.ts","../src/funcs/field-type-inference.ts","../src/useSchema.tsx","../src/element.tsx","../src/provider.tsx","../src/index.ts"],"sourcesContent":["import { createContext } from \"use-context-selector\";\nimport { zodResolverProps } from \"./type\";\n\nexport const ZodResolverContext = createContext<zodResolverProps>({} as zodResolverProps);\n","import { z } from \"zod\";\nimport { ZodObjectOrWrapped } from \"./types\";\n\nexport function getDefaultValueInZodStack(schema: z.ZodTypeAny): any {\n if (schema instanceof z.ZodDefault) {\n return schema._def.defaultValue();\n }\n\n if (schema instanceof z.ZodEffects) {\n return getDefaultValueInZodStack(schema.innerType());\n }\n\n return undefined;\n}\n\nexport function getDefaultValues(schema: ZodObjectOrWrapped): Record<string, any> {\n const objectSchema = schema instanceof z.ZodEffects ? schema.innerType() : schema;\n const shape = objectSchema.shape;\n\n const defaultValues: Record<string, any> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const defaultValue = getDefaultValueInZodStack(field as z.ZodTypeAny);\n if (defaultValue !== undefined) {\n defaultValues[key] = defaultValue;\n }\n }\n\n return defaultValues;\n}\n","import { RefinementEffect, z } from \"zod\";\nimport { FieldConfig, SuperRefineFunction } from \"./types\";\nexport const FIELD_CONFIG_SYMBOL = Symbol(\"GetFieldConfig\");\n\nexport function fieldConfig<AdditionalRenderable = null, FieldTypes = string>(\n config: FieldConfig<AdditionalRenderable, FieldTypes>,\n): SuperRefineFunction {\n const refinementFunction: SuperRefineFunction = () => {\n // Do nothing.\n };\n\n // @ts-expect-error This is a symbol and not a real value.\n refinementFunction[FIELD_CONFIG_SYMBOL] = config;\n\n return refinementFunction;\n}\n\nexport function getFieldConfigInZodStack(schema: z.ZodTypeAny): FieldConfig {\n const typedSchema = schema as unknown as z.ZodEffects<z.ZodNumber | z.ZodString>;\n\n if (typedSchema._def.typeName === \"ZodEffects\") {\n const effect = typedSchema._def.effect as RefinementEffect<any>;\n const refinementFunction = effect.refinement;\n\n if (FIELD_CONFIG_SYMBOL in refinementFunction) {\n return refinementFunction[FIELD_CONFIG_SYMBOL] as FieldConfig;\n }\n }\n\n if (\"innerType\" in typedSchema._def) {\n return getFieldConfigInZodStack(typedSchema._def.innerType as unknown as z.ZodAny);\n }\n if (\"schema\" in typedSchema._def) {\n return getFieldConfigInZodStack((typedSchema._def as any).schema as z.ZodAny);\n }\n\n return {};\n}\n","import { z } from \"zod\";\nimport { getDefaultValueInZodStack } from \"./default-values\";\nimport { getFieldConfigInZodStack } from \"./field-config\";\nimport { inferFieldType } from \"./field-type-inference\";\nimport { ParsedField, ParsedSchema, ZodObjectOrWrapped } from \"./types\";\n\nfunction parseField(key: string, schema: z.ZodTypeAny): ParsedField<any> {\n const baseSchema = getBaseSchema(schema);\n const { fieldType, ...fieldConfig } = getFieldConfigInZodStack(schema);\n const type = inferFieldType(baseSchema, fieldType);\n const defaultValue = getDefaultValueInZodStack(schema);\n\n // Enums\n const options = baseSchema._def.values;\n let optionValues: [string, string][] = [];\n if (options) {\n if (!Array.isArray(options)) {\n optionValues = Object.entries(options);\n } else {\n optionValues = options.map((value) => [value, value]);\n }\n }\n\n // Arrays and objects\n let subSchema: ParsedField<any>[] = [];\n if (baseSchema instanceof z.ZodObject) {\n subSchema = Object.entries(baseSchema.shape).map(([key, field]) =>\n parseField(key, field as z.ZodTypeAny),\n );\n }\n if (baseSchema instanceof z.ZodArray) {\n subSchema = [parseField(\"0\", baseSchema._def.type)];\n }\n\n const resp = {\n key,\n type,\n required: !schema.isOptional(),\n default: defaultValue,\n fieldConfig,\n options: optionValues,\n schema: subSchema,\n description: baseSchema.description,\n };\n\n return resp;\n}\n\nfunction getBaseSchema<ChildType extends z.ZodAny | z.ZodTypeAny | z.AnyZodObject = z.ZodAny>(\n schema: ChildType | z.ZodEffects<ChildType>,\n): ChildType {\n if (\"innerType\" in schema._def) {\n return getBaseSchema(schema._def.innerType as ChildType);\n }\n if (\"schema\" in schema._def) {\n return getBaseSchema(schema._def.schema as ChildType);\n }\n\n return schema as ChildType;\n}\n\nexport const parseSchema = (S: ZodObjectOrWrapped): ParsedSchema => {\n const objectSchema = S instanceof z.ZodEffects ? S.innerType() : S;\n const shape = objectSchema.shape;\n\n const fields = Object.fromEntries(\n Object.entries(shape).map(([key, field]) => [key, parseField(key, field as z.ZodTypeAny)]),\n );\n\n return { fields };\n};\n","import { z } from \"zod\";\nimport { FieldConfig } from \"./types\";\n\nexport function inferFieldType(schema: z.ZodTypeAny, fieldType?: FieldConfig[\"fieldType\"]): string {\n if (fieldType) {\n return fieldType;\n }\n\n const type = schema._def.typeName;\n\n const zodToInputType = new Map([\n [\"ZodObject\", \"object\"],\n [\"ZodString\", \"string\"],\n [\"ZodNumber\", \"number\"],\n [\"ZodBoolean\", \"boolean\"],\n [\"ZodDate\", \"date\"],\n [\"ZodEnum\", \"select\"],\n [\"ZodNativeEnum\", \"select\"],\n [\"ZodArray\", \"array\"],\n ]);\n\n const match = zodToInputType.get(type);\n\n return match || \"string\"; // Default to string for unknown types\n}\n","import { useContext } from \"use-context-selector\";\nimport { ZodEffects, ZodObject } from \"zod\";\nimport { ZodResolverContext } from \"./context\";\nimport { parseSchema } from \"./funcs/schema-parser\";\n\nexport const useSchema = () =>\n useContext(ZodResolverContext) as ZodObject<never, never> | ZodEffects<never, never>;\n\nexport const useFields = <S extends Record<string, any>>(key: keyof S) => {\n const S = useSchema();\n\n const { fields } = parseSchema(S);\n\n return fields[key as string];\n};\n","import { useInputMapping } from '@form-instant/react-input-mapping';\nimport { useId } from 'react';\nimport { useFields } from './useSchema';\n\nexport interface ElementProps<Schema extends Record<string, any>> {\n name: keyof Schema;\n}\n\nexport const Element = <S extends Record<string, any>>({\n name,\n}: ElementProps<S>) => {\n const InputMapping = useInputMapping();\n const field = useFields(name);\n\n const inputs = Object.values(field.schema!);\n\n const id = useId();\n\n return (\n <>\n {inputs.map((props) => {\n const Element = InputMapping.get(props.type)!;\n\n const { key, ...prop } = props;\n\n return <Element {...prop} key={`${key}-${id}`} />;\n })}\n </>\n );\n};\n","\"use client\";\nimport { ZodResolverContext } from \"./context\";\nimport { zodResolverProps } from \"./type\";\n\nexport const Provider: FCC<{ schema: zodResolverProps }> = ({ children, schema }) => {\n return <ZodResolverContext.Provider value={schema}>{children}</ZodResolverContext.Provider>;\n};\n","export * from './type';\nimport { Element } from './element';\nimport { fieldConfig } from './funcs/field-config';\nimport { FieldConfig } from './funcs/types';\nimport { Provider } from './provider';\nimport { useFields, useSchema } from './useSchema';\n\nexport const ZodSchemaResolver = <\n AdditionalRenderable = null,\n FieldTypes = string,\n>() => ({\n useSchema,\n useFields,\n fieldConfig: (config: FieldConfig<AdditionalRenderable, FieldTypes>) =>\n fieldConfig<AdditionalRenderable, FieldTypes>(config),\n FormInstantProvider: Provider,\n FormInstantElement: Element,\n});\n"],"names":["ZodResolverContext","createContext","getDefaultValueInZodStack","schema","z","ZodDefault","_def","defaultValue","ZodEffects","innerType","FIELD_CONFIG_SYMBOL","Symbol","getFieldConfigInZodStack","typedSchema","typeName","refinementFunction","effect","refinement","parseField","key","baseSchema","getBaseSchema","_getFieldConfigInZodS","fieldType","fieldConfig","_objectWithoutPropertiesLoose","_excluded","type","Map","get","inferFieldType","options","values","optionValues","Array","isArray","map","value","Object","entries","subSchema","ZodObject","shape","_ref","ZodArray","required","isOptional","default","description","useSchema","useContext","useFields","S","objectSchema","_parseSchema","fields","fromEntries","_ref2","Element","name","InputMapping","useInputMapping","field","inputs","id","useId","_jsx","props","prop","_createElement","createElement","_extends","Provider","jsx","children","config","FormInstantProvider","FormInstantElement"],"mappings":"sgBAGO,IAAMA,EAAqBC,EAAaA,cAAmB,ICA5D,SAAUC,EAA0BC,GACtC,OAAIA,aAAkBC,EAACA,EAACC,WACbF,EAAOG,KAAKC,eAGnBJ,aAAkBC,EAACA,EAACI,WACbN,EAA0BC,EAAOM,kBAD5C,CAKJ,CCXO,IAAMC,EAAsBC,OAAO,kBAepC,SAAUC,EAAyBT,GACrC,IAAMU,EAAcV,EAEpB,GAAkC,eAA9BU,EAAYP,KAAKQ,SAA2B,CAC5C,IACMC,EADSF,EAAYP,KAAKU,OACEC,WAElC,GAAIP,KAAuBK,EACvB,OAAOA,EAAmBL,EAElC,CAEA,MAAI,cAAeG,EAAYP,KACpBM,EAAyBC,EAAYP,KAAKG,WAEjD,WAAYI,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AAH,OAClBC,EAAAA,WAAWlD,EAAyE,EAE3EmD,EAAY,SAAgChC,GACrD,IFoDwBiC,EAClBC,EEnDNC,GFmDMD,GADkBD,EEpDdH,eFqDwB7C,EAACA,EAACI,WAAa4C,EAAE3C,YAAc2C,EAO1D,CAAEG,OAJMjB,OAAOkB,YAClBlB,OAAOC,QAHGc,EAAaX,OAGDN,KAAI,SAAAqB,GAAA,IAAEtC,EAAGsC,EAAA,GAAO,MAAM,CAACtC,EAAKD,EAAWC,EAAvBsC,EAAA,IAAmD,OErD7F,OAFcH,EAANC,OAEMpC,EAClB,YCNauC,EAAU,SAAHf,GAEE,IADpBgB,EAAIhB,EAAJgB,KAEMC,EAAeC,EAAAA,kBACfC,EAAQX,EAAUQ,GAElBI,EAASzB,OAAON,OAAO8B,EAAM3D,QAE7B6D,EAAKC,EAAAA,QAEX,OACEC,EAAAA,yBACGH,EAAO3B,KAAI,SAAC+B,GACX,IAAMT,EAAUE,EAAa/B,IAAIsC,EAAMxC,MAE/BR,EAAiBgD,EAAjBhD,IAAQiD,EAAI3C,EAAK0C,EAAKzC,GAE9B,OAAO2C,EAACC,cAAAZ,EAAOa,KAAKH,EAAI,CAAEjD,IAAQA,EAAO6C,IAAAA,SAIjD,ECzBaQ,EAA8C,SAAtC7B,GACjB,OAAOuB,EAAAO,IAACzE,EAAmBwE,SAAQ,CAACnC,MADsCM,EAANxC,OACnBuE,SADiB/B,EAAR+B,UAE9D,4BCCiC,WAAH,MAGtB,CACNzB,UAAAA,EACAE,UAAAA,EACA3B,YAAa,SAACmD,GAAqD,ONT/D,SACFA,GAEA,IAAM5D,EAA0C,aAOhD,OAFAA,EAAmBL,GAAuBiE,EAEnC5D,CACX,CMDIS,CAA8CmD,EAAO,EACvDC,oBAAqBJ,EACrBK,mBAAoBnB,EACrB"}
|
@@ -0,0 +1,192 @@
|
|
1
|
+
import { jsx, Fragment } from 'react/jsx-runtime';
|
2
|
+
import { useId, createElement } from 'react';
|
3
|
+
import { useInputMapping } from '@form-instant/react-input-mapping';
|
4
|
+
import { createContext, useContext } from 'use-context-selector';
|
5
|
+
import { z } from 'zod';
|
6
|
+
|
7
|
+
function _extends() {
|
8
|
+
return _extends = Object.assign ? Object.assign.bind() : function (n) {
|
9
|
+
for (var e = 1; e < arguments.length; e++) {
|
10
|
+
var t = arguments[e];
|
11
|
+
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
|
12
|
+
}
|
13
|
+
return n;
|
14
|
+
}, _extends.apply(null, arguments);
|
15
|
+
}
|
16
|
+
function _objectWithoutPropertiesLoose(r, e) {
|
17
|
+
if (null == r) return {};
|
18
|
+
var t = {};
|
19
|
+
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
|
20
|
+
if (e.includes(n)) continue;
|
21
|
+
t[n] = r[n];
|
22
|
+
}
|
23
|
+
return t;
|
24
|
+
}
|
25
|
+
|
26
|
+
var ZodResolverContext = /*#__PURE__*/createContext({});
|
27
|
+
|
28
|
+
function getDefaultValueInZodStack(schema) {
|
29
|
+
if (schema instanceof z.ZodDefault) {
|
30
|
+
return schema._def.defaultValue();
|
31
|
+
}
|
32
|
+
if (schema instanceof z.ZodEffects) {
|
33
|
+
return getDefaultValueInZodStack(schema.innerType());
|
34
|
+
}
|
35
|
+
return undefined;
|
36
|
+
}
|
37
|
+
|
38
|
+
var FIELD_CONFIG_SYMBOL = /*#__PURE__*/Symbol("GetFieldConfig");
|
39
|
+
function fieldConfig(config) {
|
40
|
+
var refinementFunction = function refinementFunction() {
|
41
|
+
// Do nothing.
|
42
|
+
};
|
43
|
+
// @ts-expect-error This is a symbol and not a real value.
|
44
|
+
refinementFunction[FIELD_CONFIG_SYMBOL] = config;
|
45
|
+
return refinementFunction;
|
46
|
+
}
|
47
|
+
function getFieldConfigInZodStack(schema) {
|
48
|
+
var typedSchema = schema;
|
49
|
+
if (typedSchema._def.typeName === "ZodEffects") {
|
50
|
+
var effect = typedSchema._def.effect;
|
51
|
+
var refinementFunction = effect.refinement;
|
52
|
+
if (FIELD_CONFIG_SYMBOL in refinementFunction) {
|
53
|
+
return refinementFunction[FIELD_CONFIG_SYMBOL];
|
54
|
+
}
|
55
|
+
}
|
56
|
+
if ("innerType" in typedSchema._def) {
|
57
|
+
return getFieldConfigInZodStack(typedSchema._def.innerType);
|
58
|
+
}
|
59
|
+
if ("schema" in typedSchema._def) {
|
60
|
+
return getFieldConfigInZodStack(typedSchema._def.schema);
|
61
|
+
}
|
62
|
+
return {};
|
63
|
+
}
|
64
|
+
|
65
|
+
function inferFieldType(schema, fieldType) {
|
66
|
+
if (fieldType) {
|
67
|
+
return fieldType;
|
68
|
+
}
|
69
|
+
var type = schema._def.typeName;
|
70
|
+
var zodToInputType = new Map([["ZodObject", "object"], ["ZodString", "string"], ["ZodNumber", "number"], ["ZodBoolean", "boolean"], ["ZodDate", "date"], ["ZodEnum", "select"], ["ZodNativeEnum", "select"], ["ZodArray", "array"]]);
|
71
|
+
var match = zodToInputType.get(type);
|
72
|
+
return match || "string"; // Default to string for unknown types
|
73
|
+
}
|
74
|
+
|
75
|
+
var _excluded$1 = ["fieldType"];
|
76
|
+
function parseField(key, schema) {
|
77
|
+
var baseSchema = getBaseSchema(schema);
|
78
|
+
var _getFieldConfigInZodS = getFieldConfigInZodStack(schema),
|
79
|
+
fieldType = _getFieldConfigInZodS.fieldType,
|
80
|
+
fieldConfig = _objectWithoutPropertiesLoose(_getFieldConfigInZodS, _excluded$1);
|
81
|
+
var type = inferFieldType(baseSchema, fieldType);
|
82
|
+
var defaultValue = getDefaultValueInZodStack(schema);
|
83
|
+
// Enums
|
84
|
+
var options = baseSchema._def.values;
|
85
|
+
var optionValues = [];
|
86
|
+
if (options) {
|
87
|
+
if (!Array.isArray(options)) {
|
88
|
+
optionValues = Object.entries(options);
|
89
|
+
} else {
|
90
|
+
optionValues = options.map(function (value) {
|
91
|
+
return [value, value];
|
92
|
+
});
|
93
|
+
}
|
94
|
+
}
|
95
|
+
// Arrays and objects
|
96
|
+
var subSchema = [];
|
97
|
+
if (baseSchema instanceof z.ZodObject) {
|
98
|
+
subSchema = Object.entries(baseSchema.shape).map(function (_ref) {
|
99
|
+
var key = _ref[0],
|
100
|
+
field = _ref[1];
|
101
|
+
return parseField(key, field);
|
102
|
+
});
|
103
|
+
}
|
104
|
+
if (baseSchema instanceof z.ZodArray) {
|
105
|
+
subSchema = [parseField("0", baseSchema._def.type)];
|
106
|
+
}
|
107
|
+
var resp = {
|
108
|
+
key: key,
|
109
|
+
type: type,
|
110
|
+
required: !schema.isOptional(),
|
111
|
+
"default": defaultValue,
|
112
|
+
fieldConfig: fieldConfig,
|
113
|
+
options: optionValues,
|
114
|
+
schema: subSchema,
|
115
|
+
description: baseSchema.description
|
116
|
+
};
|
117
|
+
return resp;
|
118
|
+
}
|
119
|
+
function getBaseSchema(schema) {
|
120
|
+
if ("innerType" in schema._def) {
|
121
|
+
return getBaseSchema(schema._def.innerType);
|
122
|
+
}
|
123
|
+
if ("schema" in schema._def) {
|
124
|
+
return getBaseSchema(schema._def.schema);
|
125
|
+
}
|
126
|
+
return schema;
|
127
|
+
}
|
128
|
+
var parseSchema = function parseSchema(S) {
|
129
|
+
var objectSchema = S instanceof z.ZodEffects ? S.innerType() : S;
|
130
|
+
var shape = objectSchema.shape;
|
131
|
+
var fields = Object.fromEntries(Object.entries(shape).map(function (_ref2) {
|
132
|
+
var key = _ref2[0],
|
133
|
+
field = _ref2[1];
|
134
|
+
return [key, parseField(key, field)];
|
135
|
+
}));
|
136
|
+
return {
|
137
|
+
fields: fields
|
138
|
+
};
|
139
|
+
};
|
140
|
+
|
141
|
+
var useSchema = function useSchema() {
|
142
|
+
return useContext(ZodResolverContext);
|
143
|
+
};
|
144
|
+
var useFields = function useFields(key) {
|
145
|
+
var S = useSchema();
|
146
|
+
var _parseSchema = parseSchema(S),
|
147
|
+
fields = _parseSchema.fields;
|
148
|
+
return fields[key];
|
149
|
+
};
|
150
|
+
|
151
|
+
var _excluded = ["key"];
|
152
|
+
var Element = function Element(_ref) {
|
153
|
+
var name = _ref.name;
|
154
|
+
var InputMapping = useInputMapping();
|
155
|
+
var field = useFields(name);
|
156
|
+
var inputs = Object.values(field.schema);
|
157
|
+
var id = useId();
|
158
|
+
return jsx(Fragment, {
|
159
|
+
children: inputs.map(function (props) {
|
160
|
+
var Element = InputMapping.get(props.type);
|
161
|
+
var key = props.key,
|
162
|
+
prop = _objectWithoutPropertiesLoose(props, _excluded);
|
163
|
+
return createElement(Element, _extends({}, prop, {
|
164
|
+
key: key + "-" + id
|
165
|
+
}));
|
166
|
+
})
|
167
|
+
});
|
168
|
+
};
|
169
|
+
|
170
|
+
var Provider = function Provider(_ref) {
|
171
|
+
var children = _ref.children,
|
172
|
+
schema = _ref.schema;
|
173
|
+
return jsx(ZodResolverContext.Provider, {
|
174
|
+
value: schema,
|
175
|
+
children: children
|
176
|
+
});
|
177
|
+
};
|
178
|
+
|
179
|
+
var ZodSchemaResolver = function ZodSchemaResolver() {
|
180
|
+
return {
|
181
|
+
useSchema: useSchema,
|
182
|
+
useFields: useFields,
|
183
|
+
fieldConfig: function fieldConfig$1(config) {
|
184
|
+
return fieldConfig(config);
|
185
|
+
},
|
186
|
+
FormInstantProvider: Provider,
|
187
|
+
FormInstantElement: Element
|
188
|
+
};
|
189
|
+
};
|
190
|
+
|
191
|
+
export { ZodSchemaResolver };
|
192
|
+
//# sourceMappingURL=react-resolver-zod.esm.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"react-resolver-zod.esm.js","sources":["../src/context.tsx","../src/funcs/default-values.ts","../src/funcs/field-config.ts","../src/funcs/field-type-inference.ts","../src/funcs/schema-parser.ts","../src/useSchema.tsx","../src/element.tsx","../src/provider.tsx","../src/index.ts"],"sourcesContent":["import { createContext } from \"use-context-selector\";\nimport { zodResolverProps } from \"./type\";\n\nexport const ZodResolverContext = createContext<zodResolverProps>({} as zodResolverProps);\n","import { z } from \"zod\";\nimport { ZodObjectOrWrapped } from \"./types\";\n\nexport function getDefaultValueInZodStack(schema: z.ZodTypeAny): any {\n if (schema instanceof z.ZodDefault) {\n return schema._def.defaultValue();\n }\n\n if (schema instanceof z.ZodEffects) {\n return getDefaultValueInZodStack(schema.innerType());\n }\n\n return undefined;\n}\n\nexport function getDefaultValues(schema: ZodObjectOrWrapped): Record<string, any> {\n const objectSchema = schema instanceof z.ZodEffects ? schema.innerType() : schema;\n const shape = objectSchema.shape;\n\n const defaultValues: Record<string, any> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const defaultValue = getDefaultValueInZodStack(field as z.ZodTypeAny);\n if (defaultValue !== undefined) {\n defaultValues[key] = defaultValue;\n }\n }\n\n return defaultValues;\n}\n","import { RefinementEffect, z } from \"zod\";\nimport { FieldConfig, SuperRefineFunction } from \"./types\";\nexport const FIELD_CONFIG_SYMBOL = Symbol(\"GetFieldConfig\");\n\nexport function fieldConfig<AdditionalRenderable = null, FieldTypes = string>(\n config: FieldConfig<AdditionalRenderable, FieldTypes>,\n): SuperRefineFunction {\n const refinementFunction: SuperRefineFunction = () => {\n // Do nothing.\n };\n\n // @ts-expect-error This is a symbol and not a real value.\n refinementFunction[FIELD_CONFIG_SYMBOL] = config;\n\n return refinementFunction;\n}\n\nexport function getFieldConfigInZodStack(schema: z.ZodTypeAny): FieldConfig {\n const typedSchema = schema as unknown as z.ZodEffects<z.ZodNumber | z.ZodString>;\n\n if (typedSchema._def.typeName === \"ZodEffects\") {\n const effect = typedSchema._def.effect as RefinementEffect<any>;\n const refinementFunction = effect.refinement;\n\n if (FIELD_CONFIG_SYMBOL in refinementFunction) {\n return refinementFunction[FIELD_CONFIG_SYMBOL] as FieldConfig;\n }\n }\n\n if (\"innerType\" in typedSchema._def) {\n return getFieldConfigInZodStack(typedSchema._def.innerType as unknown as z.ZodAny);\n }\n if (\"schema\" in typedSchema._def) {\n return getFieldConfigInZodStack((typedSchema._def as any).schema as z.ZodAny);\n }\n\n return {};\n}\n","import { z } from \"zod\";\nimport { FieldConfig } from \"./types\";\n\nexport function inferFieldType(schema: z.ZodTypeAny, fieldType?: FieldConfig[\"fieldType\"]): string {\n if (fieldType) {\n return fieldType;\n }\n\n const type = schema._def.typeName;\n\n const zodToInputType = new Map([\n [\"ZodObject\", \"object\"],\n [\"ZodString\", \"string\"],\n [\"ZodNumber\", \"number\"],\n [\"ZodBoolean\", \"boolean\"],\n [\"ZodDate\", \"date\"],\n [\"ZodEnum\", \"select\"],\n [\"ZodNativeEnum\", \"select\"],\n [\"ZodArray\", \"array\"],\n ]);\n\n const match = zodToInputType.get(type);\n\n return match || \"string\"; // Default to string for unknown types\n}\n","import { z } from \"zod\";\nimport { getDefaultValueInZodStack } from \"./default-values\";\nimport { getFieldConfigInZodStack } from \"./field-config\";\nimport { inferFieldType } from \"./field-type-inference\";\nimport { ParsedField, ParsedSchema, ZodObjectOrWrapped } from \"./types\";\n\nfunction parseField(key: string, schema: z.ZodTypeAny): ParsedField<any> {\n const baseSchema = getBaseSchema(schema);\n const { fieldType, ...fieldConfig } = getFieldConfigInZodStack(schema);\n const type = inferFieldType(baseSchema, fieldType);\n const defaultValue = getDefaultValueInZodStack(schema);\n\n // Enums\n const options = baseSchema._def.values;\n let optionValues: [string, string][] = [];\n if (options) {\n if (!Array.isArray(options)) {\n optionValues = Object.entries(options);\n } else {\n optionValues = options.map((value) => [value, value]);\n }\n }\n\n // Arrays and objects\n let subSchema: ParsedField<any>[] = [];\n if (baseSchema instanceof z.ZodObject) {\n subSchema = Object.entries(baseSchema.shape).map(([key, field]) =>\n parseField(key, field as z.ZodTypeAny),\n );\n }\n if (baseSchema instanceof z.ZodArray) {\n subSchema = [parseField(\"0\", baseSchema._def.type)];\n }\n\n const resp = {\n key,\n type,\n required: !schema.isOptional(),\n default: defaultValue,\n fieldConfig,\n options: optionValues,\n schema: subSchema,\n description: baseSchema.description,\n };\n\n return resp;\n}\n\nfunction getBaseSchema<ChildType extends z.ZodAny | z.ZodTypeAny | z.AnyZodObject = z.ZodAny>(\n schema: ChildType | z.ZodEffects<ChildType>,\n): ChildType {\n if (\"innerType\" in schema._def) {\n return getBaseSchema(schema._def.innerType as ChildType);\n }\n if (\"schema\" in schema._def) {\n return getBaseSchema(schema._def.schema as ChildType);\n }\n\n return schema as ChildType;\n}\n\nexport const parseSchema = (S: ZodObjectOrWrapped): ParsedSchema => {\n const objectSchema = S instanceof z.ZodEffects ? S.innerType() : S;\n const shape = objectSchema.shape;\n\n const fields = Object.fromEntries(\n Object.entries(shape).map(([key, field]) => [key, parseField(key, field as z.ZodTypeAny)]),\n );\n\n return { fields };\n};\n","import { useContext } from \"use-context-selector\";\nimport { ZodEffects, ZodObject } from \"zod\";\nimport { ZodResolverContext } from \"./context\";\nimport { parseSchema } from \"./funcs/schema-parser\";\n\nexport const useSchema = () =>\n useContext(ZodResolverContext) as ZodObject<never, never> | ZodEffects<never, never>;\n\nexport const useFields = <S extends Record<string, any>>(key: keyof S) => {\n const S = useSchema();\n\n const { fields } = parseSchema(S);\n\n return fields[key as string];\n};\n","import { useInputMapping } from '@form-instant/react-input-mapping';\nimport { useId } from 'react';\nimport { useFields } from './useSchema';\n\nexport interface ElementProps<Schema extends Record<string, any>> {\n name: keyof Schema;\n}\n\nexport const Element = <S extends Record<string, any>>({\n name,\n}: ElementProps<S>) => {\n const InputMapping = useInputMapping();\n const field = useFields(name);\n\n const inputs = Object.values(field.schema!);\n\n const id = useId();\n\n return (\n <>\n {inputs.map((props) => {\n const Element = InputMapping.get(props.type)!;\n\n const { key, ...prop } = props;\n\n return <Element {...prop} key={`${key}-${id}`} />;\n })}\n </>\n );\n};\n","\"use client\";\nimport { ZodResolverContext } from \"./context\";\nimport { zodResolverProps } from \"./type\";\n\nexport const Provider: FCC<{ schema: zodResolverProps }> = ({ children, schema }) => {\n return <ZodResolverContext.Provider value={schema}>{children}</ZodResolverContext.Provider>;\n};\n","export * from './type';\nimport { Element } from './element';\nimport { fieldConfig } from './funcs/field-config';\nimport { FieldConfig } from './funcs/types';\nimport { Provider } from './provider';\nimport { useFields, useSchema } from './useSchema';\n\nexport const ZodSchemaResolver = <\n AdditionalRenderable = null,\n FieldTypes = string,\n>() => ({\n useSchema,\n useFields,\n fieldConfig: (config: FieldConfig<AdditionalRenderable, FieldTypes>) =>\n fieldConfig<AdditionalRenderable, FieldTypes>(config),\n FormInstantProvider: Provider,\n FormInstantElement: Element,\n});\n"],"names":["ZodResolverContext","createContext","getDefaultValueInZodStack","schema","z","ZodDefault","_def","defaultValue","ZodEffects","innerType","undefined","FIELD_CONFIG_SYMBOL","Symbol","fieldConfig","config","refinementFunction","getFieldConfigInZodStack","typedSchema","typeName","effect","refinement","inferFieldType","fieldType","type","zodToInputType","Map","match","get","parseField","key","baseSchema","getBaseSchema","_getFieldConfigInZodS","_objectWithoutPropertiesLoose","_excluded","options","values","optionValues","Array","isArray","Object","entries","map","value","subSchema","ZodObject","shape","_ref","field","ZodArray","resp","required","isOptional","description","parseSchema","S","objectSchema","fields","fromEntries","_ref2","useSchema","useContext","useFields","_parseSchema","Element","name","InputMapping","useInputMapping","inputs","id","useId","_jsx","props","prop","_createElement","_extends","Provider","children","ZodSchemaResolver","FormInstantProvider","FormInstantElement"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,kBAAkB,gBAAGC,aAAa,CAAmB,EAAsB,CAAC;;ACAnF,SAAUC,yBAAyBA,CAACC,MAAoB,EAAA;AAC1D,EAAA,IAAIA,MAAM,YAAYC,CAAC,CAACC,UAAU,EAAE;AAChC,IAAA,OAAOF,MAAM,CAACG,IAAI,CAACC,YAAY,EAAE,CAAA;AACrC,GAAA;AAEA,EAAA,IAAIJ,MAAM,YAAYC,CAAC,CAACI,UAAU,EAAE;AAChC,IAAA,OAAON,yBAAyB,CAACC,MAAM,CAACM,SAAS,EAAE,CAAC,CAAA;AACxD,GAAA;AAEA,EAAA,OAAOC,SAAS,CAAA;AACpB;;ACXO,IAAMC,mBAAmB,gBAAGC,MAAM,CAAC,gBAAgB,CAAC,CAAA;AAErD,SAAUC,W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AAA,EAAGA,QAAAA;AAAQ,GAAA,CAA+B,CAAA;AAC/F,CAAC;;ACCYC,IAAAA,iBAAiB,GAAG,SAApBA,iBAAiBA,GAAA;EAAA,OAGtB;AACNlB,IAAAA,SAAS,EAATA,SAAS;AACTE,IAAAA,SAAS,EAATA,SAAS;AACTjD,IAAAA,WAAW,EAAE,SAAbA,aAAWA,CAAGC,MAAqD,EAAA;MAAA,OACjED,WAAW,CAAmCC,MAAM,CAAC,CAAA;AAAA,KAAA;AACvDiE,IAAAA,mBAAmB,EAAEH,QAAQ;AAC7BI,IAAAA,kBAAkB,EAAEhB,OAAAA;GACrB,CAAA;AAAA;;;;"}
|
package/dist/type.d.ts
ADDED
package/package.json
ADDED
@@ -0,0 +1,79 @@
|
|
1
|
+
{
|
2
|
+
"name": "@form-instant/react-resolver-zod",
|
3
|
+
"version": "0.0.0-alpha",
|
4
|
+
"license": "MIT",
|
5
|
+
"author": {
|
6
|
+
"name": "leomerida15",
|
7
|
+
"email": "dimasmerida15@gmail.com",
|
8
|
+
"url": "https://github.com/leomerida15"
|
9
|
+
},
|
10
|
+
"main": "dist/index.js",
|
11
|
+
"module": "dist/react-input-mapping.esm.js",
|
12
|
+
"typings": "dist/index.d.ts",
|
13
|
+
"files": [
|
14
|
+
"dist",
|
15
|
+
"src"
|
16
|
+
],
|
17
|
+
"private": false,
|
18
|
+
"exports": {
|
19
|
+
".": "./src/index.ts"
|
20
|
+
},
|
21
|
+
"scripts": {
|
22
|
+
"analyze": "size-limit --why",
|
23
|
+
"build": "dts build",
|
24
|
+
"lint": "dts lint",
|
25
|
+
"prepare": "dts build",
|
26
|
+
"size": "size-limit",
|
27
|
+
"start": "dts watch",
|
28
|
+
"test": "dts test --passWithNoTests",
|
29
|
+
"Up": "npm publish --access public"
|
30
|
+
},
|
31
|
+
"husky": {
|
32
|
+
"hooks": {
|
33
|
+
"pre-commit": "dts lint"
|
34
|
+
}
|
35
|
+
},
|
36
|
+
"prettier": {
|
37
|
+
"printWidth": 80,
|
38
|
+
"semi": true,
|
39
|
+
"singleQuote": true,
|
40
|
+
"trailingComma": "es5"
|
41
|
+
},
|
42
|
+
"jest": {
|
43
|
+
"testEnvironment": "jsdom"
|
44
|
+
},
|
45
|
+
"peerDependencies": {
|
46
|
+
"react": ">=16"
|
47
|
+
},
|
48
|
+
"engines": {
|
49
|
+
"node": ">=12"
|
50
|
+
},
|
51
|
+
"size-limit": [
|
52
|
+
{
|
53
|
+
"path": "dist/react-input-mapping.cjs.production.min.js",
|
54
|
+
"limit": "10 KB"
|
55
|
+
},
|
56
|
+
{
|
57
|
+
"path": "dist/react-input-mapping.esm.js",
|
58
|
+
"limit": "10 KB"
|
59
|
+
}
|
60
|
+
],
|
61
|
+
"dependencies": {
|
62
|
+
"@form-instant/react-input-mapping": "^0.0.0-alpha",
|
63
|
+
"use-context-selector": "^2.0.0"
|
64
|
+
},
|
65
|
+
"devDependencies": {
|
66
|
+
"@size-limit/preset-small-lib": "^11.1.4",
|
67
|
+
"@tsconfig/recommended": "^1.0.7",
|
68
|
+
"@tsconfig/vite-react": "^3.0.2",
|
69
|
+
"@types/bun": "^1.1.8",
|
70
|
+
"dts-cli": "^2.0.5",
|
71
|
+
"husky": "^9.1.5",
|
72
|
+
"nodemon": "^3.1.4",
|
73
|
+
"prettier": "^3.3.3",
|
74
|
+
"size-limit": "^11.1.4",
|
75
|
+
"tslib": "^2.7.0",
|
76
|
+
"typescript": "^5.5.4",
|
77
|
+
"zod": "^3.23.8"
|
78
|
+
}
|
79
|
+
}
|
package/src/context.tsx
ADDED
package/src/element.tsx
ADDED
@@ -0,0 +1,30 @@
|
|
1
|
+
import { useInputMapping } from '@form-instant/react-input-mapping';
|
2
|
+
import { useId } from 'react';
|
3
|
+
import { useFields } from './useSchema';
|
4
|
+
|
5
|
+
export interface ElementProps<Schema extends Record<string, any>> {
|
6
|
+
name: keyof Schema;
|
7
|
+
}
|
8
|
+
|
9
|
+
export const Element = <S extends Record<string, any>>({
|
10
|
+
name,
|
11
|
+
}: ElementProps<S>) => {
|
12
|
+
const InputMapping = useInputMapping();
|
13
|
+
const field = useFields(name);
|
14
|
+
|
15
|
+
const inputs = Object.values(field.schema!);
|
16
|
+
|
17
|
+
const id = useId();
|
18
|
+
|
19
|
+
return (
|
20
|
+
<>
|
21
|
+
{inputs.map((props) => {
|
22
|
+
const Element = InputMapping.get(props.type)!;
|
23
|
+
|
24
|
+
const { key, ...prop } = props;
|
25
|
+
|
26
|
+
return <Element {...prop} key={`${key}-${id}`} />;
|
27
|
+
})}
|
28
|
+
</>
|
29
|
+
);
|
30
|
+
};
|
@@ -0,0 +1,30 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
import { ZodObjectOrWrapped } from "./types";
|
3
|
+
|
4
|
+
export function getDefaultValueInZodStack(schema: z.ZodTypeAny): any {
|
5
|
+
if (schema instanceof z.ZodDefault) {
|
6
|
+
return schema._def.defaultValue();
|
7
|
+
}
|
8
|
+
|
9
|
+
if (schema instanceof z.ZodEffects) {
|
10
|
+
return getDefaultValueInZodStack(schema.innerType());
|
11
|
+
}
|
12
|
+
|
13
|
+
return undefined;
|
14
|
+
}
|
15
|
+
|
16
|
+
export function getDefaultValues(schema: ZodObjectOrWrapped): Record<string, any> {
|
17
|
+
const objectSchema = schema instanceof z.ZodEffects ? schema.innerType() : schema;
|
18
|
+
const shape = objectSchema.shape;
|
19
|
+
|
20
|
+
const defaultValues: Record<string, any> = {};
|
21
|
+
|
22
|
+
for (const [key, field] of Object.entries(shape)) {
|
23
|
+
const defaultValue = getDefaultValueInZodStack(field as z.ZodTypeAny);
|
24
|
+
if (defaultValue !== undefined) {
|
25
|
+
defaultValues[key] = defaultValue;
|
26
|
+
}
|
27
|
+
}
|
28
|
+
|
29
|
+
return defaultValues;
|
30
|
+
}
|
@@ -0,0 +1,38 @@
|
|
1
|
+
import { RefinementEffect, z } from "zod";
|
2
|
+
import { FieldConfig, SuperRefineFunction } from "./types";
|
3
|
+
export const FIELD_CONFIG_SYMBOL = Symbol("GetFieldConfig");
|
4
|
+
|
5
|
+
export function fieldConfig<AdditionalRenderable = null, FieldTypes = string>(
|
6
|
+
config: FieldConfig<AdditionalRenderable, FieldTypes>,
|
7
|
+
): SuperRefineFunction {
|
8
|
+
const refinementFunction: SuperRefineFunction = () => {
|
9
|
+
// Do nothing.
|
10
|
+
};
|
11
|
+
|
12
|
+
// @ts-expect-error This is a symbol and not a real value.
|
13
|
+
refinementFunction[FIELD_CONFIG_SYMBOL] = config;
|
14
|
+
|
15
|
+
return refinementFunction;
|
16
|
+
}
|
17
|
+
|
18
|
+
export function getFieldConfigInZodStack(schema: z.ZodTypeAny): FieldConfig {
|
19
|
+
const typedSchema = schema as unknown as z.ZodEffects<z.ZodNumber | z.ZodString>;
|
20
|
+
|
21
|
+
if (typedSchema._def.typeName === "ZodEffects") {
|
22
|
+
const effect = typedSchema._def.effect as RefinementEffect<any>;
|
23
|
+
const refinementFunction = effect.refinement;
|
24
|
+
|
25
|
+
if (FIELD_CONFIG_SYMBOL in refinementFunction) {
|
26
|
+
return refinementFunction[FIELD_CONFIG_SYMBOL] as FieldConfig;
|
27
|
+
}
|
28
|
+
}
|
29
|
+
|
30
|
+
if ("innerType" in typedSchema._def) {
|
31
|
+
return getFieldConfigInZodStack(typedSchema._def.innerType as unknown as z.ZodAny);
|
32
|
+
}
|
33
|
+
if ("schema" in typedSchema._def) {
|
34
|
+
return getFieldConfigInZodStack((typedSchema._def as any).schema as z.ZodAny);
|
35
|
+
}
|
36
|
+
|
37
|
+
return {};
|
38
|
+
}
|
@@ -0,0 +1,25 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
import { FieldConfig } from "./types";
|
3
|
+
|
4
|
+
export function inferFieldType(schema: z.ZodTypeAny, fieldType?: FieldConfig["fieldType"]): string {
|
5
|
+
if (fieldType) {
|
6
|
+
return fieldType;
|
7
|
+
}
|
8
|
+
|
9
|
+
const type = schema._def.typeName;
|
10
|
+
|
11
|
+
const zodToInputType = new Map([
|
12
|
+
["ZodObject", "object"],
|
13
|
+
["ZodString", "string"],
|
14
|
+
["ZodNumber", "number"],
|
15
|
+
["ZodBoolean", "boolean"],
|
16
|
+
["ZodDate", "date"],
|
17
|
+
["ZodEnum", "select"],
|
18
|
+
["ZodNativeEnum", "select"],
|
19
|
+
["ZodArray", "array"],
|
20
|
+
]);
|
21
|
+
|
22
|
+
const match = zodToInputType.get(type);
|
23
|
+
|
24
|
+
return match || "string"; // Default to string for unknown types
|
25
|
+
}
|
@@ -0,0 +1,71 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
import { getDefaultValueInZodStack } from "./default-values";
|
3
|
+
import { getFieldConfigInZodStack } from "./field-config";
|
4
|
+
import { inferFieldType } from "./field-type-inference";
|
5
|
+
import { ParsedField, ParsedSchema, ZodObjectOrWrapped } from "./types";
|
6
|
+
|
7
|
+
function parseField(key: string, schema: z.ZodTypeAny): ParsedField<any> {
|
8
|
+
const baseSchema = getBaseSchema(schema);
|
9
|
+
const { fieldType, ...fieldConfig } = getFieldConfigInZodStack(schema);
|
10
|
+
const type = inferFieldType(baseSchema, fieldType);
|
11
|
+
const defaultValue = getDefaultValueInZodStack(schema);
|
12
|
+
|
13
|
+
// Enums
|
14
|
+
const options = baseSchema._def.values;
|
15
|
+
let optionValues: [string, string][] = [];
|
16
|
+
if (options) {
|
17
|
+
if (!Array.isArray(options)) {
|
18
|
+
optionValues = Object.entries(options);
|
19
|
+
} else {
|
20
|
+
optionValues = options.map((value) => [value, value]);
|
21
|
+
}
|
22
|
+
}
|
23
|
+
|
24
|
+
// Arrays and objects
|
25
|
+
let subSchema: ParsedField<any>[] = [];
|
26
|
+
if (baseSchema instanceof z.ZodObject) {
|
27
|
+
subSchema = Object.entries(baseSchema.shape).map(([key, field]) =>
|
28
|
+
parseField(key, field as z.ZodTypeAny),
|
29
|
+
);
|
30
|
+
}
|
31
|
+
if (baseSchema instanceof z.ZodArray) {
|
32
|
+
subSchema = [parseField("0", baseSchema._def.type)];
|
33
|
+
}
|
34
|
+
|
35
|
+
const resp = {
|
36
|
+
key,
|
37
|
+
type,
|
38
|
+
required: !schema.isOptional(),
|
39
|
+
default: defaultValue,
|
40
|
+
fieldConfig,
|
41
|
+
options: optionValues,
|
42
|
+
schema: subSchema,
|
43
|
+
description: baseSchema.description,
|
44
|
+
};
|
45
|
+
|
46
|
+
return resp;
|
47
|
+
}
|
48
|
+
|
49
|
+
function getBaseSchema<ChildType extends z.ZodAny | z.ZodTypeAny | z.AnyZodObject = z.ZodAny>(
|
50
|
+
schema: ChildType | z.ZodEffects<ChildType>,
|
51
|
+
): ChildType {
|
52
|
+
if ("innerType" in schema._def) {
|
53
|
+
return getBaseSchema(schema._def.innerType as ChildType);
|
54
|
+
}
|
55
|
+
if ("schema" in schema._def) {
|
56
|
+
return getBaseSchema(schema._def.schema as ChildType);
|
57
|
+
}
|
58
|
+
|
59
|
+
return schema as ChildType;
|
60
|
+
}
|
61
|
+
|
62
|
+
export const parseSchema = (S: ZodObjectOrWrapped): ParsedSchema => {
|
63
|
+
const objectSchema = S instanceof z.ZodEffects ? S.innerType() : S;
|
64
|
+
const shape = objectSchema.shape;
|
65
|
+
|
66
|
+
const fields = Object.fromEntries(
|
67
|
+
Object.entries(shape).map(([key, field]) => [key, parseField(key, field as z.ZodTypeAny)]),
|
68
|
+
);
|
69
|
+
|
70
|
+
return { fields };
|
71
|
+
};
|
@@ -0,0 +1,32 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
export type ZodObjectOrWrapped = z.ZodObject<any, any> | z.ZodEffects<z.ZodObject<any, any>>;
|
3
|
+
|
4
|
+
export interface ParsedField<AdditionalRenderable, FieldTypes = string> {
|
5
|
+
key: string;
|
6
|
+
type: string;
|
7
|
+
required: boolean;
|
8
|
+
default?: any;
|
9
|
+
fieldConfig?: FieldConfig<AdditionalRenderable, FieldTypes>;
|
10
|
+
|
11
|
+
// Field-specific
|
12
|
+
options?: [string, string][]; // [value, label] for enums
|
13
|
+
schema?: ParsedField<AdditionalRenderable, FieldTypes>[]; // For objects and arrays
|
14
|
+
}
|
15
|
+
|
16
|
+
export interface ParsedSchema<AdditionalRenderable = null, FieldTypes = string> {
|
17
|
+
fields: Record<string, ParsedField<AdditionalRenderable, FieldTypes>>;
|
18
|
+
}
|
19
|
+
|
20
|
+
export type SuperRefineFunction = () => unknown;
|
21
|
+
|
22
|
+
export type Renderable<AdditionalRenderable = null> =
|
23
|
+
| string
|
24
|
+
| number
|
25
|
+
| boolean
|
26
|
+
| null
|
27
|
+
| undefined
|
28
|
+
| AdditionalRenderable;
|
29
|
+
|
30
|
+
export type FieldConfig<AdditionalRenderable = {}, FieldTypes = string> = {
|
31
|
+
fieldType?: FieldTypes;
|
32
|
+
} & AdditionalRenderable;
|
package/src/global.d.ts
ADDED
package/src/index.ts
ADDED
@@ -0,0 +1,18 @@
|
|
1
|
+
export * from './type';
|
2
|
+
import { Element } from './element';
|
3
|
+
import { fieldConfig } from './funcs/field-config';
|
4
|
+
import { FieldConfig } from './funcs/types';
|
5
|
+
import { Provider } from './provider';
|
6
|
+
import { useFields, useSchema } from './useSchema';
|
7
|
+
|
8
|
+
export const ZodSchemaResolver = <
|
9
|
+
AdditionalRenderable = null,
|
10
|
+
FieldTypes = string,
|
11
|
+
>() => ({
|
12
|
+
useSchema,
|
13
|
+
useFields,
|
14
|
+
fieldConfig: (config: FieldConfig<AdditionalRenderable, FieldTypes>) =>
|
15
|
+
fieldConfig<AdditionalRenderable, FieldTypes>(config),
|
16
|
+
FormInstantProvider: Provider,
|
17
|
+
FormInstantElement: Element,
|
18
|
+
});
|
package/src/provider.tsx
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
"use client";
|
2
|
+
import { ZodResolverContext } from "./context";
|
3
|
+
import { zodResolverProps } from "./type";
|
4
|
+
|
5
|
+
export const Provider: FCC<{ schema: zodResolverProps }> = ({ children, schema }) => {
|
6
|
+
return <ZodResolverContext.Provider value={schema}>{children}</ZodResolverContext.Provider>;
|
7
|
+
};
|
package/src/type.ts
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
import { useContext } from "use-context-selector";
|
2
|
+
import { ZodEffects, ZodObject } from "zod";
|
3
|
+
import { ZodResolverContext } from "./context";
|
4
|
+
import { parseSchema } from "./funcs/schema-parser";
|
5
|
+
|
6
|
+
export const useSchema = () =>
|
7
|
+
useContext(ZodResolverContext) as ZodObject<never, never> | ZodEffects<never, never>;
|
8
|
+
|
9
|
+
export const useFields = <S extends Record<string, any>>(key: keyof S) => {
|
10
|
+
const S = useSchema();
|
11
|
+
|
12
|
+
const { fields } = parseSchema(S);
|
13
|
+
|
14
|
+
return fields[key as string];
|
15
|
+
};
|