81 lines
2.1 KiB
TypeScript
81 lines
2.1 KiB
TypeScript
import { z } from "zod";
|
|
|
|
export const validationPackageName = "personal-brand-validation";
|
|
|
|
const inquiryFieldTypeSchema = z.enum([
|
|
"text",
|
|
"tel",
|
|
"phone",
|
|
"number",
|
|
"select",
|
|
"radio",
|
|
"multi-select",
|
|
"textarea",
|
|
"date",
|
|
"image",
|
|
"url",
|
|
]);
|
|
|
|
const inquiryFieldOptionSchema = z.object({
|
|
label: z.string().min(1),
|
|
value: z.string().min(1),
|
|
});
|
|
|
|
export const inquiryFieldSchema = z
|
|
.object({
|
|
key: z.string().regex(/^[a-z][a-z0-9_]*$/),
|
|
type: inquiryFieldTypeSchema,
|
|
label: z.string().min(1),
|
|
required: z.boolean().optional(),
|
|
options: z.array(inquiryFieldOptionSchema).optional(),
|
|
})
|
|
.passthrough()
|
|
.superRefine((field, context) => {
|
|
if (["select", "radio", "multi-select"].includes(field.type) && !field.options?.length) {
|
|
context.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
path: ["options"],
|
|
message: "选择类字段必须配置 options",
|
|
});
|
|
}
|
|
});
|
|
|
|
export const fieldSnapshotSchema = z.array(inquiryFieldSchema).superRefine((fields, context) => {
|
|
const seen = new Set<string>();
|
|
fields.forEach((field, index) => {
|
|
if (seen.has(field.key)) {
|
|
context.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
path: [index, "key"],
|
|
message: "字段 key 不能重复",
|
|
});
|
|
}
|
|
seen.add(field.key);
|
|
});
|
|
});
|
|
|
|
export const offeringConfigSchema = z
|
|
.object({
|
|
schemaVersion: z.string().optional(),
|
|
sections: z.array(z.unknown()).optional(),
|
|
media: z.array(z.unknown()).optional(),
|
|
cta: z.record(z.unknown()).optional(),
|
|
})
|
|
.passthrough();
|
|
|
|
export type ValidationIssue = { path: string; message: string };
|
|
|
|
function issues(result: z.SafeParseReturnType<unknown, unknown>): ValidationIssue[] {
|
|
return result.success
|
|
? []
|
|
: result.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
}
|
|
|
|
export function validateFieldSnapshot(value: unknown): ValidationIssue[] {
|
|
return issues(fieldSnapshotSchema.safeParse(value));
|
|
}
|
|
|
|
export function validateOfferingConfig(value: unknown): ValidationIssue[] {
|
|
return value === undefined || value === null ? [] : issues(offeringConfigSchema.safeParse(value));
|
|
}
|