UNPKG

@beignet/core

Version:

Core framework primitives for Beignet

73 lines 2.61 kB
import { z } from "zod"; import { getObjectSchemaShape } from "../contracts/schema-shape.js"; /** * Create the default schema converter for Zod schemas. */ export function createZodSchemaConverter() { return { name: "zod", canConvert(schema) { return schema instanceof z.ZodType; }, toJSONSchema(schema, context) { const jsonSchema = z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "any", io: context.io, }); delete jsonSchema.$schema; return jsonSchema; }, }; } /** * Create a schema introspector for Zod schemas. * * This accesses Zod's internal `_def` property, which is a common pattern in * Zod ecosystem libraries but may break with major Zod updates. Each helper * gracefully returns a safe default if the structure is unexpected. */ export function createZodIntrospector() { return { getShape(schema) { return getObjectSchemaShape(schema); }, getDescription(schema) { if (!schema || typeof schema !== "object") return undefined; const directDescription = schema .description; if (typeof directDescription === "string") { return directDescription; } const schemaDef = schema?._def; if (!schemaDef || typeof schemaDef !== "object") return undefined; const description = schemaDef.description; return typeof description === "string" ? description : undefined; }, isOptional(schema) { if (!schema || typeof schema !== "object") return false; const schemaWithOptional = schema; if (typeof schemaWithOptional.isOptional === "function") { return schemaWithOptional.isOptional(); } const schemaDef = schema?._def; if (!schemaDef || typeof schemaDef !== "object") return false; const def = schemaDef; return def.typeName === "ZodOptional" || def.type === "optional"; }, unwrapOptional(schema) { const schemaDef = schema?._def; const def = schemaDef; if (def?.typeName !== "ZodOptional" && def?.type !== "optional") { return schema; } const innerType = def?.innerType; return innerType ?? schema; }, }; } //# sourceMappingURL=schema-introspector.js.map