|
| 1 | +import { type $ZodObject, type $ZodErrorMap, safeParseAsync, toJSONSchema } from 'zod/v4/core'; |
| 2 | +import type { JSONSchema7 } from 'json-schema'; |
| 3 | +import { |
| 4 | + type AdapterOptions, |
| 5 | + type ValidationAdapter, |
| 6 | + type Infer, |
| 7 | + type InferIn, |
| 8 | + createAdapter, |
| 9 | + type ValidationResult, |
| 10 | + type ClientValidationAdapter |
| 11 | +} from './adapters.js'; |
| 12 | +import { memoize } from '$lib/memoize.js'; |
| 13 | + |
| 14 | +type Options = NonNullable<Parameters<typeof toJSONSchema>[1]>; |
| 15 | + |
| 16 | +type ZodObject = $ZodObject; |
| 17 | + |
| 18 | +const defaultJSONSchemaOptions = { |
| 19 | + unrepresentable: 'any', |
| 20 | + override: (ctx) => { |
| 21 | + const def = ctx.zodSchema._zod.def; |
| 22 | + if (def.type === 'date') { |
| 23 | + ctx.jsonSchema.type = 'string'; |
| 24 | + ctx.jsonSchema.format = 'date-time'; |
| 25 | + } |
| 26 | + } |
| 27 | +} satisfies Options; |
| 28 | + |
| 29 | +/* @__NO_SIDE_EFFECTS__ */ |
| 30 | +export const zodToJSONSchema = <S extends ZodObject>(schema: S, options?: Options) => { |
| 31 | + return toJSONSchema(schema, { ...defaultJSONSchemaOptions, ...options }) as JSONSchema7; |
| 32 | +}; |
| 33 | + |
| 34 | +async function validate<T extends ZodObject>( |
| 35 | + schema: T, |
| 36 | + data: unknown, |
| 37 | + error: $ZodErrorMap | undefined |
| 38 | +): Promise<ValidationResult<Infer<T, 'zod4'>>> { |
| 39 | + const result = await safeParseAsync(schema, data, { error }); |
| 40 | + if (result.success) { |
| 41 | + return { |
| 42 | + data: result.data as Infer<T, 'zod4'>, |
| 43 | + success: true |
| 44 | + }; |
| 45 | + } |
| 46 | + |
| 47 | + return { |
| 48 | + issues: result.error.issues.map(({ message, path }) => ({ message, path })), |
| 49 | + success: false |
| 50 | + }; |
| 51 | +} |
| 52 | + |
| 53 | +function _zod4<T extends ZodObject>( |
| 54 | + schema: T, |
| 55 | + options?: AdapterOptions<Infer<T, 'zod4'>> & { error?: $ZodErrorMap; config?: Options } |
| 56 | +): ValidationAdapter<Infer<T, 'zod4'>, InferIn<T, 'zod4'>> { |
| 57 | + return createAdapter({ |
| 58 | + superFormValidationLibrary: 'zod4', |
| 59 | + validate: async (data) => { |
| 60 | + return validate(schema, data, options?.error); |
| 61 | + }, |
| 62 | + jsonSchema: options?.jsonSchema ?? zodToJSONSchema(schema, options?.config), |
| 63 | + defaults: options?.defaults |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +function _zod4Client<T extends ZodObject>( |
| 68 | + schema: T, |
| 69 | + options?: { error?: $ZodErrorMap } |
| 70 | +): ClientValidationAdapter<Infer<T, 'zod4'>, InferIn<T, 'zod4'>> { |
| 71 | + return { |
| 72 | + superFormValidationLibrary: 'zod4', |
| 73 | + validate: async (data) => validate(schema, data, options?.error) |
| 74 | + }; |
| 75 | +} |
| 76 | + |
| 77 | +export const zod4 = /* @__PURE__ */ memoize(_zod4); |
| 78 | +export const zod4Client = /* @__PURE__ */ memoize(_zod4Client); |
0 commit comments