Line data Source code
1 : import type { TypedSchema, TypedSchemaError } from 'vee-validate'
2 : import { toValue } from 'vue'
3 : import type { MaybeRefOrGetter } from 'vue'
4 : import type { z } from 'zod'
5 :
6 : type IssuePath = readonly PropertyKey[]
7 :
8 105 : function toFormPath(path: IssuePath): string {
9 105 : return path.reduce<string>((formPath, segment, index) => {
10 105 : if (typeof segment === 'number') return `${formPath}[${segment}]`
11 105 : return index === 0 ? String(segment) : `${formPath}.${String(segment)}`
12 : }, '')
13 : }
14 :
15 36 : function flattenIssues(
16 : issues: readonly z.core.$ZodIssue[],
17 : prefix: IssuePath = []
18 : ): { path: string; message: string }[] {
19 36 : return issues.flatMap((issue) => {
20 105 : const issuePath = [...prefix, ...issue.path]
21 105 : const path = toFormPath(issuePath)
22 105 : const own = { path, message: issue.message }
23 105 : if (issue.code !== 'invalid_union') return [own]
24 :
25 0 : const nested = flattenIssues(issue.errors.flat(), issuePath)
26 105 : return path || nested.length === 0 ? [...nested, own] : nested
27 : })
28 : }
29 :
30 36 : function toTypedSchemaErrors(
31 : issues: readonly z.core.$ZodIssue[]
32 : ): TypedSchemaError[] {
33 36 : const errorsByPath = new Map<string, string[]>()
34 36 : for (const { path, message } of flattenIssues(issues)) {
35 105 : errorsByPath.set(path, [...(errorsByPath.get(path) ?? []), message])
36 : }
37 36 : return Array.from(errorsByPath, ([path, errors]) => ({ path, errors }))
38 : }
39 :
40 56 : export function toTypedSchema<TSchema extends z.ZodType>(
41 : schema: MaybeRefOrGetter<TSchema>
42 : ): TypedSchema<z.input<TSchema>, z.output<TSchema>> {
43 56 : return {
44 : __type: 'VVTypedSchema',
45 : async parse(values) {
46 42 : const result = await toValue(schema).safeParseAsync(values)
47 42 : return result.success
48 : ? { value: result.data, errors: [] }
49 : : { errors: toTypedSchemaErrors(result.error.issues) }
50 : }
51 : }
52 : }
|