-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathparse.ts
106 lines (96 loc) · 2.9 KB
/
parse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import {
type Intent,
type Submission,
parse as baseParse,
formatPaths,
} from "@conform-to/dom";
import {
type BaseIssue,
type Config,
type GenericSchema,
type GenericSchemaAsync,
type InferOutput,
type SafeParseResult,
safeParse,
safeParseAsync,
} from "valibot";
import { enableTypeCoercion } from "./coercion";
export const conformValibotMessage = {
VALIDATION_SKIPPED: "__skipped__",
VALIDATION_UNDEFINED: "__undefined__",
};
type ErrorType = Record<string, string[] | null> | null;
export function parseWithValibot<Schema extends GenericSchema>(
payload: FormData | URLSearchParams,
config: {
schema: Schema | ((intent: Intent | null) => Schema);
info?: Pick<
Config<BaseIssue<unknown>>,
"abortEarly" | "abortPipeEarly" | "lang"
>;
},
): Submission<InferOutput<Schema>>;
export function parseWithValibot<Schema extends GenericSchemaAsync>(
payload: FormData | URLSearchParams,
config: {
schema: Schema | ((intent: Intent | null) => Schema);
info?: Pick<
Config<BaseIssue<unknown>>,
"abortEarly" | "abortPipeEarly" | "lang"
>;
},
): Promise<Submission<InferOutput<Schema>>>;
export function parseWithValibot<
Schema extends GenericSchema | GenericSchemaAsync,
>(
payload: FormData | URLSearchParams,
config: {
schema: Schema | ((intent: Intent | null) => Schema);
info?: Pick<
Config<BaseIssue<unknown>>,
"abortEarly" | "abortPipeEarly" | "lang"
>;
},
): Submission<InferOutput<Schema>> | Promise<Submission<InferOutput<Schema>>> {
return baseParse<InferOutput<Schema>, string[]>(payload, {
resolve(payload, intent) {
const originalSchema =
typeof config.schema === "function"
? config.schema(intent)
: config.schema;
const { schema } = enableTypeCoercion(originalSchema);
const resolveResult = (
result: SafeParseResult<Schema>,
): { value: InferOutput<Schema> } | { error: ErrorType } => {
if (result.success) {
return {
value: result.output,
};
}
return {
error: result.issues.reduce<ErrorType>((result, e) => {
if (
result === null ||
e.message === conformValibotMessage.VALIDATION_UNDEFINED
) {
return null;
}
const name = formatPaths(
e.path?.map((d) => d.key as string | number) ?? [],
);
result[name] =
result[name] === null ||
e.message === conformValibotMessage.VALIDATION_SKIPPED
? null
: [...(result[name] ?? []), e.message];
return result;
}, {}),
};
};
if (schema.async === true) {
return safeParseAsync(schema, payload, config.info).then(resolveResult);
}
return resolveResult(safeParse(schema, payload, config.info));
},
});
}