import { z } from "zod/mini" import { WidgetKeySchema } from "../common/widgetKey" import { DynamicWidgetModelSchema, StaticWidgetModelSchema } from "./widget" // Tab export const StaticCustomTypeModelTabSchema = z.record(WidgetKeySchema, StaticWidgetModelSchema) export type StaticCustomTypeModelTab = z.infer export const DynamicCustomTypeModelTabSchema = z.record(WidgetKeySchema, DynamicWidgetModelSchema) export type DynamicCustomTypeModelTab = z.infer // Custom types export const CustomTypeFormatSchema = z.enum(["page", "custom"]) export type CustomTypeFormat = z.infer // Factory to create CustomType schema with configurable section type const createCustomTypeSchema = < T extends typeof StaticCustomTypeModelTabSchema | typeof DynamicCustomTypeModelTabSchema, >( sectionSchema: T, ) => { // 4.4.0 and earlier const Schema_4_4_0 = z.object({ id: z.string(), label: z.nullish(z.string()), repeatable: z._default(z.boolean(), true), json: z.record(z.string(), sectionSchema), status: z._default(z.boolean(), true), format: z._default(CustomTypeFormatSchema, "custom"), schema: z.optional(z.undefined()), }) // 4.5.0 and later const Schema_4_5_0 = z .object({ ...Schema_4_4_0.shape, schema: z.literal("@prismicio/types-internal@4.5.0"), }) .check( z.superRefine((model, ctx) => { const { json } = model const tabEntries = Object.entries(json) // A map of widget IDs to the tab they belong to // to check for ID uniqueness across all tabs. const existingWidgetKeys = new Map() for (const [tabID, tab] of tabEntries) { for (const [widgetID, widget] of Object.entries(tab)) { if (widget.type === "UID" && widgetID !== "uid") { ctx.addIssue({ code: "custom", message: `The UID widget ID must be set to "uid"`, path: ["json", tabID, widgetID], }) } const maybeTabID = existingWidgetKeys.get(widgetID) if (typeof maybeTabID === "string") { ctx.addIssue({ code: "custom", message: `${widgetID} already exists in the "${maybeTabID}" tab`, path: ["json", tabID, widgetID], }) continue } existingWidgetKeys.set(widgetID, tabID) } } }), ) return z.discriminatedUnion("schema", [Schema_4_4_0, Schema_4_5_0]) } export const StaticCustomTypeModelSchema = createCustomTypeSchema(StaticCustomTypeModelTabSchema) export type StaticCustomTypeModel = z.infer export const DynamicCustomTypeModelSchema = createCustomTypeSchema(DynamicCustomTypeModelTabSchema) export type DynamicCustomTypeModel = z.infer /** @deprecated Use DynamicCustomTypeModelSchema instead */ export const CustomTypeModelSchema = DynamicCustomTypeModelSchema /** @deprecated Use DynamicCustomTypeModel instead */ export type CustomTypeModel = DynamicCustomTypeModel