@hookform/resolvers 5.5.7 → 5.5.8
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/package.json +1 -1
- package/zod/dist/zod.js +1 -1
- package/zod/dist/zod.js.map +1 -1
- package/zod/dist/zod.mjs +1 -1
- package/zod/dist/zod.modern.mjs +1 -1
- package/zod/dist/zod.modern.mjs.map +1 -1
- package/zod/dist/zod.module.js +1 -1
- package/zod/dist/zod.module.js.map +1 -1
- package/zod/dist/zod.umd.js +1 -1
- package/zod/dist/zod.umd.js.map +1 -1
- package/zod/src/__tests__/special-path-names.ts +55 -0
- package/zod/src/zod.ts +7 -2
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hookform/resolvers",
|
|
3
3
|
"amdName": "hookformResolvers",
|
|
4
|
-
"version": "5.5.
|
|
4
|
+
"version": "5.5.8",
|
|
5
5
|
"description": "React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion, Effect-TS and VineJS",
|
|
6
6
|
"main": "dist/resolvers.js",
|
|
7
7
|
"module": "dist/resolvers.module.js",
|
package/zod/dist/zod.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var r=require("@hookform/resolvers"),e=require("react-hook-form");function n(){return n=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},n.apply(null,arguments)}function o(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function t(r,n){for(var o=
|
|
1
|
+
var r=require("@hookform/resolvers"),e=require("react-hook-form");function n(){return n=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},n.apply(null,arguments)}function o(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function t(r,n){for(var o=Object.create(null);r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!o[a])if("unionErrors"in t){var u,l,c=t.unionErrors.reduce(function(r,e){return e.errors.length<r.errors.length?e:r}).errors[0];o[a]={message:null!=(u=null==c?void 0:c.message)?u:i,type:null!=(l=null==c?void 0:c.code)?l:s}}else o[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),n){var f=o[a].types,d=f&&f[t.code];o[a]=e.appendErrors(a,n,o,s,d?[].concat(d,t.message):t.message)}r.shift()}return o}function s(r,o){for(var t=Object.create(null),s=function(){var s=r[0],i=s.code,a=s.message,u=s.path.join(".");if(!t[u])if("invalid_union"===s.code&&s.errors.length>0){var l,c,f=s.errors.reduce(function(r,e){return e.length<r.length?e:r})[0];t[u]={message:null!=(l=null==f?void 0:f.message)?l:a,type:null!=(c=null==f?void 0:f.code)?c:i}}else t[u]={message:a,type:i};if("invalid_union"===s.code&&s.errors.forEach(function(e){return e.forEach(function(e){return r.push(n({},e,{path:[].concat(s.path,e.path)}))})}),o){var d=t[u].types,v=d&&d[s.code];t[u]=e.appendErrors(u,o,t,i,v?[].concat(v,s.message):s.message)}r.shift()};r.length;)s();return t}exports.zodResolver=function(e,n,i){if(void 0===i&&(i={}),function(r){return"_zod"in r&&"object"==typeof r._zod}(e))return function(t,a,u){try{return Promise.resolve(o(function(){function o(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:i.raw?Object.assign({},t):e}}var s=e;return"sync"===i.mode?o(s.parse(t,n)):Promise.resolve(s.parseAsync(t,n)).then(o)},function(e){if(function(r){var e;return!(null==r||null==(e=r._zod)||null==(e=e.traits)||!e.has("$ZodError"))}(e))return{values:{},errors:r.toNestErrors(s(e.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(r){return Promise.reject(r)}};if(function(r){return"_def"in r&&"object"==typeof r._def}(e))return function(s,a,u){try{return Promise.resolve(o(function(){return Promise.resolve(e["sync"===i.mode?"parse":"parseAsync"](s,n)).then(function(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:i.raw?Object.assign({},s):e}})},function(e){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(e))return{values:{},errors:r.toNestErrors(t(e.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")};
|
|
2
2
|
//# sourceMappingURL=zod.js.map
|
package/zod/dist/zod.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","classicSchema","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"iXAuCA,SAASA,EACPC,EACAC,GAGA,IADA,IAAMC,EAAqC,CAAE,EACtCF,EAAUG,QAAU,CACzB,IAAMC,EAAQJ,EAAU,GAChBK,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKP,EAAOK,GACV,GAAI,gBAAiBH,EAAO,KAAAM,EAAAC,EAWpBC,EAPoBR,EAAMS,YAAYC,OAC1C,SAACC,EAASC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OAARoB,EAAXA,EAAaC,UAAbD,EAAqBE,IAAI,aACpC,CAgSYC,CAAYtD,GACd,MAAO,CACLiC,OAAQ,CAAE,EACVnC,OAAQyD,eACNjC,EACEtB,EAAMwD,QACLrB,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMnC,CACR,GACF,CAAC,MAAAe,GAAAqB,OAAAA,QAAAsB,OAAA3C,EAAA,CAAA,EAGH,GAjUmB,SAACa,GAKpB,MAAO,SAAUA,GAAiC,iBAAhBA,EAAO+B,IAC3C,CA2TMC,CAAahC,GACf,OAAA,SAAcK,EAAeC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,QAAAC,EAAA,kBACrCF,QAAAC,QACiBT,EACQ,SAAzBE,EAAgBiB,KAAkB,QAAU,cAC5Cd,EAAQJ,IAAcqB,KAAA,SAFlBV,GAON,OAHAL,EAAQM,2BACNC,EAAAA,uBAAuB,CAAA,EAAIP,GAEtB,CACLrC,OAAQ,CAAA,EACRmC,OAAQH,EAAgBa,IAAMC,OAAOC,OAAO,CAAA,EAAIZ,GAAUO,EAChB,EAC9C,EAAC,SAAQxC,GACP,GAnVY,SAACA,GACnB,OAAO6D,MAAMC,QAAQ9D,MAAAA,OAAAA,EAAAA,EAAOwD,OAC9B,CAiVYO,CAAY/D,GACd,MAAO,CACLiC,OAAQ,CAAE,EACVnC,OAAQyD,EAAYA,aAClB5D,EACEK,EAAMF,QACLqC,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMnC,CACR,GACF,CAAC,MAAAe,GAAA,OAAAqB,QAAAsB,OAAA3C,EACH,CAAA,EAEA,MAAM,IAAIiD,MAAM,kCAClB"}
|
|
1
|
+
{"version":3,"file":"zod.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`, `__proto__`) when a field is\n // named after one of them — a plain `{}` would make `!errors[_path]`\n // truthy-skip those paths and silently drop their errors.\n const errors: Record<string, FieldError> = Object.create(null);\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // See the matching comment in `parseZod3Issues` above.\n const errors: Record<string, FieldError> = Object.create(null);\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","Object","create","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","assign","classicSchema","_temp","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"iXAuCA,SAASA,EACPC,EACAC,GAOA,IADA,IAAMC,EAAqCC,OAAOC,OAAO,MAClDJ,EAAUK,QAAU,CACzB,IAAMC,EAAQN,EAAU,GAChBO,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKT,EAAOO,GACV,GAAI,gBAAiBH,EAAO,CAAAM,IAAAA,EAAAC,EAWpBC,EAPoBR,EAAMS,YAAYC,OAC1C,SAACC,EAASC,GACR,OAAAA,EAAQhB,OAAOG,OAASY,EAAQf,OAAOG,OAASa,EAAUD,CAAO,GAKhCf,OAAO,GAE5CA,EAAOO,GAAS,CACdD,QAA4BI,OAArBA,EAAY,MAAVE,OAAU,EAAVA,EAAYN,SAAOI,EAAIJ,EAChCW,KAAsB,OAAlBN,EAAY,MAAVC,OAAU,EAAVA,EAAYP,MAAIM,EAAIN,EAE9B,MACEL,EAAOO,GAAS,CAAED,QAAAA,EAASW,KAAMZ,GAUrC,GANI,gBAAiBD,GACnBA,EAAMS,YAAYK,QAAQ,SAACN,GAAU,OACnCA,EAAWZ,OAAOkB,QAAQ,SAACC,GAAM,OAAArB,EAAUsB,KAAKD,EAAE,EAAC,G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ACrCF,OAAAA,QAAAC,QACiBT,EACQ,SAAzBE,EAAgBiB,KAAkB,QAAU,cAC5Cd,EAAQJ,IAAcqB,KAFlBV,SAAAA,GAON,OAHAL,EAAQM,2BACNC,EAAsBA,uBAAC,GAAIP,GAEtB,CACLvC,OAAQ,CAAA,EACRqC,OAAQH,EAAgBa,IAAM9C,OAAO+C,OAAO,CAAA,EAAIX,GAAUO,EAChB,EAC9C,EAASxC,SAAAA,GACP,GAxVY,SAACA,GACnB,OAAO6D,MAAMC,QAAa,MAAL9D,OAAK,EAALA,EAAOwD,OAC9B,CAsVYO,CAAY/D,GACd,MAAO,CACLiC,OAAQ,CAAE,EACVrC,OAAQ2D,EAAYA,aAClB9D,EACEO,EAAMJ,QACLuC,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMnC,CACR,GACF,CAAC,MAAAe,GAAAqB,OAAAA,QAAAsB,OAAA3C,EAAA,CAAA,EAGH,UAAUiD,MAAM,kCAClB"}
|
package/zod/dist/zod.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as n}from"react-hook-form";function o(){return o=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},o.apply(null,arguments)}function t(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function s(r,e){for(var o=
|
|
1
|
+
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as n}from"react-hook-form";function o(){return o=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},o.apply(null,arguments)}function t(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function s(r,e){for(var o=Object.create(null);r.length;){var t=r[0],s=t.code,i=t.message,u=t.path.join(".");if(!o[u])if("unionErrors"in t){var a,c,l=t.unionErrors.reduce(function(r,e){return e.errors.length<r.errors.length?e:r}).errors[0];o[u]={message:null!=(a=null==l?void 0:l.message)?a:i,type:null!=(c=null==l?void 0:l.code)?c:s}}else o[u]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var f=o[u].types,d=f&&f[t.code];o[u]=n(u,e,o,s,d?[].concat(d,t.message):t.message)}r.shift()}return o}function i(r,e){for(var t=Object.create(null),s=function(){var s=r[0],i=s.code,u=s.message,a=s.path.join(".");if(!t[a])if("invalid_union"===s.code&&s.errors.length>0){var c,l,f=s.errors.reduce(function(r,e){return e.length<r.length?e:r})[0];t[a]={message:null!=(c=null==f?void 0:f.message)?c:u,type:null!=(l=null==f?void 0:f.code)?l:i}}else t[a]={message:u,type:i};if("invalid_union"===s.code&&s.errors.forEach(function(e){return e.forEach(function(e){return r.push(o({},e,{path:[].concat(s.path,e.path)}))})}),e){var d=t[a].types,h=d&&d[s.code];t[a]=n(a,e,t,i,h?[].concat(h,s.message):s.message)}r.shift()};r.length;)s();return t}function u(n,o,u){if(void 0===u&&(u={}),function(r){return"_zod"in r&&"object"==typeof r._zod}(n))return function(s,a,c){try{return Promise.resolve(t(function(){function e(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},s):e}}var t=n;return"sync"===u.mode?e(t.parse(s,o)):Promise.resolve(t.parseAsync(s,o)).then(e)},function(r){if(function(r){var e;return!(null==r||null==(e=r._zod)||null==(e=e.traits)||!e.has("$ZodError"))}(r))return{values:{},errors:e(i(r.issues,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return"_def"in r&&"object"==typeof r._def}(n))return function(i,a,c){try{return Promise.resolve(t(function(){return Promise.resolve(n["sync"===u.mode?"parse":"parseAsync"](i,o)).then(function(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},i):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return{values:{},errors:e(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}export{u as zodResolver};
|
|
2
2
|
//# sourceMappingURL=zod.module.js.map
|
package/zod/dist/zod.modern.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as o}from"react-hook-form";function s(){return s=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var s in o)({}).hasOwnProperty.call(o,s)&&(r[s]=o[s])}return r},s.apply(null,arguments)}function n(r,e){const s=
|
|
1
|
+
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as o}from"react-hook-form";function s(){return s=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var s in o)({}).hasOwnProperty.call(o,s)&&(r[s]=o[s])}return r},s.apply(null,arguments)}function n(r,e){const s=Object.create(null);for(;r.length;){const a=r[0],{code:i,message:l,path:c}=a,u=c.join(".");if(!s[u])if("unionErrors"in a){var n,t;const r=a.unionErrors.reduce((r,e)=>e.errors.length<r.errors.length?e:r).errors[0];s[u]={message:null!=(n=null==r?void 0:r.message)?n:l,type:null!=(t=null==r?void 0:r.code)?t:i}}else s[u]={message:l,type:i};if("unionErrors"in a&&a.unionErrors.forEach(e=>e.errors.forEach(e=>r.push(e))),e){const r=s[u].types,n=r&&r[a.code];s[u]=o(u,e,s,i,n?[].concat(n,a.message):a.message)}r.shift()}return s}function t(r,e){const n=Object.create(null);for(;r.length;){const i=r[0],{code:l,message:c,path:u}=i,d=u.join(".");if(!n[d])if("invalid_union"===i.code&&i.errors.length>0){var t,a;const r=i.errors.reduce((r,e)=>e.length<r.length?e:r)[0];n[d]={message:null!=(t=null==r?void 0:r.message)?t:c,type:null!=(a=null==r?void 0:r.code)?a:l}}else n[d]={message:c,type:l};if("invalid_union"===i.code&&i.errors.forEach(e=>e.forEach(e=>r.push(s({},e,{path:[...i.path,...e.path]})))),e){const r=n[d].types,s=r&&r[i.code];n[d]=o(d,e,n,l,s?[].concat(s,i.message):i.message)}r.shift()}return n}function a(o,s,a={}){if((r=>"_zod"in r&&"object"==typeof r._zod)(o))return async(n,i,l)=>{try{const e=o,t="sync"===a.mode?e.parse(n,s):await e.parseAsync(n,s);return l.shouldUseNativeValidation&&r({},l),{errors:{},values:a.raw?Object.assign({},n):t}}catch(r){if((r=>{var e;return!(null==r||null==(e=r._zod)||null==(e=e.traits)||!e.has("$ZodError"))})(r))return{values:{},errors:e(t(r.issues,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)};throw r}};if((r=>"_def"in r&&"object"==typeof r._def)(o))return async(t,i,l)=>{try{const e=await o["sync"===a.mode?"parse":"parseAsync"](t,s);return l.shouldUseNativeValidation&&r({},l),{errors:{},values:a.raw?Object.assign({},t):e}}catch(r){if((r=>Array.isArray(null==r?void 0:r.issues))(r))return{values:{},errors:e(n(r.errors,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)};throw r}};throw new Error("Invalid input: not a Zod schema")}export{a as zodResolver};
|
|
2
2
|
//# sourceMappingURL=zod.modern.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod.modern.mjs","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","path","_path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_unionError$message2","_unionError$code2","branch","_extends","zodResolver","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","classicSchema","data","mode","parse","parseAsync","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","_def","isZod3Schema","async","Array","isArray","isZod3Error","Error"],"mappings":"sVAuCA,SAASA,EACPC,EACAC,GAEA,MAAMC,EAAqC,CAAA,EAC3C,KAAOF,EAAUG,QAAU,CACzB,MAAMC,EAAQJ,EAAU,IAClBK,KAAEA,EAAIC,QAAEA,EAAOC,KAAEA,GAASH,EAC1BI,EAAQD,EAAKE,KAAK,KAExB,IAAKP,EAAOM,GACV,GAAI,gBAAiBJ,EAAO,CAAAM,IAAAA,EAAAC,EAI1B,MAOMC,EAPoBR,EAAMS,YAAYC,OAC1C,CAACC,EAASC,IACRA,EAAQd,OAAOC,OAASY,EAAQb,OAAOC,OAASa,EAAUD,GAKzBb,OAAO,GAE5CA,EAAOM,GAAS,CACdF,QAA4B,OAArBI,EAAY,MAAVE,OAAU,EAAVA,EAAYN,SAAOI,EAAIJ,EAChCW,KAAsBN,OAAlBA,EAAEC,MAAAA,OAAAA,EAAAA,EAAYP,MAAIM,EAAIN,EAE9B,MACEH,EAAOM,GAAS,CAAEF,UAASW,KAAMZ,GAUrC,GANI,gBAAiBD,GACnBA,EAAMS,YAAYK,QAASN,GACzBA,EAAWV,OAAOgB,QAASC,GAAMnB,EAAUoB,KAAKD,KAIhDlB,EAA0B,CAC5B,MAAMoB,EAAQnB,EAAOM,GAAOa,MACtBC,EAAWD,GAASA,EAAMjB,EAAMC,MAEtCH,EAAOM,GAASe,EACdf,EACAP,EACAC,EACAG,EACAiB,EACK,GAAgBE,OAAOF,EAAsBlB,EAAME,SACpDF,EAAME,QAEd,CAEAN,EAAUyB,OACZ,CAEA,OAAOvB,CACT,CAEA,SAASwB,EACP1B,EACAC,GAEA,MAAMC,EAAqC,CAAA,EAE3C,KAAOF,EAAUG,QAAU,CACzB,MAAMC,EAAQJ,EAAU,IAClBK,KAAEA,EAAIC,QAAEA,EAAO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AAQH,EAAgBa,IAAMC,OAAOC,OAAO,CAAA,EAAIZ,GAAUI,EAE9D,CAAE,MAAOrC,GACP,GAvSaA,KAAqC8C,IAAAA,EAMxD,QAAc,MAAL9C,GAAW,OAAN8C,EAAL9C,EAAO+B,OAAY,OAARe,EAAXA,EAAaC,UAAbD,EAAqBE,IAAI,aACpC,EAgSYC,CAAYjD,GACd,MAAO,CACLiC,OAAQ,CAAE,EACVnC,OAAQoD,EACN5B,EACEtB,EAAMmD,QACLhB,EAAQM,2BACkB,QAAzBN,EAAQiB,cAEZjB,IAKN,MAAMnC,CACR,GAIJ,GAjUoB4B,IAKb,SAAUA,GAAiC,iBAAhBA,EAAOyB,KA4TrCC,CAAa1B,GACf,OAAO2B,MAAOtB,EAAeC,EAAGC,KAC9B,IACE,MAAME,QAAaT,EACQ,SAAzBE,EAAgBQ,KAAkB,QAAU,cAC5CL,EAAQJ,GAKV,OAHAM,EAAQM,2BACNC,EAAuB,CAAA,EAAIP,GAEtB,CACLrC,OAAQ,CAAE,EACVmC,OAAQH,EAAgBa,IAAMC,OAAOC,OAAO,CAAE,EAAEZ,GAAUI,EAE9D,CAAE,MAAOrC,GACP,GAnVaA,IACZwD,MAAMC,QAAa,MAALzD,OAAK,EAALA,EAAOmD,QAkVlBO,CAAY1D,GACd,MAAO,CACLiC,OAAQ,CAAA,EACRnC,OAAQoD,EACNvD,EACEK,EAAMF,QACLqC,EAAQM,2BACkB,QAAzBN,EAAQiB,cAEZjB,IAKN,MAAMnC,CACR,GAIJ,MAAU,IAAA2D,MAAM,kCAClB"}
|
|
1
|
+
{"version":3,"file":"zod.modern.mjs","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`, `__proto__`) when a field is\n // named after one of them — a plain `{}` would make `!errors[_path]`\n // truthy-skip those paths and silently drop their errors.\n const errors: Record<string, FieldError> = Object.create(null);\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // See the matching comment in `parseZod3Issues` above.\n const errors: Record<string, FieldError> = Object.create(null);\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","Object","create","length","error","code","message","path","_path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_unionError$message2","_unionError$code2","branch","_extends","zodResolver","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","async","values","_","options","classicSchema","data","mode","parse","parseAsync","shouldUseNativeValidation","validateFieldsNatively","raw","assign","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"sVAuCA,SAASA,EACPC,EACAC,GAMA,MAAMC,EAAqCC,OAAOC,OAAO,MACzD,KAAOJ,EAAUK,QAAU,CACzB,MAAMC,EAAQN,EAAU,IAClBO,KAAEA,EAAIC,QAAEA,EAAOC,KAAEA,GAASH,EAC1BI,EAAQD,EAAKE,KAAK,KAExB,IAAKT,EAAOQ,GACV,GAAI,gBAAiBJ,EAAO,CAAAM,IAAAA,EAAAC,EAI1B,MAOMC,EAPoBR,EAAMS,YAAYC,OAC1C,CAACC,EAASC,IACRA,EAAQhB,OAAOG,OAASY,EAAQf,OAAOG,OAASa,EAAUD,GAKzBf,OAAO,GAE5CA,EAAOQ,GAAS,CACdF,QAA4BI,OAArBA,EAAY,MAAVE,OAAU,EAAVA,EAAYN,SAAOI,EAAIJ,EAChCW,KAAsBN,OAAlBA,EAAEC,MAAAA,OAAAA,EAAAA,EAAYP,MAAIM,EAAIN,EAE9B,MACEL,EAAOQ,GAAS,CAAEF,UAASW,KAAMZ,GAUrC,GANI,gBAAiBD,GACnBA,EAAMS,YAAYK,QAASN,GACzBA,EAAWZ,OAAOkB,QAASC,GAAMrB,EAAUsB,KAAKD,KAIhDpB,EAA0B,CAC5B,MAAMsB,EAAQrB,EAAOQ,GAAOa,MACtBC,EAAWD,GAASA,EAAMjB,EAAMC,MAEtCL,EAAOQ,GAASe,EACdf,EACAT,EACAC,EACA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AAA0D,MAAM,kCAClB"}
|
package/zod/dist/zod.module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as n}from"react-hook-form";function o(){return o=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},o.apply(null,arguments)}function t(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function s(r,e){for(var o=
|
|
1
|
+
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as n}from"react-hook-form";function o(){return o=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(r[o]=n[o])}return r},o.apply(null,arguments)}function t(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function s(r,e){for(var o=Object.create(null);r.length;){var t=r[0],s=t.code,i=t.message,u=t.path.join(".");if(!o[u])if("unionErrors"in t){var a,c,l=t.unionErrors.reduce(function(r,e){return e.errors.length<r.errors.length?e:r}).errors[0];o[u]={message:null!=(a=null==l?void 0:l.message)?a:i,type:null!=(c=null==l?void 0:l.code)?c:s}}else o[u]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var f=o[u].types,d=f&&f[t.code];o[u]=n(u,e,o,s,d?[].concat(d,t.message):t.message)}r.shift()}return o}function i(r,e){for(var t=Object.create(null),s=function(){var s=r[0],i=s.code,u=s.message,a=s.path.join(".");if(!t[a])if("invalid_union"===s.code&&s.errors.length>0){var c,l,f=s.errors.reduce(function(r,e){return e.length<r.length?e:r})[0];t[a]={message:null!=(c=null==f?void 0:f.message)?c:u,type:null!=(l=null==f?void 0:f.code)?l:i}}else t[a]={message:u,type:i};if("invalid_union"===s.code&&s.errors.forEach(function(e){return e.forEach(function(e){return r.push(o({},e,{path:[].concat(s.path,e.path)}))})}),e){var d=t[a].types,h=d&&d[s.code];t[a]=n(a,e,t,i,h?[].concat(h,s.message):s.message)}r.shift()};r.length;)s();return t}function u(n,o,u){if(void 0===u&&(u={}),function(r){return"_zod"in r&&"object"==typeof r._zod}(n))return function(s,a,c){try{return Promise.resolve(t(function(){function e(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},s):e}}var t=n;return"sync"===u.mode?e(t.parse(s,o)):Promise.resolve(t.parseAsync(s,o)).then(e)},function(r){if(function(r){var e;return!(null==r||null==(e=r._zod)||null==(e=e.traits)||!e.has("$ZodError"))}(r))return{values:{},errors:e(i(r.issues,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return"_def"in r&&"object"==typeof r._def}(n))return function(i,a,c){try{return Promise.resolve(t(function(){return Promise.resolve(n["sync"===u.mode?"parse":"parseAsync"](i,o)).then(function(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},i):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return{values:{},errors:e(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}export{u as zodResolver};
|
|
2
2
|
//# sourceMappingURL=zod.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod.module.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","zodResolver","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","classicSchema","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"6aAuCA,SAASA,EACPC,EACAC,GAGA,IADA,IAAMC,EAAqC,CAAE,EACtCF,EAAUG,QAAU,CACzB,IAAMC,EAAQJ,EAAU,GAChBK,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKP,EAAOK,GACV,GAAI,gBAAiBH,EAAO,KAAAM,EAAAC,EAWpBC,EAPoBR,EAAMS,YAAYC,OAC1C,SAACC,EAASC,GACR,OAAAA,EAAQd,OAAOC,OAASY,EAAQb,OAAOC,OAASa,EAAUD,CAAO,GAKhCb,OAAO,GAE5CA,EAAOK,GAAS,CACdD,QAA4B,OAArBI,EAAEE,MAAAA,OAAAA,EAAAA,EAAYN,SAAOI,EAAIJ,EAChCW,KAAsBN,OAAlBA,EAAEC,MAAAA,OAAAA,EAAAA,EAAYP,MAAIM,EAAIN,EAE9B,MACEH,EAAOK,GAAS,CAAED,QAAAA,EAASW,KAAMZ,GAUrC,GANI,gBAAiBD,GACnBA,EAAMS,YAAYK,QAAQ,SAACN,GACzB,OAAAA,EAAWV,OAAOgB,QAAQ,SAACC,GAAC,OAAKnB,EAAUoB,KAAKD,EAAE,EAAC,GAInDlB,EAA0B,CAC5B,IAAMoB,EAAQnB,EAAOK,GAAOc,MACtBC,EAAWD,GAASA,EAAMjB,EAAMC,MAEtCH,EAAOK,GAASgB,EACdhB,EACAN,EACAC,EACAG,EACAiB,EACK,GAAgBE,OAAOF,EAAsBlB,EAAME,SACpDF,EAAME,QAEd,CAEAN,EAAUyB,OACZ,CAEA,OAAOvB,CACT,CAEA,SAASwB,EACP1B,EACAC,GAIA,IAFA,IAAMC,EAAqC,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,EAAAA,EAAOyD,OAC9B,CAiVYO,CAAYhE,GACd,MAAO,CACLkC,OAAQ,CAAE,EACVpC,OAAQ0D,EACN7D,EACEK,EAAMF,QACLsC,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMpC,CACR,GACF,CAAC,MAAAe,GAAA,OAAAsB,QAAAsB,OAAA5C,EACH,CAAA,EAEA,MAAM,IAAIkD,MAAM,kCAClB"}
|
|
1
|
+
{"version":3,"file":"zod.module.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`, `__proto__`) when a field is\n // named after one of them — a plain `{}` would make `!errors[_path]`\n // truthy-skip those paths and silently drop their errors.\n const errors: Record<string, FieldError> = Object.create(null);\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // See the matching comment in `parseZod3Issues` above.\n const errors: Record<string, FieldError> = Object.create(null);\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","Object","create","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","zodResolver","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","assign","classicSchema","_temp","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"6aAuCA,SAASA,EACPC,EACAC,GAOA,IADA,IAAMC,EAAqCC,OAAOC,OAAO,MAClDJ,EAAUK,QAAU,CACzB,IAAMC,EAAQN,EAAU,GAChBO,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKT,EAAOO,GACV,GAAI,gBAAiBH,EAAO,CAAAM,IAAAA,EAAAC,EAWpBC,EAPoBR,EAAMS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oD,EAALpD,EAAOgC,OAAPoB,OAAWA,EAAXA,EAAaC,UAAbD,EAAqBE,IAAI,aACpC,CAqSYC,CAAYvD,GACd,MAAO,CACLkC,OAAQ,CAAE,EACVtC,OAAQ4D,EACNlC,EACEtB,EAAMyD,QACLrB,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMpC,CACR,GACF,CAAC,MAAAe,GAAA,OAAAsB,QAAAsB,OAAA5C,EACH,CAAA,EAEA,GAtUmB,SAACc,GAKpB,MAAO,SAAUA,GAAiC,iBAAhBA,EAAO+B,IAC3C,CAgUMC,CAAahC,GACf,OAAcK,SAAAA,EAAeC,EAAGC,GAAO,IAAIC,OAAAA,QAAAC,QAAAC,aACrCF,OAAAA,QAAAC,QACiBT,EACQ,SAAzBE,EAAgBiB,KAAkB,QAAU,cAC5Cd,EAAQJ,IAAcqB,KAFlBV,SAAAA,GAON,OAHAL,EAAQM,2BACNC,EAAuB,GAAIP,GAEtB,CACLxC,OAAQ,CAAA,EACRsC,OAAQH,EAAgBa,IAAM/C,OAAOgD,OAAO,CAAA,EAAIX,GAAUO,EAChB,EAC9C,EAASzC,SAAAA,GACP,GAxVY,SAACA,GACnB,OAAO8D,MAAMC,QAAa,MAAL/D,OAAK,EAALA,EAAOyD,OAC9B,CAsVYO,CAAYhE,GACd,MAAO,CACLkC,OAAQ,CAAE,EACVtC,OAAQ4D,EACN/D,EACEO,EAAMJ,QACLwC,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMpC,CACR,GACF,CAAC,MAAAe,GAAAsB,OAAAA,QAAAsB,OAAA5C,EAAA,CAAA,EAGH,UAAUkD,MAAM,kCAClB"}
|
package/zod/dist/zod.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(r
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","react-hook-form"],r):r((e||self).hookformResolversZod={},e.hookformResolvers,e.ReactHookForm)}(this,function(e,r,n){function o(){return o=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},o.apply(null,arguments)}function t(e,r){try{var n=e()}catch(e){return r(e)}return n&&n.then?n.then(void 0,r):n}function s(e,r){for(var o=Object.create(null);e.length;){var t=e[0],s=t.code,i=t.message,a=t.path.join(".");if(!o[a])if("unionErrors"in t){var u,l,c=t.unionErrors.reduce(function(e,r){return r.errors.length<e.errors.length?r:e}).errors[0];o[a]={message:null!=(u=null==c?void 0:c.message)?u:i,type:null!=(l=null==c?void 0:c.code)?l:s}}else o[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),r){var f=o[a].types,d=f&&f[t.code];o[a]=n.appendErrors(a,r,o,s,d?[].concat(d,t.message):t.message)}e.shift()}return o}function i(e,r){for(var t=Object.create(null),s=function(){var s=e[0],i=s.code,a=s.message,u=s.path.join(".");if(!t[u])if("invalid_union"===s.code&&s.errors.length>0){var l,c,f=s.errors.reduce(function(e,r){return r.length<e.length?r:e})[0];t[u]={message:null!=(l=null==f?void 0:f.message)?l:a,type:null!=(c=null==f?void 0:f.code)?c:i}}else t[u]={message:a,type:i};if("invalid_union"===s.code&&s.errors.forEach(function(r){return r.forEach(function(r){return e.push(o({},r,{path:[].concat(s.path,r.path)}))})}),r){var d=t[u].types,h=d&&d[s.code];t[u]=n.appendErrors(u,r,t,i,h?[].concat(h,s.message):s.message)}e.shift()};e.length;)s();return t}e.zodResolver=function(e,n,o){if(void 0===o&&(o={}),function(e){return"_zod"in e&&"object"==typeof e._zod}(e))return function(s,a,u){try{return Promise.resolve(t(function(){function t(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:o.raw?Object.assign({},s):e}}var i=e;return"sync"===o.mode?t(i.parse(s,n)):Promise.resolve(i.parseAsync(s,n)).then(t)},function(e){if(function(e){var r;return!(null==e||null==(r=e._zod)||null==(r=r.traits)||!r.has("$ZodError"))}(e))return{values:{},errors:r.toNestErrors(i(e.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(e){return Promise.reject(e)}};if(function(e){return"_def"in e&&"object"==typeof e._def}(e))return function(i,a,u){try{return Promise.resolve(t(function(){return Promise.resolve(e["sync"===o.mode?"parse":"parseAsync"](i,n)).then(function(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:o.raw?Object.assign({},i):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:r.toNestErrors(s(e.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(e){return Promise.reject(e)}};throw new Error("Invalid input: not a Zod schema")}});
|
|
2
2
|
//# sourceMappingURL=zod.umd.js.map
|
package/zod/dist/zod.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","classicSchema","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"uqBAuCA,SAASA,EACPC,EACAC,GAGA,IADA,IAAMC,EAAqC,CAAE,EACtCF,EAAUG,QAAU,C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AAM,IAAIiD,MAAM,kCAClB"}
|
|
1
|
+
{"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\n// Type-only: these subpaths don't exist before zod@3.25.0, so importing them\n// as values would break resolution for anyone on an older zod 3.x. `import\n// type` is fully erased at build time, so the compiled output never\n// references these subpaths at runtime — see `isZod4Error` below for how the\n// one runtime check that used to need `z4.$ZodError` avoids that now.\nimport type * as z3 from 'zod/v3';\nimport type * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n // Deliberately doesn't require `typeName` in `_def` — dynamically selected\n // schemas typed via the generic `z.ZodType<Output>` annotation (rather than\n // a concrete subclass like `ZodObject`) don't statically expose `typeName`,\n // even though they're genuine Zod 3 schema instances at runtime.\n return '_def' in schema && typeof schema._def === 'object';\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // Replicates zod4's own `$ZodError`/`Symbol.hasInstance` check\n // (`inst?._zod?.traits?.has(name)`, see zod's `$constructor` in\n // `v4/core/core.ts`) by hand rather than importing `$ZodError` as a value,\n // since that import only exists in zod@3.25.0+ (see the `import type` note\n // above).\n return !!error?._zod?.traits?.has('$ZodError');\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // A null-prototype object avoids false-positive hits from inherited\n // members (e.g. `toString`, `constructor`, `__proto__`) when a field is\n // named after one of them — a plain `{}` would make `!errors[_path]`\n // truthy-skip those paths and silently drop their errors.\n const errors: Record<string, FieldError> = Object.create(null);\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestUnionError = error.unionErrors.reduce(\n (closest, current) =>\n current.errors.length < closest.errors.length ? current : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // member somehow has no issues of its own (shouldn't happen, but\n // avoids ever throwing on an unexpected/malformed union shape).\n const unionError = closestUnionError.errors[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n // See the matching comment in `parseZod3Issues` above.\n const errors: Record<string, FieldError> = Object.create(null);\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union' && error.errors.length > 0) {\n // Surface the error from whichever union member came closest to\n // matching (fewest issues), rather than always the first member —\n // the first member isn't necessarily the one the input was meant for.\n const closestBranch = error.errors.reduce((closest, branch) =>\n branch.length < closest.length ? branch : closest,\n );\n // Fall back to the union issue's own message/code if the closest\n // branch somehow has no issues of its own (shouldn't happen — a\n // 0-issue branch means that branch matched — but this guarantees we\n // never throw on an unexpected/malformed union shape, e.g. a \"no\n // matching discriminator\" issue nested in a way we haven't seen).\n const unionError = closestBranch[0];\n\n errors[_path] = {\n message: unionError?.message ?? message,\n type: unionError?.code ?? code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) =>\n zodErrors.push({ ...e, path: [...error.path, ...e.path] }),\n ),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: object;\n}\n\n// minimal interface to avoid assignability issues between zod v4 patch/minor\n// releases, which brand the full `$ZodType` shape with an exact version literal\n// (e.g. `_zod.version.minor`)\ninterface Zod4Type<Output = unknown, Input = unknown> {\n _zod: {\n output: Output;\n input: Input;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends Zod4Type<Output, Input> = Zod4Type<Output, Input>,\n>(\n schema: Zod4Type<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n // Zod 4 is checked first: its `_zod` marker is unambiguous, whereas the\n // Zod 3 check below only requires an object-shaped `_def` (to support\n // dynamically-selected schemas typed via the generic `z.ZodType<Output>`\n // annotation, see `isZod3Schema`) — and Zod 4 schemas also have an\n // object-shaped `_def`, so they'd otherwise be misdetected as Zod 3.\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n // Call the schema's own bound `parse`/`parseAsync` method rather\n // than the standalone `z4.parse`/`z4.parseAsync` functions. Those\n // standalone functions read from this module's own imported\n // `zod/v4/core`, which — under bundlers that can resolve `zod` and\n // `zod/v4/core` to two distinct module instances (e.g. Metro with\n // package-exports resolution enabled) — may not be the same zod\n // instance the schema was created with, silently dropping any\n // global config (`z.config()`) or locale the app configured on its\n // own zod instance. The schema's own method is always bound to\n // whichever zod instance actually created it.\n const classicSchema = schema as unknown as {\n parse: (values: unknown, schemaOptions: unknown) => unknown;\n parseAsync: (\n values: unknown,\n schemaOptions: unknown,\n ) => Promise<unknown>;\n };\n const data: any =\n resolverOptions.mode === 'sync'\n ? classicSchema.parse(values, schemaOptions)\n : await classicSchema.parseAsync(values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","Object","create","length","error","code","message","_path","path","join","_unionError$message","_unionError$code","unionError","unionErrors","reduce","closest","current","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","_loop","_unionError$message2","_unionError$code2","branch","_extends","schema","schemaOptions","resolverOptions","_zod","isZod4Schema","values","_","options","Promise","resolve","_catch","_temp2","data","shouldUseNativeValidation","validateFieldsNatively","raw","assign","classicSchema","_temp","mode","parse","parseAsync","then","_error$_zod","traits","has","isZod4Error","toNestErrors","issues","criteriaMode","reject","_def","isZod3Schema","Array","isArray","isZod3Error","Error"],"mappings":"uqBAuCA,SAASA,EACPC,EACAC,GAOA,IADA,IAAMC,EAAqCC,OAAOC,OAAO,MAClDJ,EAAUK,QAAU,CACzB,IAAMC,EAAQN,EAAU,GAChBO,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKT,EAAOO,GACV,GAAI,gBAAiBH,EAAO,CAAAM,IAAAA,EAAAC,EAWpBC,EAPoBR,EAAMS,YAAYC,OAC1C,SAACC,EAASC,GACR,OAAAA,EAAQhB,OAAOG,OAASY,EAAQf,OAAOG,OAASa,EAAUD,CAAO,GAKhCf,OAAO,GAE5CA,EAAOO,GAAS,CACdD,QAA4BI,OAArBA,EAAY,MAAVE,OAAU,EAAVA,EAAYN,SAAOI,EAAIJ,EAChCW,KAAsB,OAAlBN,EAAY,MAAVC,OAAU,EAA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,GACF,CAAC,MAAAe,GAAA,OAAAqB,QAAAsB,OAAA3C,EACH,CAAA,EAEA,GAtUmB,SAACa,GAKpB,MAAO,SAAUA,GAAiC,iBAAhBA,EAAO+B,IAC3C,CAgUMC,CAAahC,GACf,OAAcK,SAAAA,EAAeC,EAAGC,GAAO,IAAIC,OAAAA,QAAAC,QAAAC,aACrCF,OAAAA,QAAAC,QACiBT,EACQ,SAAzBE,EAAgBiB,KAAkB,QAAU,cAC5Cd,EAAQJ,IAAcqB,KAFlBV,SAAAA,GAON,OAHAL,EAAQM,2BACNC,EAAsBA,uBAAC,GAAIP,GAEtB,CACLvC,OAAQ,CAAA,EACRqC,OAAQH,EAAgBa,IAAM9C,OAAO+C,OAAO,CAAA,EAAIX,GAAUO,EAChB,EAC9C,EAASxC,SAAAA,GACP,GAxVY,SAACA,GACnB,OAAO6D,MAAMC,QAAa,MAAL9D,OAAK,EAALA,EAAOwD,OAC9B,CAsVYO,CAAY/D,GACd,MAAO,CACLiC,OAAQ,CAAE,EACVrC,OAAQ2D,EAAYA,aAClB9D,EACEO,EAAMJ,QACLuC,EAAQM,2BACkB,QAAzBN,EAAQsB,cAEZtB,IAKN,MAAMnC,CACR,GACF,CAAC,MAAAe,GAAAqB,OAAAA,QAAAsB,OAAA3C,EAAA,CAAA,EAGH,UAAUiD,MAAM,kCAClB"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { z as z3 } from 'zod/v3';
|
|
2
|
+
import { z as z4 } from 'zod/v4';
|
|
3
|
+
import { zodResolver } from '..';
|
|
4
|
+
|
|
5
|
+
const shouldUseNativeValidation = false;
|
|
6
|
+
|
|
7
|
+
describe.each([
|
|
8
|
+
{ version: 'v3', z: z3 as unknown as typeof z4 },
|
|
9
|
+
{ version: 'v4', z: z4 },
|
|
10
|
+
])('zodResolver special path names ($version)', ({ z }) => {
|
|
11
|
+
// These names are inherited (truthy) members of `Object.prototype`, so a
|
|
12
|
+
// resolver that tracks seen paths via a plain `{}` map and `!errors[path]`
|
|
13
|
+
// would treat them as "already recorded" and drop the real error.
|
|
14
|
+
it.each(['toString', 'hasOwnProperty'])(
|
|
15
|
+
'reports a validation error for a field named "%s"',
|
|
16
|
+
async (name) => {
|
|
17
|
+
const schema = z.object({ [name]: z.string().min(1) });
|
|
18
|
+
|
|
19
|
+
const direct = schema.safeParse({ [name]: '' });
|
|
20
|
+
expect(direct.success).toBe(false);
|
|
21
|
+
|
|
22
|
+
const result = await zodResolver(schema)(
|
|
23
|
+
{ [name]: '' } as any,
|
|
24
|
+
undefined,
|
|
25
|
+
{ fields: {}, shouldUseNativeValidation } as any,
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
expect(result.errors[name]).toMatchObject({ type: 'too_small' });
|
|
29
|
+
},
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
// `__proto__`, `constructor`, and `prototype` are also inherited/special
|
|
33
|
+
// members, but even once the resolver stops mis-tracking them internally,
|
|
34
|
+
// react-hook-form's own `set`/`get` helpers refuse to write those path
|
|
35
|
+
// segments at all (they hard-code them as a protected-path list to guard
|
|
36
|
+
// against prototype pollution). So these remain dropped end-to-end — that
|
|
37
|
+
// part of the behavior lives in react-hook-form, not in this resolver.
|
|
38
|
+
it.each(['__proto__', 'constructor', 'prototype'])(
|
|
39
|
+
'still drops a field named "%s" (react-hook-form protected path)',
|
|
40
|
+
async (name) => {
|
|
41
|
+
const schema = z.object({ [name]: z.string().min(1) });
|
|
42
|
+
|
|
43
|
+
const direct = schema.safeParse({ [name]: '' });
|
|
44
|
+
expect(direct.success).toBe(false);
|
|
45
|
+
|
|
46
|
+
const result = await zodResolver(schema)(
|
|
47
|
+
{ [name]: '' } as any,
|
|
48
|
+
undefined,
|
|
49
|
+
{ fields: {}, shouldUseNativeValidation } as any,
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
expect(result.errors).toEqual({});
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
});
|
package/zod/src/zod.ts
CHANGED
|
@@ -41,7 +41,11 @@ function parseZod3Issues(
|
|
|
41
41
|
zodErrors: z3.ZodIssue[],
|
|
42
42
|
validateAllFieldCriteria: boolean,
|
|
43
43
|
) {
|
|
44
|
-
|
|
44
|
+
// A null-prototype object avoids false-positive hits from inherited
|
|
45
|
+
// members (e.g. `toString`, `constructor`, `__proto__`) when a field is
|
|
46
|
+
// named after one of them — a plain `{}` would make `!errors[_path]`
|
|
47
|
+
// truthy-skip those paths and silently drop their errors.
|
|
48
|
+
const errors: Record<string, FieldError> = Object.create(null);
|
|
45
49
|
for (; zodErrors.length; ) {
|
|
46
50
|
const error = zodErrors[0];
|
|
47
51
|
const { code, message, path } = error;
|
|
@@ -101,7 +105,8 @@ function parseZod4Issues(
|
|
|
101
105
|
zodErrors: z4.$ZodIssue[],
|
|
102
106
|
validateAllFieldCriteria: boolean,
|
|
103
107
|
) {
|
|
104
|
-
|
|
108
|
+
// See the matching comment in `parseZod3Issues` above.
|
|
109
|
+
const errors: Record<string, FieldError> = Object.create(null);
|
|
105
110
|
// const _zodErrors = zodErrors as z4.$ZodISsue; //
|
|
106
111
|
for (; zodErrors.length; ) {
|
|
107
112
|
const error = zodErrors[0];
|