@kubb/plugin-zod
Version:
Zod schema generator plugin for Kubb, creating type-safe validation schemas from OpenAPI specifications for runtime data validation.
794 lines (789 loc) • 31.7 kB
JavaScript
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
value,
configurable: true
});
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) {
__defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
}
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let _kubb_core_transformers = require("@kubb/core/transformers");
_kubb_core_transformers = __toESM(_kubb_core_transformers);
let _kubb_plugin_oas = require("@kubb/plugin-oas");
let _kubb_react_fabric = require("@kubb/react-fabric");
let _kubb_react_fabric_jsx_runtime = require("@kubb/react-fabric/jsx-runtime");
//#region src/components/Operations.tsx
function Operations({ name, operations }) {
const operationsJSON = operations.reduce((prev, acc) => {
prev[`"${acc.operation.getOperationId()}"`] = acc.data;
return prev;
}, {});
const pathsJSON = operations.reduce((prev, acc) => {
prev[`"${acc.operation.path}"`] = {
...prev[`"${acc.operation.path}"`] || {},
[acc.operation.method]: `operations["${acc.operation.getOperationId()}"]`
};
return prev;
}, {});
return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
name: "OperationSchema",
isExportable: true,
isIndexable: true,
children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
name: "OperationSchema",
export: true,
children: `{
readonly request: z.ZodTypeAny | undefined;
readonly parameters: {
readonly path: z.ZodTypeAny | undefined;
readonly query: z.ZodTypeAny | undefined;
readonly header: z.ZodTypeAny | undefined;
};
readonly responses: {
readonly [status: number]: z.ZodTypeAny;
readonly default: z.ZodTypeAny;
};
readonly errors: {
readonly [status: number]: z.ZodTypeAny;
};
}`
})
}),
/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
name: "OperationsMap",
isExportable: true,
isIndexable: true,
children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
name: "OperationsMap",
export: true,
children: "Record<string, OperationSchema>"
})
}),
/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
name,
isExportable: true,
isIndexable: true,
children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
export: true,
name,
asConst: true,
children: `{${_kubb_core_transformers.default.stringifyObject(operationsJSON)}}`
})
}),
/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
name: "paths",
isExportable: true,
isIndexable: true,
children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
export: true,
name: "paths",
asConst: true,
children: `{${_kubb_core_transformers.default.stringifyObject(pathsJSON)}}`
})
})
] });
}
//#endregion
//#region src/parser.ts
/**
* Helper to build string/array length constraint checks for Zod Mini mode
*/
function buildLengthChecks(min, max) {
const checks = [];
if (min !== void 0) checks.push(`z.minLength(${min})`);
if (max !== void 0) checks.push(`z.maxLength(${max})`);
return checks;
}
const zodKeywordMapper = {
any: () => "z.any()",
unknown: () => "z.unknown()",
void: () => "z.void()",
number: (coercion, min, max, exclusiveMinimum, exclusiveMaximum, mini) => {
if (mini) {
const checks = [];
if (min !== void 0) checks.push(`z.minimum(${min})`);
if (max !== void 0) checks.push(`z.maximum(${max})`);
if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
if (checks.length > 0) return `z.number().check(${checks.join(", ")})`;
return "z.number()";
}
return [
coercion ? "z.coerce.number()" : "z.number()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0,
exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : void 0,
exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : void 0
].filter(Boolean).join("");
},
integer: (coercion, min, max, version = "3", exclusiveMinimum, exclusiveMaximum, mini) => {
if (mini) {
const checks = [];
if (min !== void 0) checks.push(`z.minimum(${min})`);
if (max !== void 0) checks.push(`z.maximum(${max})`);
if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
if (checks.length > 0) return `z.int().check(${checks.join(", ")})`;
return "z.int()";
}
return [
coercion ? "z.coerce.number().int()" : version === "4" ? "z.int()" : "z.number().int()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0,
exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : void 0,
exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : void 0
].filter(Boolean).join("");
},
interface: (value, strict) => {
if (strict) return `z.strictInterface({
${value}
})`;
return `z.interface({
${value}
})`;
},
object: (value, strict, version = "3") => {
if (version === "4" && strict) return `z.strictObject({
${value}
})`;
if (strict) return `z.object({
${value}
}).strict()`;
return `z.object({
${value}
})`;
},
string: (coercion, min, max, mini) => {
if (mini) {
const checks = buildLengthChecks(min, max);
if (checks.length > 0) return `z.string().check(${checks.join(", ")})`;
return "z.string()";
}
return [
coercion ? "z.coerce.string()" : "z.string()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0
].filter(Boolean).join("");
},
boolean: () => "z.boolean()",
undefined: () => "z.undefined()",
nullable: (value) => {
if (value) return `z.nullable(${value})`;
return ".nullable()";
},
null: () => "z.null()",
nullish: (value) => {
if (value) return `z.nullish(${value})`;
return ".nullish()";
},
array: (items = [], min, max, unique, mini) => {
if (mini) {
const checks = buildLengthChecks(min, max);
if (unique) checks.push(`z.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`);
if (checks.length > 0) return `z.array(${items?.join("")}).check(${checks.join(", ")})`;
return `z.array(${items?.join("")})`;
}
return [
`z.array(${items?.join("")})`,
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0,
unique ? `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })` : void 0
].filter(Boolean).join("");
},
tuple: (items = []) => `z.tuple([${items?.join(", ")}])`,
enum: (items = []) => `z.enum([${items?.join(", ")}])`,
union: (items = []) => `z.union([${items?.join(", ")}])`,
const: (value) => `z.literal(${value ?? ""})`,
datetime: (offset = false, local = false, version = "3", mini) => {
if (mini) return "z.string()";
if (offset) return version === "4" ? `z.iso.datetime({ offset: ${offset} })` : `z.string().datetime({ offset: ${offset} })`;
if (local) return version === "4" ? `z.iso.datetime({ local: ${local} })` : `z.string().datetime({ local: ${local} })`;
return version === "4" ? "z.iso.datetime()" : "z.string().datetime()";
},
date: (type = "string", coercion, version = "3") => {
if (type === "string") return version === "4" ? "z.iso.date()" : "z.string().date()";
if (coercion) return "z.coerce.date()";
return "z.date()";
},
time: (type = "string", coercion, version = "3") => {
if (type === "string") return version === "4" ? "z.iso.time()" : "z.string().time()";
if (coercion) return "z.coerce.date()";
return "z.date()";
},
uuid: (coercion, version = "3", min, max, mini) => {
if (mini) {
const checks = buildLengthChecks(min, max);
if (checks.length > 0) return `z.uuid().check(${checks.join(", ")})`;
return "z.uuid()";
}
return [
coercion ? version === "4" ? "z.uuid()" : "z.coerce.string().uuid()" : version === "4" ? "z.uuid()" : "z.string().uuid()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0
].filter(Boolean).join("");
},
url: (coercion, version = "3", min, max, mini) => {
if (mini) {
const checks = buildLengthChecks(min, max);
if (checks.length > 0) return `z.url().check(${checks.join(", ")})`;
return "z.url()";
}
return [
coercion ? version === "4" ? "z.url()" : "z.coerce.string().url()" : version === "4" ? "z.url()" : "z.string().url()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0
].filter(Boolean).join("");
},
default: (value, innerSchema, mini) => {
if (mini && innerSchema) return `z._default(${innerSchema}, ${typeof value === "object" ? "{}" : value ?? ""})`;
if (typeof value === "object") return ".default({})";
if (value === void 0) return ".default()";
if (typeof value === "string" && !value) return `.default('')`;
return `.default(${value ?? ""})`;
},
and: (items = [], mini) => {
if (mini && items.length > 0) {
const checks = [];
for (const item of items) {
const checkStart = item.indexOf(".check(");
if (checkStart !== -1) {
let depth = 0;
let i = checkStart + 7;
let checkContent = "";
while (i < item.length) {
const char = item[i];
if (char === "(") depth++;
else if (char === ")") {
if (depth === 0) break;
depth--;
}
checkContent += char;
i++;
}
if (checkContent) checks.push(checkContent);
}
}
if (checks.length > 0) return `.check(${checks.join(", ")})`;
return "";
}
return items?.map((item) => `.and(${item})`).join("");
},
describe: (value = "", innerSchema, mini) => {
if (mini) return;
if (innerSchema) return `z.describe(${innerSchema}, ${value})`;
return `.describe(${value})`;
},
max: void 0,
min: void 0,
optional: (value) => {
if (value) return `z.optional(${value})`;
return ".optional()";
},
matches: (value = "", coercion, mini, min, max) => {
if (mini) {
const checks = buildLengthChecks(min, max);
checks.push(`z.regex(${value})`);
return `z.string().check(${checks.join(", ")})`;
}
return [
coercion ? "z.coerce.string()" : "z.string()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0,
`.regex(${value})`
].filter(Boolean).join("");
},
email: (coercion, version = "3", min, max, mini) => {
if (mini) {
const checks = buildLengthChecks(min, max);
if (checks.length > 0) return `z.email().check(${checks.join(", ")})`;
return "z.email()";
}
return [
coercion ? version === "4" ? "z.email()" : "z.coerce.string().email()" : version === "4" ? "z.email()" : "z.string().email()",
min !== void 0 ? `.min(${min})` : void 0,
max !== void 0 ? `.max(${max})` : void 0
].filter(Boolean).join("");
},
firstName: void 0,
lastName: void 0,
password: void 0,
phone: void 0,
readOnly: void 0,
writeOnly: void 0,
ref: (value) => {
if (!value) return;
return `z.lazy(() => ${value})`;
},
blob: () => "z.instanceof(File)",
deprecated: void 0,
example: void 0,
schema: void 0,
catchall: (value, mini) => {
if (mini) return;
return value ? `.catchall(${value})` : void 0;
},
name: void 0,
exclusiveMinimum: void 0,
exclusiveMaximum: void 0
};
/**
* @link based on https://github.com/cellular/oazapfts/blob/7ba226ebb15374e8483cc53e7532f1663179a22c/src/codegen/generate.ts#L398
*/
function sort(items) {
const order = [
_kubb_plugin_oas.schemaKeywords.string,
_kubb_plugin_oas.schemaKeywords.datetime,
_kubb_plugin_oas.schemaKeywords.date,
_kubb_plugin_oas.schemaKeywords.time,
_kubb_plugin_oas.schemaKeywords.tuple,
_kubb_plugin_oas.schemaKeywords.number,
_kubb_plugin_oas.schemaKeywords.object,
_kubb_plugin_oas.schemaKeywords.enum,
_kubb_plugin_oas.schemaKeywords.url,
_kubb_plugin_oas.schemaKeywords.email,
_kubb_plugin_oas.schemaKeywords.firstName,
_kubb_plugin_oas.schemaKeywords.lastName,
_kubb_plugin_oas.schemaKeywords.password,
_kubb_plugin_oas.schemaKeywords.matches,
_kubb_plugin_oas.schemaKeywords.uuid,
_kubb_plugin_oas.schemaKeywords.null,
_kubb_plugin_oas.schemaKeywords.min,
_kubb_plugin_oas.schemaKeywords.max,
_kubb_plugin_oas.schemaKeywords.default,
_kubb_plugin_oas.schemaKeywords.describe,
_kubb_plugin_oas.schemaKeywords.optional,
_kubb_plugin_oas.schemaKeywords.nullable,
_kubb_plugin_oas.schemaKeywords.nullish
];
if (!items) return [];
return _kubb_core_transformers.default.orderBy(items, [(v) => order.indexOf(v.keyword)], ["asc"]);
}
/**
* Keywords that represent modifiers for mini mode
* These are separated from the base schema and wrapped around it
* Note: describe is included to filter it out, but won't be wrapped (Zod Mini doesn't support describe)
*/
const miniModifierKeywords = [
_kubb_plugin_oas.schemaKeywords.optional,
_kubb_plugin_oas.schemaKeywords.nullable,
_kubb_plugin_oas.schemaKeywords.nullish,
_kubb_plugin_oas.schemaKeywords.default,
_kubb_plugin_oas.schemaKeywords.describe
];
/**
* Extracts mini mode modifiers from a schemas array
* This can be reused by other parsers (e.g., valibot) that need similar functionality
* Note: describe is not included as Zod Mini doesn't support it
*/
function extractMiniModifiers(schemas) {
const defaultSchema = schemas.find((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.default));
return {
hasOptional: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.optional)),
hasNullable: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.nullable)),
hasNullish: schemas.some((item) => (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.nullish)),
defaultValue: defaultSchema?.args
};
}
/**
* Filters out modifier keywords from schemas for mini mode base schema parsing
* This can be reused by other parsers (e.g., valibot) that need similar functionality
*/
function filterMiniModifiers(schemas) {
return schemas.filter((item) => !miniModifierKeywords.some((keyword) => (0, _kubb_plugin_oas.isKeyword)(item, keyword)));
}
/**
* Wraps an output string with Zod Mini functional modifiers
* Order: default (innermost) -> nullable -> optional (outermost)
* OR: default -> nullish
* Note: describe is not supported in Zod Mini and is skipped
*/
function wrapWithMiniModifiers(output, modifiers) {
let result = output;
if (modifiers.defaultValue !== void 0) result = zodKeywordMapper.default(modifiers.defaultValue, result, true);
if (modifiers.hasNullish) result = zodKeywordMapper.nullish(result);
else {
if (modifiers.hasNullable) result = zodKeywordMapper.nullable(result);
if (modifiers.hasOptional) result = zodKeywordMapper.optional(result);
}
return result;
}
const shouldCoerce = (coercion, type) => {
if (coercion === void 0) return false;
if (typeof coercion === "boolean") return coercion;
return !!coercion[type];
};
const parse = (0, _kubb_plugin_oas.createParser)({
mapper: zodKeywordMapper,
handlers: {
union(tree, options) {
const { current, schema, parent, name, siblings } = tree;
if (Array.isArray(current.args) && current.args.length === 1) return this.parse({
schema,
parent,
name,
current: current.args[0],
siblings
}, options);
if (Array.isArray(current.args) && !current.args.length) return "";
return zodKeywordMapper.union(sort(current.args).map((it, _index, siblings$1) => this.parse({
schema,
parent: current,
name,
current: it,
siblings: siblings$1
}, options)).filter(Boolean));
},
and(tree, options) {
const { current, schema, name } = tree;
const items = sort(current.args).filter((schema$1) => {
return ![_kubb_plugin_oas.schemaKeywords.optional, _kubb_plugin_oas.schemaKeywords.describe].includes(schema$1.keyword);
}).map((it, _index, siblings) => this.parse({
schema,
parent: current,
name,
current: it,
siblings
}, options)).filter(Boolean);
return `${items.slice(0, 1)}${zodKeywordMapper.and(items.slice(1), options.mini)}`;
},
array(tree, options) {
const { current, schema, name } = tree;
return zodKeywordMapper.array(sort(current.args.items).map((it, _index, siblings) => {
return this.parse({
schema,
parent: current,
name,
current: it,
siblings
}, options);
}).filter(Boolean), current.args.min, current.args.max, current.args.unique, options.mini);
},
enum(tree, options) {
const { current, schema, name } = tree;
if (current.args.asConst) {
if (current.args.items.length === 1) {
const child = {
keyword: _kubb_plugin_oas.schemaKeywords.const,
args: current.args.items[0]
};
return this.parse({
schema,
parent: current,
name,
current: child,
siblings: [child]
}, options);
}
return zodKeywordMapper.union(current.args.items.map((schema$1) => ({
keyword: _kubb_plugin_oas.schemaKeywords.const,
args: schema$1
})).map((it, _index, siblings) => {
return this.parse({
schema,
parent: current,
name,
current: it,
siblings
}, options);
}).filter(Boolean));
}
return zodKeywordMapper.enum(current.args.items.map((schema$1) => {
if (schema$1.format === "boolean") return _kubb_core_transformers.default.stringify(schema$1.value);
if (schema$1.format === "number") return _kubb_core_transformers.default.stringify(schema$1.value);
return _kubb_core_transformers.default.stringify(schema$1.value);
}));
},
ref(tree, options) {
const { current } = tree;
if (options.skipLazyForRefs) return current.args?.name;
return zodKeywordMapper.ref(current.args?.name);
},
object(tree, options) {
const { current, schema, name } = tree;
const properties = Object.entries(current.args?.properties || {}).filter((item) => {
const schema$1 = item[1];
return schema$1 && typeof schema$1.map === "function";
}).map(([propertyName, schemas]) => {
const nameSchema = schemas.find((it) => it.keyword === _kubb_plugin_oas.schemaKeywords.name);
const isNullable = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.nullable));
const isNullish = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.nullish));
const isOptional = schemas.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.optional));
const hasRef = !!_kubb_plugin_oas.SchemaGenerator.find(schemas, _kubb_plugin_oas.schemaKeywords.ref);
const mappedName = nameSchema?.args || propertyName;
if (options.mapper && Object.hasOwn(options.mapper, mappedName)) return `"${propertyName}": ${options.mapper?.[mappedName]}`;
const baseSchemaOutput = sort(schemas).filter((schema$1) => {
return !(0, _kubb_plugin_oas.isKeyword)(schema$1, _kubb_plugin_oas.schemaKeywords.optional) && !(0, _kubb_plugin_oas.isKeyword)(schema$1, _kubb_plugin_oas.schemaKeywords.nullable) && !(0, _kubb_plugin_oas.isKeyword)(schema$1, _kubb_plugin_oas.schemaKeywords.nullish);
}).map((it) => {
const skipLazyForRefs = options.version === "4" && hasRef;
return this.parse({
schema,
parent: current,
name,
current: it,
siblings: schemas
}, {
...options,
skipLazyForRefs
});
}).filter(Boolean).join("");
const objectValue = options.wrapOutput ? options.wrapOutput({
output: baseSchemaOutput,
schema: schema?.properties?.[propertyName]
}) || baseSchemaOutput : baseSchemaOutput;
if (options.version === "4" && hasRef) {
if (options.mini) {
if (isNullish) return `get "${propertyName}"(){
return ${zodKeywordMapper.nullish(objectValue)}
}`;
if (isOptional) return `get "${propertyName}"(){
return ${zodKeywordMapper.optional(objectValue)}
}`;
if (isNullable) return `get "${propertyName}"(){
return ${zodKeywordMapper.nullable(objectValue)}
}`;
return `get "${propertyName}"(){
return ${objectValue}
}`;
}
if (isNullish) return `get "${propertyName}"(){
return ${objectValue}${zodKeywordMapper.nullish()}
}`;
if (isOptional) return `get "${propertyName}"(){
return ${objectValue}${zodKeywordMapper.optional()}
}`;
if (isNullable) return `get "${propertyName}"(){
return ${objectValue}${zodKeywordMapper.nullable()}
}`;
return `get "${propertyName}"(){
return ${objectValue}
}`;
}
if (isNullish) return `"${propertyName}": ${objectValue}${zodKeywordMapper.nullish()}`;
if (isOptional) return `"${propertyName}": ${zodKeywordMapper.optional(objectValue)}`;
if (isNullable) return `"${propertyName}": ${zodKeywordMapper.nullable(objectValue)}`;
return `"${propertyName}": ${objectValue}`;
}).join(",\n");
const additionalProperties = current.args?.additionalProperties?.length ? current.args.additionalProperties.map((it, _index, siblings) => this.parse({
schema,
parent: current,
name,
current: it,
siblings
}, options)).filter(Boolean).join("") : void 0;
return [zodKeywordMapper.object(properties, current.args?.strict, options.version), additionalProperties ? zodKeywordMapper.catchall(additionalProperties, options.mini) : void 0].filter(Boolean).join("");
},
tuple(tree, options) {
const { current, schema, name } = tree;
return zodKeywordMapper.tuple(current.args.items.map((it, _index, siblings) => this.parse({
schema,
parent: current,
name,
current: it,
siblings
}, options)).filter(Boolean));
},
const(tree, _options) {
const { current } = tree;
if (current.args.format === "number" && current.args.value !== void 0) return zodKeywordMapper.const(Number(current.args.value));
if (current.args.format === "boolean" && current.args.value !== void 0) return zodKeywordMapper.const(typeof current.args.value === "boolean" ? current.args.value : void 0);
return zodKeywordMapper.const(_kubb_core_transformers.default.stringify(current.args.value));
},
matches(tree, options) {
const { current, siblings } = tree;
if (siblings.some((it) => (0, _kubb_plugin_oas.isKeyword)(it, _kubb_plugin_oas.schemaKeywords.ref))) return;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
if (current.args) return zodKeywordMapper.matches(_kubb_core_transformers.default.toRegExpString(current.args, null), shouldCoerce(options.coercion, "strings"), options.mini, minSchema?.args, maxSchema?.args);
},
default(tree, options) {
const { current } = tree;
if (options.mini) return;
if (current.args !== void 0) return zodKeywordMapper.default(current.args);
return zodKeywordMapper.default();
},
describe(tree, options) {
const { current } = tree;
if (current.args) return zodKeywordMapper.describe(_kubb_core_transformers.default.stringify(current.args.toString()), void 0, options.mini);
},
string(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
return zodKeywordMapper.string(shouldCoerce(options.coercion, "strings"), minSchema?.args, maxSchema?.args, options.mini);
},
uuid(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
return zodKeywordMapper.uuid(shouldCoerce(options.coercion, "strings"), options.version, minSchema?.args, maxSchema?.args, options.mini);
},
email(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
return zodKeywordMapper.email(shouldCoerce(options.coercion, "strings"), options.version, minSchema?.args, maxSchema?.args, options.mini);
},
url(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
return zodKeywordMapper.url(shouldCoerce(options.coercion, "strings"), options.version, minSchema?.args, maxSchema?.args, options.mini);
},
number(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
const exclusiveMinimumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMinimum");
const exclusiveMaximumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMaximum");
return zodKeywordMapper.number(shouldCoerce(options.coercion, "numbers"), minSchema?.args, maxSchema?.args, exclusiveMinimumSchema?.args, exclusiveMaximumSchema?.args, options.mini);
},
integer(tree, options) {
const { siblings } = tree;
const minSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "min");
const maxSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "max");
const exclusiveMinimumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMinimum");
const exclusiveMaximumSchema = (0, _kubb_plugin_oas.findSchemaKeyword)(siblings, "exclusiveMaximum");
return zodKeywordMapper.integer(shouldCoerce(options.coercion, "numbers"), minSchema?.args, maxSchema?.args, options.version, exclusiveMinimumSchema?.args, exclusiveMaximumSchema?.args, options.mini);
},
datetime(tree, options) {
const { current } = tree;
return zodKeywordMapper.datetime(current.args.offset, current.args.local, options.version, options.mini);
},
date(tree, options) {
const { current } = tree;
return zodKeywordMapper.date(current.args.type, shouldCoerce(options.coercion, "dates"), options.version);
},
time(tree, options) {
const { current } = tree;
return zodKeywordMapper.time(current.args.type, shouldCoerce(options.coercion, "dates"), options.version);
}
}
});
//#endregion
//#region src/components/Zod.tsx
function Zod({ name, typeName, tree, schema, inferTypeName, mapper, coercion, keysToOmit, description, wrapOutput, version, emptySchemaType, mini = false }) {
const hasTuple = !!_kubb_plugin_oas.SchemaGenerator.find(tree, _kubb_plugin_oas.schemaKeywords.tuple);
const schemas = sort(tree).filter((item) => {
if (hasTuple && ((0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.min) || (0, _kubb_plugin_oas.isKeyword)(item, _kubb_plugin_oas.schemaKeywords.max))) return false;
return true;
});
const baseSchemas = mini ? filterMiniModifiers(schemas) : schemas;
const output = baseSchemas.map((schemaKeyword, index) => {
const siblings = baseSchemas.filter((_, i) => i !== index);
return parse({
schema,
parent: void 0,
current: schemaKeyword,
siblings,
name
}, {
mapper,
coercion,
wrapOutput,
version,
mini
});
}).filter(Boolean).join("");
let suffix = "";
const firstSchema = schemas.at(0);
const lastSchema = schemas.at(-1);
if (!mini && lastSchema && (0, _kubb_plugin_oas.isKeyword)(lastSchema, _kubb_plugin_oas.schemaKeywords.nullable)) if (firstSchema && (0, _kubb_plugin_oas.isKeyword)(firstSchema, _kubb_plugin_oas.schemaKeywords.ref)) if (version === "3") suffix = ".unwrap().schema.unwrap()";
else suffix = ".unwrap().unwrap()";
else suffix = ".unwrap()";
else if (!mini) {
if (firstSchema && (0, _kubb_plugin_oas.isKeyword)(firstSchema, _kubb_plugin_oas.schemaKeywords.ref)) if (version === "3") suffix = ".schema";
else suffix = ".unwrap()";
}
const emptyValue = parse({
schema,
parent: void 0,
current: { keyword: _kubb_plugin_oas.schemaKeywords[emptySchemaType] },
siblings: []
}, {
mapper,
coercion,
wrapOutput,
version,
mini
});
let baseSchemaOutput = [output, keysToOmit?.length ? `${suffix}.omit({ ${keysToOmit.map((key) => `'${key}': true`).join(",")} })` : void 0].filter(Boolean).join("") || emptyValue || "";
if (mini) baseSchemaOutput = wrapWithMiniModifiers(baseSchemaOutput, extractMiniModifiers(schemas));
const wrappedSchemaOutput = wrapOutput ? wrapOutput({
output: baseSchemaOutput,
schema
}) || baseSchemaOutput : baseSchemaOutput;
const finalOutput = typeName ? `${wrappedSchemaOutput} as unknown as ${version === "4" ? "z.ZodType" : "ToZod"}<${typeName}>` : wrappedSchemaOutput;
return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
name,
isExportable: true,
isIndexable: true,
children: /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Const, {
export: true,
name,
JSDoc: { comments: [description ? `@description ${_kubb_core_transformers.default.jsStringEscape(description)}` : void 0].filter(Boolean) },
children: finalOutput
})
}), inferTypeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric.File.Source, {
name: inferTypeName,
isExportable: true,
isIndexable: true,
isTypeOnly: true,
children: [typeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
export: true,
name: inferTypeName,
children: typeName
}), !typeName && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.Type, {
export: true,
name: inferTypeName,
children: `z.infer<typeof ${name}>`
})]
})] });
}
//#endregion
Object.defineProperty(exports, 'Operations', {
enumerable: true,
get: function () {
return Operations;
}
});
Object.defineProperty(exports, 'Zod', {
enumerable: true,
get: function () {
return Zod;
}
});
Object.defineProperty(exports, '__name', {
enumerable: true,
get: function () {
return __name;
}
});
Object.defineProperty(exports, '__toESM', {
enumerable: true,
get: function () {
return __toESM;
}
});
//# sourceMappingURL=components-BKoSLPE6.cjs.map