1 import { zodResolver } from "@hookform/resolvers/zod"
2 import { FieldValues, Resolver, useForm, UseFormProps } from "react-hook-form"
3 import { z, ZodObject } from "zod"
4
5 import { ConfigField } from "../types"
6
7 interface UseExtendableFormProps<
8 TSchema extends ZodObject<any>,
9 TContext = any,
10 TData = any,
11 TTransformedValues extends FieldValues = z.infer<TSchema>
12 > extends Omit<
13 UseFormProps<z.infer<TSchema>, TContext, TTransformedValues>,
14 "resolver"
15 > {
16 schema: TSchema | z.ZodPipe<TSchema, z.ZodType>
17 configs: ConfigField[]
18 data?: TData
19 }
20
21 function createAdditionalDataSchema(configs: ConfigField[]) {
22 return configs.reduce((acc, config) => {
23 acc[config.name] = config.validation
24 return acc
25 }, {} as Record<string, z.ZodTypeAny>)
26 }
27
28 /**
29 * Extracts the shape from a schema, handling both ZodObject and ZodPipe.
30 * ZodPipe is created by .transform() and wraps the original schema.
31 */
32 function getSchemaShape(
33 schema: ZodObject<any> | z.ZodPipe<ZodObject<any>, z.ZodType>
34 ): z.ZodRawShape {
35 if (schema instanceof z.ZodPipe) {
36 const innerSchema = schema.def.in
37 // Guard: ensure inner schema is a ZodObject before accessing shape
38 if (innerSchema instanceof ZodObject) {
39 return innerSchema.shape
40 }
41 throw new Error(
42 "Expected ZodPipe to contain a ZodObject. Schema extensions require the base schema to be a ZodObject."
43 )
44 }
45 return schema.shape
46 }
47
48 function createExtendedSchema(
49 baseSchema: ZodObject<any> | z.ZodPipe<ZodObject<any>, z.ZodType>,
50 additionalDataSchema: Record<string, z.ZodTypeAny>
51 ) {
52 const baseShape = getSchemaShape(baseSchema)
53
54 const extendedObjectSchema = z.object({
55 ...baseShape,
56 additional_data: z.object(additionalDataSchema).optional(),
57 })
58
59 return baseSchema
60 .superRefine((data, ctx) => {
61 const result = extendedObjectSchema.safeParse(data)
62 if (!result.success) {
63 result.error.issues.forEach((issue) => ctx.addIssue({ ...issue }))
64 }
65 })
66 .and(extendedObjectSchema)
67 }
68
69 function createExtendedDefaultValues<TData>(
70 baseDefaultValues: any,
71 configs: ConfigField[],
72 data?: TData
73 ) {
74 const additional_data = configs.reduce((acc, config) => {
75 const { name, defaultValue } = config
76
77 acc[name] =
78 typeof defaultValue === "function" ? defaultValue(data) : defaultValue
79 return acc
80 }, {} as Record<string, any>)
81
82 return Object.assign(baseDefaultValues, { additional_data })
83 }
84
85 export const useExtendableForm = <
86 TSchema extends ZodObject<any>,
87 TContext = any,
88 TTransformedValues extends FieldValues = z.infer<TSchema>
89 >({
90 defaultValues: baseDefaultValues,
91 schema: baseSchema,
92 configs,
93 data,
94 ...props
95 }: UseExtendableFormProps<TSchema, TContext, any, TTransformedValues>) => {
96 const additionalDataSchema = createAdditionalDataSchema(configs)
97 const schema = createExtendedSchema(baseSchema, additionalDataSchema)
98 const defaultValues = createExtendedDefaultValues(
99 baseDefaultValues,
100 configs,
101 data
102 )
103
104 return useForm<z.infer<TSchema>, TContext, TTransformedValues>({
105 ...props,
106 defaultValues,
107 // `schema` is assembled at runtime from the base schema plus the extension
108 // fields, so its inferred type can't be related back to `TSchema` here.
109 resolver: zodResolver(schema) as unknown as Resolver<
110 z.infer<TSchema>,
111 TContext,
112 TTransformedValues
113 >,
114 })
115 }