@kubb/plugin-zod 5.0.0-alpha.8 → 5.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +25 -7
  3. package/dist/index.cjs +1087 -105
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +369 -4
  6. package/dist/index.js +1074 -105
  7. package/dist/index.js.map +1 -1
  8. package/extension.yaml +485 -0
  9. package/package.json +43 -73
  10. package/src/components/Operations.tsx +25 -18
  11. package/src/components/Zod.tsx +21 -121
  12. package/src/constants.ts +5 -0
  13. package/src/generators/zodGenerator.tsx +174 -160
  14. package/src/index.ts +11 -2
  15. package/src/plugin.ts +67 -156
  16. package/src/printers/printerZod.ts +365 -0
  17. package/src/printers/printerZodMini.ts +310 -0
  18. package/src/resolvers/resolverZod.ts +57 -0
  19. package/src/types.ts +130 -115
  20. package/src/utils.ts +222 -0
  21. package/dist/components-B7zUFnAm.cjs +0 -890
  22. package/dist/components-B7zUFnAm.cjs.map +0 -1
  23. package/dist/components-eECfXVou.js +0 -842
  24. package/dist/components-eECfXVou.js.map +0 -1
  25. package/dist/components.cjs +0 -4
  26. package/dist/components.d.ts +0 -56
  27. package/dist/components.js +0 -2
  28. package/dist/generators-BjPDdJUz.cjs +0 -301
  29. package/dist/generators-BjPDdJUz.cjs.map +0 -1
  30. package/dist/generators-lTWPS6oN.js +0 -290
  31. package/dist/generators-lTWPS6oN.js.map +0 -1
  32. package/dist/generators.cjs +0 -4
  33. package/dist/generators.d.ts +0 -479
  34. package/dist/generators.js +0 -2
  35. package/dist/templates/ToZod.source.cjs +0 -7
  36. package/dist/templates/ToZod.source.cjs.map +0 -1
  37. package/dist/templates/ToZod.source.d.ts +0 -7
  38. package/dist/templates/ToZod.source.js +0 -6
  39. package/dist/templates/ToZod.source.js.map +0 -1
  40. package/dist/types-CoCoOc2u.d.ts +0 -172
  41. package/src/components/index.ts +0 -2
  42. package/src/generators/index.ts +0 -2
  43. package/src/generators/operationsGenerator.tsx +0 -50
  44. package/src/parser.ts +0 -909
  45. package/src/templates/ToZod.source.ts +0 -4
  46. package/templates/ToZod.ts +0 -61
package/dist/index.js CHANGED
@@ -1,10 +1,7 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as operationsGenerator, t as zodGenerator } from "./generators-lTWPS6oN.js";
3
- import { source } from "./templates/ToZod.source.js";
4
- import path from "node:path";
5
- import { PackageManager, createPlugin, getBarrelFiles, getMode } from "@kubb/core";
6
- import { OperationGenerator, SchemaGenerator, pluginOasName } from "@kubb/plugin-oas";
7
- import { pluginTsName } from "@kubb/plugin-ts";
1
+ import { t as __name } from "./chunk--u3MIqq1.js";
2
+ import { ast, defineGenerator, definePlugin, defineResolver } from "@kubb/core";
3
+ import { Const, File, Type, jsxRenderer } from "@kubb/renderer-jsx";
4
+ import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
8
5
  //#region ../../internals/utils/src/casing.ts
9
6
  /**
10
7
  * Shared implementation for camelCase and PascalCase conversion.
@@ -24,9 +21,12 @@ function toCamelOrPascal(text, pascal) {
24
21
  * Splits `text` on `.` and applies `transformPart` to each segment.
25
22
  * The last segment receives `isLast = true`, all earlier segments receive `false`.
26
23
  * Segments are joined with `/` to form a file path.
24
+ *
25
+ * Only splits on dots followed by a letter so that version numbers
26
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
27
27
  */
28
28
  function applyToFileParts(text, transformPart) {
29
- const parts = text.split(".");
29
+ const parts = text.split(/\.(?=[a-zA-Z])/);
30
30
  return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
31
31
  }
32
32
  /**
@@ -60,116 +60,1085 @@ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
60
60
  return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
61
61
  }
62
62
  //#endregion
63
+ //#region ../../internals/utils/src/string.ts
64
+ /**
65
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
66
+ * Returns the string unchanged when no balanced quote pair is found.
67
+ *
68
+ * @example
69
+ * trimQuotes('"hello"') // 'hello'
70
+ * trimQuotes('hello') // 'hello'
71
+ */
72
+ function trimQuotes(text) {
73
+ if (text.length >= 2) {
74
+ const first = text[0];
75
+ const last = text[text.length - 1];
76
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
77
+ }
78
+ return text;
79
+ }
80
+ //#endregion
81
+ //#region ../../internals/utils/src/object.ts
82
+ /**
83
+ * Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
84
+ *
85
+ * @example
86
+ * stringify('hello') // '"hello"'
87
+ * stringify('"hello"') // '"hello"'
88
+ */
89
+ function stringify(value) {
90
+ if (value === void 0 || value === null) return "\"\"";
91
+ return JSON.stringify(trimQuotes(value.toString()));
92
+ }
93
+ /**
94
+ * Converts a plain object into a multiline key-value string suitable for embedding in generated code.
95
+ * Nested objects are recursively stringified with indentation.
96
+ *
97
+ * @example
98
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
99
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
100
+ */
101
+ function stringifyObject(value) {
102
+ return Object.entries(value).map(([key, val]) => {
103
+ if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
104
+ return `${key}: ${val}`;
105
+ }).filter(Boolean).join(",\n");
106
+ }
107
+ //#endregion
108
+ //#region ../../internals/utils/src/regexp.ts
109
+ /**
110
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
111
+ * Inline flags expressed as `^(?im)` prefixes are extracted and applied to the resulting expression.
112
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
113
+ *
114
+ * @example
115
+ * toRegExpString('^(?im)foo') // → 'new RegExp("foo", "im")'
116
+ * toRegExpString('^(?im)foo', null) // → '/foo/im'
117
+ */
118
+ function toRegExpString(text, func = "RegExp") {
119
+ const raw = trimQuotes(text);
120
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
121
+ const replacementTarget = match?.[1] ?? "";
122
+ const matchedFlags = match?.[2];
123
+ const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
124
+ const { source, flags } = new RegExp(cleaned, matchedFlags);
125
+ if (func === null) return `/${source}/${flags}`;
126
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
127
+ }
128
+ //#endregion
129
+ //#region src/components/Operations.tsx
130
+ function Operations({ name, operations }) {
131
+ const operationsJSON = operations.reduce((prev, acc) => {
132
+ prev[`"${acc.node.operationId}"`] = acc.data;
133
+ return prev;
134
+ }, {});
135
+ const pathsJSON = operations.reduce((prev, acc) => {
136
+ prev[`"${acc.node.path}"`] = {
137
+ ...prev[`"${acc.node.path}"`] ?? {},
138
+ [acc.node.method]: `operations["${acc.node.operationId}"]`
139
+ };
140
+ return prev;
141
+ }, {});
142
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
143
+ /* @__PURE__ */ jsx(File.Source, {
144
+ name: "OperationSchema",
145
+ isExportable: true,
146
+ isIndexable: true,
147
+ children: /* @__PURE__ */ jsx(Type, {
148
+ name: "OperationSchema",
149
+ export: true,
150
+ children: `{
151
+ readonly request: z.ZodTypeAny | undefined;
152
+ readonly parameters: {
153
+ readonly path: z.ZodTypeAny | undefined;
154
+ readonly query: z.ZodTypeAny | undefined;
155
+ readonly header: z.ZodTypeAny | undefined;
156
+ };
157
+ readonly responses: {
158
+ readonly [status: number]: z.ZodTypeAny;
159
+ readonly default: z.ZodTypeAny;
160
+ };
161
+ readonly errors: {
162
+ readonly [status: number]: z.ZodTypeAny;
163
+ };
164
+ }`
165
+ })
166
+ }),
167
+ /* @__PURE__ */ jsx(File.Source, {
168
+ name: "OperationsMap",
169
+ isExportable: true,
170
+ isIndexable: true,
171
+ children: /* @__PURE__ */ jsx(Type, {
172
+ name: "OperationsMap",
173
+ export: true,
174
+ children: "Record<string, OperationSchema>"
175
+ })
176
+ }),
177
+ /* @__PURE__ */ jsx(File.Source, {
178
+ name,
179
+ isExportable: true,
180
+ isIndexable: true,
181
+ children: /* @__PURE__ */ jsx(Const, {
182
+ export: true,
183
+ name,
184
+ asConst: true,
185
+ children: `{${stringifyObject(operationsJSON)}}`
186
+ })
187
+ }),
188
+ /* @__PURE__ */ jsx(File.Source, {
189
+ name: "paths",
190
+ isExportable: true,
191
+ isIndexable: true,
192
+ children: /* @__PURE__ */ jsx(Const, {
193
+ export: true,
194
+ name: "paths",
195
+ asConst: true,
196
+ children: `{${stringifyObject(pathsJSON)}}`
197
+ })
198
+ })
199
+ ] });
200
+ }
201
+ //#endregion
202
+ //#region src/components/Zod.tsx
203
+ function Zod({ name, node, printer, inferTypeName }) {
204
+ const output = printer.print(node);
205
+ if (!output) return;
206
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
207
+ name,
208
+ isExportable: true,
209
+ isIndexable: true,
210
+ children: /* @__PURE__ */ jsx(Const, {
211
+ export: true,
212
+ name,
213
+ children: output
214
+ })
215
+ }), inferTypeName && /* @__PURE__ */ jsx(File.Source, {
216
+ name: inferTypeName,
217
+ isExportable: true,
218
+ isIndexable: true,
219
+ isTypeOnly: true,
220
+ children: /* @__PURE__ */ jsx(Type, {
221
+ export: true,
222
+ name: inferTypeName,
223
+ children: `z.infer<typeof ${name}>`
224
+ })
225
+ })] });
226
+ }
227
+ //#endregion
228
+ //#region src/constants.ts
229
+ /**
230
+ * Import paths that use a namespace import (`import * as z from '...'`).
231
+ * All other import paths use a named import (`import { z } from '...'`).
232
+ */
233
+ const ZOD_NAMESPACE_IMPORTS = new Set(["zod", "zod/mini"]);
234
+ //#endregion
235
+ //#region src/utils.ts
236
+ /**
237
+ * Returns `true` when the given coercion option enables coercion for the specified type.
238
+ */
239
+ function shouldCoerce(coercion, type) {
240
+ if (coercion === void 0 || coercion === false) return false;
241
+ if (coercion === true) return true;
242
+ return !!coercion[type];
243
+ }
244
+ /**
245
+ * Collects all resolved schema names for an operation's parameters and responses
246
+ * into a single lookup object, useful for building imports and type references.
247
+ */
248
+ function buildSchemaNames(node, { params, resolver }) {
249
+ const pathParam = params.find((p) => p.in === "path");
250
+ const queryParam = params.find((p) => p.in === "query");
251
+ const headerParam = params.find((p) => p.in === "header");
252
+ const responses = {};
253
+ const errors = {};
254
+ for (const res of node.responses) {
255
+ const name = resolver.resolveResponseStatusName(node, res.statusCode);
256
+ const statusNum = Number(res.statusCode);
257
+ if (!Number.isNaN(statusNum)) {
258
+ responses[statusNum] = name;
259
+ if (statusNum >= 400) errors[statusNum] = name;
260
+ }
261
+ }
262
+ responses["default"] = resolver.resolveResponseName(node);
263
+ return {
264
+ request: node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0,
265
+ parameters: {
266
+ path: pathParam ? resolver.resolvePathParamsName(node, pathParam) : void 0,
267
+ query: queryParam ? resolver.resolveQueryParamsName(node, queryParam) : void 0,
268
+ header: headerParam ? resolver.resolveHeaderParamsName(node, headerParam) : void 0
269
+ },
270
+ responses,
271
+ errors
272
+ };
273
+ }
274
+ /**
275
+ * Format a default value as a code-level literal.
276
+ * Objects become `{}`, primitives become their string representation, strings are quoted.
277
+ */
278
+ function formatDefault(value) {
279
+ if (typeof value === "string") return stringify(value);
280
+ if (typeof value === "object" && value !== null) return "{}";
281
+ return String(value ?? "");
282
+ }
283
+ /**
284
+ * Format a primitive enum/literal value.
285
+ * Strings are quoted; numbers and booleans are emitted raw.
286
+ */
287
+ function formatLiteral(v) {
288
+ if (typeof v === "string") return stringify(v);
289
+ return String(v);
290
+ }
291
+ /**
292
+ * Build `.min()` / `.max()` / `.gt()` / `.lt()` constraint chains for numbers
293
+ * using the standard chainable Zod v4 API.
294
+ */
295
+ function numberConstraints({ min, max, exclusiveMinimum, exclusiveMaximum, multipleOf }) {
296
+ return [
297
+ min !== void 0 ? `.min(${min})` : "",
298
+ max !== void 0 ? `.max(${max})` : "",
299
+ exclusiveMinimum !== void 0 ? `.gt(${exclusiveMinimum})` : "",
300
+ exclusiveMaximum !== void 0 ? `.lt(${exclusiveMaximum})` : "",
301
+ multipleOf !== void 0 ? `.multipleOf(${multipleOf})` : ""
302
+ ].join("");
303
+ }
304
+ /**
305
+ * Build `.min()` / `.max()` / `.regex()` chains for strings/arrays
306
+ * using the standard chainable Zod v4 API.
307
+ */
308
+ function lengthConstraints({ min, max, pattern }) {
309
+ return [
310
+ min !== void 0 ? `.min(${min})` : "",
311
+ max !== void 0 ? `.max(${max})` : "",
312
+ pattern !== void 0 ? `.regex(${toRegExpString(pattern, null)})` : ""
313
+ ].join("");
314
+ }
315
+ /**
316
+ * Build `.check(z.minimum(), z.maximum())` for `zod/mini` numeric constraints.
317
+ */
318
+ function numberChecksMini({ min, max, exclusiveMinimum, exclusiveMaximum, multipleOf }) {
319
+ const checks = [];
320
+ if (min !== void 0) checks.push(`z.minimum(${min})`);
321
+ if (max !== void 0) checks.push(`z.maximum(${max})`);
322
+ if (exclusiveMinimum !== void 0) checks.push(`z.minimum(${exclusiveMinimum}, { exclusive: true })`);
323
+ if (exclusiveMaximum !== void 0) checks.push(`z.maximum(${exclusiveMaximum}, { exclusive: true })`);
324
+ if (multipleOf !== void 0) checks.push(`z.multipleOf(${multipleOf})`);
325
+ return checks.length ? `.check(${checks.join(", ")})` : "";
326
+ }
327
+ /**
328
+ * Build `.check(z.minLength(), z.maxLength(), z.regex())` for `zod/mini` length constraints.
329
+ */
330
+ function lengthChecksMini({ min, max, pattern }) {
331
+ const checks = [];
332
+ if (min !== void 0) checks.push(`z.minLength(${min})`);
333
+ if (max !== void 0) checks.push(`z.maxLength(${max})`);
334
+ if (pattern !== void 0) checks.push(`z.regex(${toRegExpString(pattern, null)})`);
335
+ return checks.length ? `.check(${checks.join(", ")})` : "";
336
+ }
337
+ /**
338
+ * Apply nullable / optional / nullish modifiers and an optional `.describe()` call
339
+ * to a schema value string using the chainable Zod v4 API.
340
+ */
341
+ function applyModifiers({ value, nullable, optional, nullish, defaultValue, description }) {
342
+ let result = value;
343
+ if (nullish || nullable && optional) result = `${result}.nullish()`;
344
+ else if (optional) result = `${result}.optional()`;
345
+ else if (nullable) result = `${result}.nullable()`;
346
+ if (defaultValue !== void 0) result = `${result}.default(${formatDefault(defaultValue)})`;
347
+ if (description) result = `${result}.describe(${stringify(description)})`;
348
+ return result;
349
+ }
350
+ /**
351
+ * Apply nullable / optional / nullish modifiers using the functional `zod/mini` API
352
+ * (`z.nullable()`, `z.optional()`, `z.nullish()`).
353
+ */
354
+ function applyMiniModifiers({ value, nullable, optional, nullish, defaultValue }) {
355
+ let result = value;
356
+ if (nullish) result = `z.nullish(${result})`;
357
+ else {
358
+ if (nullable) result = `z.nullable(${result})`;
359
+ if (optional) result = `z.optional(${result})`;
360
+ }
361
+ if (defaultValue !== void 0) result = `z._default(${result}, ${formatDefault(defaultValue)})`;
362
+ return result;
363
+ }
364
+ //#endregion
365
+ //#region src/printers/printerZod.ts
366
+ function strictOneOfMember$1(member, node) {
367
+ if (node.type === "object" && node.additionalProperties === void 0) return `${member}.strict()`;
368
+ if (node.type === "ref") {
369
+ if (member.startsWith("z.lazy(")) return member;
370
+ const schema = ast.syncSchemaRef(node);
371
+ if (schema.type === "object" && (schema.additionalProperties === void 0 || schema.additionalProperties === false)) return `${member}.strict()`;
372
+ }
373
+ return member;
374
+ }
375
+ __name(strictOneOfMember$1, "strictOneOfMember");
376
+ /**
377
+ * Zod v4 printer built with `definePrinter`.
378
+ *
379
+ * Converts a `SchemaNode` AST into a Zod v4 code string using the chainable API
380
+ * (`.optional()`, `.nullable()`, `.omit()`, etc.). For improved tree-shaking, see {@link printerZodMini}.
381
+ *
382
+ * @example Chainable API
383
+ * ```ts
384
+ * const printer = printerZod({ coercion: false })
385
+ * const code = printer.print(stringNode) // "z.string()"
386
+ * ```
387
+ */
388
+ const printerZod = ast.definePrinter((options) => {
389
+ return {
390
+ name: "zod",
391
+ options,
392
+ nodes: {
393
+ any: () => "z.any()",
394
+ unknown: () => "z.unknown()",
395
+ void: () => "z.void()",
396
+ never: () => "z.never()",
397
+ boolean: () => "z.boolean()",
398
+ null: () => "z.null()",
399
+ string(node) {
400
+ return `${shouldCoerce(this.options.coercion, "strings") ? "z.coerce.string()" : "z.string()"}${lengthConstraints(node)}`;
401
+ },
402
+ number(node) {
403
+ return `${shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.number()" : "z.number()"}${numberConstraints(node)}`;
404
+ },
405
+ integer(node) {
406
+ return `${shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.number().int()" : "z.int()"}${numberConstraints(node)}`;
407
+ },
408
+ bigint() {
409
+ return shouldCoerce(this.options.coercion, "numbers") ? "z.coerce.bigint()" : "z.bigint()";
410
+ },
411
+ date(node) {
412
+ if (node.representation === "string") return "z.iso.date()";
413
+ return shouldCoerce(this.options.coercion, "dates") ? "z.coerce.date()" : "z.date()";
414
+ },
415
+ datetime(node) {
416
+ const offset = node.offset || this.options.dateType === "stringOffset";
417
+ const local = node.local || this.options.dateType === "stringLocal";
418
+ if (offset) return "z.iso.datetime({ offset: true })";
419
+ if (local) return "z.iso.datetime({ local: true })";
420
+ return "z.iso.datetime()";
421
+ },
422
+ time(node) {
423
+ if (node.representation === "string") return "z.iso.time()";
424
+ return shouldCoerce(this.options.coercion, "dates") ? "z.coerce.date()" : "z.date()";
425
+ },
426
+ uuid(node) {
427
+ return `${this.options.guidType === "guid" ? "z.guid()" : "z.uuid()"}${lengthConstraints(node)}`;
428
+ },
429
+ email(node) {
430
+ return `z.email()${lengthConstraints(node)}`;
431
+ },
432
+ url(node) {
433
+ return `z.url()${lengthConstraints(node)}`;
434
+ },
435
+ ipv4: () => "z.ipv4()",
436
+ ipv6: () => "z.ipv6()",
437
+ blob: () => "z.instanceof(File)",
438
+ enum(node) {
439
+ const nonNullValues = (node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? []).filter((v) => v !== null);
440
+ if (node.namedEnumValues?.length) {
441
+ const literals = nonNullValues.map((v) => `z.literal(${formatLiteral(v)})`);
442
+ if (literals.length === 1) return literals[0];
443
+ return `z.union([${literals.join(", ")}])`;
444
+ }
445
+ return `z.enum([${nonNullValues.map(formatLiteral).join(", ")}])`;
446
+ },
447
+ ref(node) {
448
+ if (!node.name) return void 0;
449
+ const refName = node.ref ? ast.extractRefName(node.ref) ?? node.name : node.name;
450
+ const resolvedName = node.ref ? this.options.resolver?.default(refName, "function") ?? refName : node.name;
451
+ if (node.ref && this.options.cyclicSchemas?.has(refName)) return `z.lazy(() => ${resolvedName})`;
452
+ return resolvedName;
453
+ },
454
+ object(node) {
455
+ let result = `z.object({\n ${node.properties.map((prop) => {
456
+ const { name: propName, schema } = prop;
457
+ const meta = ast.syncSchemaRef(schema);
458
+ const isNullable = meta.nullable;
459
+ const isOptional = schema.optional;
460
+ const isNullish = schema.nullish;
461
+ const hasSelfRef = this.options.cyclicSchemas != null && ast.containsCircularRef(schema, { circularSchemas: this.options.cyclicSchemas });
462
+ if (hasSelfRef) this.options.cyclicSchemas = void 0;
463
+ const baseOutput = this.transform(schema) ?? this.transform(ast.createSchema({ type: "unknown" }));
464
+ if (hasSelfRef) this.options.cyclicSchemas = options.cyclicSchemas;
465
+ const wrappedOutput = this.options.wrapOutput ? this.options.wrapOutput({
466
+ output: baseOutput,
467
+ schema
468
+ }) || baseOutput : baseOutput;
469
+ let descriptionToApply = meta.description;
470
+ if (schema.type !== "ref" && meta.type === "ref") descriptionToApply = void 0;
471
+ const value = applyModifiers({
472
+ value: wrappedOutput,
473
+ nullable: isNullable,
474
+ optional: isOptional,
475
+ nullish: isNullish,
476
+ defaultValue: meta.default,
477
+ description: descriptionToApply
478
+ });
479
+ if (hasSelfRef) return `get "${propName}"() { return ${value} }`;
480
+ return `"${propName}": ${value}`;
481
+ }).join(",\n ")}\n })`;
482
+ if (node.additionalProperties && node.additionalProperties !== true) {
483
+ const catchallType = this.transform(node.additionalProperties);
484
+ if (catchallType) result += `.catchall(${catchallType})`;
485
+ } else if (node.additionalProperties === true) result += `.catchall(${this.transform(ast.createSchema({ type: "unknown" }))})`;
486
+ else if (node.additionalProperties === false) result += ".strict()";
487
+ return result;
488
+ },
489
+ array(node) {
490
+ let result = `z.array(${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ") || this.transform(ast.createSchema({ type: "unknown" }))})${lengthConstraints(node)}`;
491
+ if (node.unique) result += `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`;
492
+ return result;
493
+ },
494
+ tuple(node) {
495
+ return `z.tuple([${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ")}])`;
496
+ },
497
+ union(node) {
498
+ const nodeMembers = node.members ?? [];
499
+ const members = nodeMembers.map((memberNode) => {
500
+ const member = this.transform(memberNode);
501
+ return member && node.strategy === "one" ? strictOneOfMember$1(member, memberNode) : member;
502
+ }).filter(Boolean);
503
+ if (members.length === 0) return "";
504
+ if (members.length === 1) return members[0];
505
+ if (node.discriminatorPropertyName && !nodeMembers.some((m) => m.type === "intersection")) return `z.discriminatedUnion(${stringify(node.discriminatorPropertyName)}, [${members.join(", ")}])`;
506
+ return `z.union([${members.join(", ")}])`;
507
+ },
508
+ intersection(node) {
509
+ const members = node.members ?? [];
510
+ if (members.length === 0) return "";
511
+ const [first, ...rest] = members;
512
+ if (!first) return "";
513
+ let base = this.transform(first);
514
+ if (!base) return "";
515
+ for (const member of rest) {
516
+ if (member.primitive === "string") {
517
+ const c = lengthConstraints(ast.narrowSchema(member, "string") ?? {});
518
+ if (c) {
519
+ base += c;
520
+ continue;
521
+ }
522
+ } else if (member.primitive === "number" || member.primitive === "integer") {
523
+ const c = numberConstraints(ast.narrowSchema(member, "number") ?? ast.narrowSchema(member, "integer") ?? {});
524
+ if (c) {
525
+ base += c;
526
+ continue;
527
+ }
528
+ } else if (member.primitive === "array") {
529
+ const c = lengthConstraints(ast.narrowSchema(member, "array") ?? {});
530
+ if (c) {
531
+ base += c;
532
+ continue;
533
+ }
534
+ }
535
+ const transformed = this.transform(member);
536
+ if (transformed) base = `${base}.and(${transformed})`;
537
+ }
538
+ return base;
539
+ },
540
+ ...options.nodes
541
+ },
542
+ print(node) {
543
+ const { keysToOmit } = this.options;
544
+ let base = this.transform(node);
545
+ if (!base) return null;
546
+ const meta = ast.syncSchemaRef(node);
547
+ if (keysToOmit?.length && meta.primitive === "object" && !(meta.type === "union" && meta.discriminatorPropertyName)) {
548
+ const lazyMatch = base.match(/^z\.lazy\(\(\)\s*=>\s*(.+)\)$/);
549
+ if (lazyMatch) base = `z.lazy(() => ${lazyMatch[1]}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} }))`;
550
+ else base = `${base}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} })`;
551
+ }
552
+ return applyModifiers({
553
+ value: base,
554
+ nullable: meta.nullable,
555
+ optional: meta.optional,
556
+ nullish: meta.nullish,
557
+ defaultValue: meta.default,
558
+ description: meta.description
559
+ });
560
+ }
561
+ };
562
+ });
563
+ //#endregion
564
+ //#region src/printers/printerZodMini.ts
565
+ function strictOneOfMember(member, node) {
566
+ if (node.type === "object" && (node.additionalProperties === void 0 || node.additionalProperties === false)) return member.replace(/^z\.object\(/, "z.strictObject(");
567
+ return member;
568
+ }
569
+ /**
570
+ * Zod v4 **Mini** printer built with `definePrinter`.
571
+ *
572
+ * Converts a `SchemaNode` AST into a Zod v4 code string using the functional API
573
+ * (`z.optional(z.string())`) for improved tree-shaking. See {@link printerZod} for the chainable API.
574
+ *
575
+ * @example Functional Mini API
576
+ * ```ts
577
+ * const printer = printerZodMini({})
578
+ * const code = printer.print(optionalStringNode) // "z.optional(z.string())"
579
+ * ```
580
+ */
581
+ const printerZodMini = ast.definePrinter((options) => {
582
+ return {
583
+ name: "zod-mini",
584
+ options,
585
+ nodes: {
586
+ any: () => "z.any()",
587
+ unknown: () => "z.unknown()",
588
+ void: () => "z.void()",
589
+ never: () => "z.never()",
590
+ boolean: () => "z.boolean()",
591
+ null: () => "z.null()",
592
+ string(node) {
593
+ return `z.string()${lengthChecksMini(node)}`;
594
+ },
595
+ number(node) {
596
+ return `z.number()${numberChecksMini(node)}`;
597
+ },
598
+ integer(node) {
599
+ return `z.int()${numberChecksMini(node)}`;
600
+ },
601
+ bigint(node) {
602
+ return `z.bigint()${numberChecksMini(node)}`;
603
+ },
604
+ date(node) {
605
+ if (node.representation === "string") return "z.iso.date()";
606
+ return "z.date()";
607
+ },
608
+ datetime() {
609
+ return "z.string()";
610
+ },
611
+ time(node) {
612
+ if (node.representation === "string") return "z.iso.time()";
613
+ return "z.date()";
614
+ },
615
+ uuid(node) {
616
+ return `${this.options.guidType === "guid" ? "z.guid()" : "z.uuid()"}${lengthChecksMini(node)}`;
617
+ },
618
+ email(node) {
619
+ return `z.email()${lengthChecksMini(node)}`;
620
+ },
621
+ url(node) {
622
+ return `z.url()${lengthChecksMini(node)}`;
623
+ },
624
+ ipv4: () => "z.ipv4()",
625
+ ipv6: () => "z.ipv6()",
626
+ blob: () => "z.instanceof(File)",
627
+ enum(node) {
628
+ const nonNullValues = (node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? []).filter((v) => v !== null);
629
+ if (node.namedEnumValues?.length) {
630
+ const literals = nonNullValues.map((v) => `z.literal(${formatLiteral(v)})`);
631
+ if (literals.length === 1) return literals[0];
632
+ return `z.union([${literals.join(", ")}])`;
633
+ }
634
+ return `z.enum([${nonNullValues.map(formatLiteral).join(", ")}])`;
635
+ },
636
+ ref(node) {
637
+ if (!node.name) return void 0;
638
+ const refName = node.ref ? ast.extractRefName(node.ref) ?? node.name : node.name;
639
+ const resolvedName = node.ref ? this.options.resolver?.default(refName, "function") ?? refName : node.name;
640
+ if (node.ref && this.options.cyclicSchemas?.has(refName)) return `z.lazy(() => ${resolvedName})`;
641
+ return resolvedName;
642
+ },
643
+ object(node) {
644
+ return `z.object({\n ${node.properties.map((prop) => {
645
+ const { name: propName, schema } = prop;
646
+ const meta = ast.syncSchemaRef(schema);
647
+ const isNullable = meta.nullable;
648
+ const isOptional = schema.optional;
649
+ const isNullish = schema.nullish;
650
+ const hasSelfRef = this.options.cyclicSchemas != null && ast.containsCircularRef(schema, { circularSchemas: this.options.cyclicSchemas });
651
+ if (hasSelfRef) this.options.cyclicSchemas = void 0;
652
+ const baseOutput = this.transform(schema) ?? this.transform(ast.createSchema({ type: "unknown" }));
653
+ if (hasSelfRef) this.options.cyclicSchemas = options.cyclicSchemas;
654
+ const value = applyMiniModifiers({
655
+ value: this.options.wrapOutput ? this.options.wrapOutput({
656
+ output: baseOutput,
657
+ schema
658
+ }) || baseOutput : baseOutput,
659
+ nullable: isNullable,
660
+ optional: isOptional,
661
+ nullish: isNullish,
662
+ defaultValue: meta.default
663
+ });
664
+ if (hasSelfRef) return `get "${propName}"() { return ${value} }`;
665
+ return `"${propName}": ${value}`;
666
+ }).join(",\n ")}\n })`;
667
+ },
668
+ array(node) {
669
+ let result = `z.array(${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ") || this.transform(ast.createSchema({ type: "unknown" }))})${lengthChecksMini(node)}`;
670
+ if (node.unique) result += `.refine(items => new Set(items).size === items.length, { message: "Array entries must be unique" })`;
671
+ return result;
672
+ },
673
+ tuple(node) {
674
+ return `z.tuple([${(node.items ?? []).map((item) => this.transform(item)).filter(Boolean).join(", ")}])`;
675
+ },
676
+ union(node) {
677
+ const nodeMembers = node.members ?? [];
678
+ const members = nodeMembers.map((memberNode) => {
679
+ const member = this.transform(memberNode);
680
+ return member && node.strategy === "one" ? strictOneOfMember(member, memberNode) : member;
681
+ }).filter(Boolean);
682
+ if (members.length === 0) return "";
683
+ if (members.length === 1) return members[0];
684
+ if (node.discriminatorPropertyName && !nodeMembers.some((m) => m.type === "intersection")) return `z.discriminatedUnion(${stringify(node.discriminatorPropertyName)}, [${members.join(", ")}])`;
685
+ return `z.union([${members.join(", ")}])`;
686
+ },
687
+ intersection(node) {
688
+ const members = node.members ?? [];
689
+ if (members.length === 0) return "";
690
+ const [first, ...rest] = members;
691
+ if (!first) return "";
692
+ let base = this.transform(first);
693
+ if (!base) return "";
694
+ for (const member of rest) {
695
+ if (member.primitive === "string") {
696
+ const c = lengthChecksMini(ast.narrowSchema(member, "string") ?? {});
697
+ if (c) {
698
+ base += c;
699
+ continue;
700
+ }
701
+ } else if (member.primitive === "number" || member.primitive === "integer") {
702
+ const c = numberChecksMini(ast.narrowSchema(member, "number") ?? ast.narrowSchema(member, "integer") ?? {});
703
+ if (c) {
704
+ base += c;
705
+ continue;
706
+ }
707
+ } else if (member.primitive === "array") {
708
+ const c = lengthChecksMini(ast.narrowSchema(member, "array") ?? {});
709
+ if (c) {
710
+ base += c;
711
+ continue;
712
+ }
713
+ }
714
+ const transformed = this.transform(member);
715
+ if (transformed) base = `z.intersection(${base}, ${transformed})`;
716
+ }
717
+ return base;
718
+ },
719
+ ...options.nodes
720
+ },
721
+ print(node) {
722
+ const { keysToOmit } = this.options;
723
+ let base = this.transform(node);
724
+ if (!base) return null;
725
+ const meta = ast.syncSchemaRef(node);
726
+ if (keysToOmit?.length && meta.primitive === "object" && !(meta.type === "union" && meta.discriminatorPropertyName)) {
727
+ const lazyMatch = base.match(/^z\.lazy\(\(\)\s*=>\s*(.+)\)$/);
728
+ if (lazyMatch) base = `z.lazy(() => ${lazyMatch[1]}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} }))`;
729
+ else base = `${base}.omit({ ${keysToOmit.map((k) => `"${k}": true`).join(", ")} })`;
730
+ }
731
+ return applyMiniModifiers({
732
+ value: base,
733
+ nullable: meta.nullable,
734
+ optional: meta.optional,
735
+ nullish: meta.nullish,
736
+ defaultValue: meta.default
737
+ });
738
+ }
739
+ };
740
+ });
741
+ //#endregion
742
+ //#region src/generators/zodGenerator.tsx
743
+ const zodGenerator = defineGenerator({
744
+ name: "zod",
745
+ renderer: jsxRenderer,
746
+ schema(node, ctx) {
747
+ const { adapter, config, resolver, root } = ctx;
748
+ const { output, coercion, guidType, mini, wrapOutput, inferred, importPath, group, printer } = ctx.options;
749
+ const dateType = adapter.options.dateType;
750
+ if (!node.name) return;
751
+ const mode = ctx.getMode(output);
752
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
753
+ const imports = adapter.getImports(node, (schemaName) => ({
754
+ name: resolver.resolveSchemaName(schemaName),
755
+ path: resolver.resolveFile({
756
+ name: schemaName,
757
+ extname: ".ts"
758
+ }, {
759
+ root,
760
+ output,
761
+ group
762
+ }).path
763
+ }));
764
+ const meta = {
765
+ name: resolver.resolveSchemaName(node.name),
766
+ file: resolver.resolveFile({
767
+ name: node.name,
768
+ extname: ".ts"
769
+ }, {
770
+ root,
771
+ output,
772
+ group
773
+ })
774
+ };
775
+ const inferTypeName = inferred ? resolver.resolveSchemaTypeName(node.name) : void 0;
776
+ const cyclicSchemas = adapter.inputNode ? ast.findCircularSchemas(adapter.inputNode.schemas) : void 0;
777
+ const schemaPrinter = mini ? printerZodMini({
778
+ guidType,
779
+ wrapOutput,
780
+ resolver,
781
+ cyclicSchemas,
782
+ nodes: printer?.nodes
783
+ }) : printerZod({
784
+ coercion,
785
+ guidType,
786
+ dateType,
787
+ wrapOutput,
788
+ resolver,
789
+ cyclicSchemas,
790
+ nodes: printer?.nodes
791
+ });
792
+ return /* @__PURE__ */ jsxs(File, {
793
+ baseName: meta.file.baseName,
794
+ path: meta.file.path,
795
+ meta: meta.file.meta,
796
+ banner: resolver.resolveBanner(adapter.inputNode, {
797
+ output,
798
+ config
799
+ }),
800
+ footer: resolver.resolveFooter(adapter.inputNode, {
801
+ output,
802
+ config
803
+ }),
804
+ children: [
805
+ /* @__PURE__ */ jsx(File.Import, {
806
+ name: isZodImport ? "z" : ["z"],
807
+ path: importPath,
808
+ isNameSpace: isZodImport
809
+ }),
810
+ mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
811
+ root: meta.file.path,
812
+ path: imp.path,
813
+ name: imp.name
814
+ }, [node.name, imp.path].join("-"))),
815
+ /* @__PURE__ */ jsx(Zod, {
816
+ name: meta.name,
817
+ node,
818
+ printer: schemaPrinter,
819
+ inferTypeName
820
+ })
821
+ ]
822
+ });
823
+ },
824
+ operation(node, ctx) {
825
+ const { adapter, config, resolver, root } = ctx;
826
+ const { output, coercion, guidType, mini, wrapOutput, inferred, importPath, group, paramsCasing, printer } = ctx.options;
827
+ const dateType = adapter.options.dateType;
828
+ const mode = ctx.getMode(output);
829
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
830
+ const params = ast.caseParams(node.parameters, paramsCasing);
831
+ const meta = { file: resolver.resolveFile({
832
+ name: node.operationId,
833
+ extname: ".ts",
834
+ tag: node.tags[0] ?? "default",
835
+ path: node.path
836
+ }, {
837
+ root,
838
+ output,
839
+ group
840
+ }) };
841
+ const cyclicSchemas = adapter.inputNode ? ast.findCircularSchemas(adapter.inputNode.schemas) : void 0;
842
+ function renderSchemaEntry({ schema, name, keysToOmit }) {
843
+ if (!schema) return null;
844
+ const inferTypeName = inferred ? resolver.resolveTypeName(name) : void 0;
845
+ const imports = adapter.getImports(schema, (schemaName) => ({
846
+ name: resolver.resolveSchemaName(schemaName),
847
+ path: resolver.resolveFile({
848
+ name: schemaName,
849
+ extname: ".ts"
850
+ }, {
851
+ root,
852
+ output,
853
+ group
854
+ }).path
855
+ }));
856
+ const schemaPrinter = mini ? printerZodMini({
857
+ guidType,
858
+ wrapOutput,
859
+ resolver,
860
+ keysToOmit,
861
+ cyclicSchemas,
862
+ nodes: printer?.nodes
863
+ }) : printerZod({
864
+ coercion,
865
+ guidType,
866
+ dateType,
867
+ wrapOutput,
868
+ resolver,
869
+ keysToOmit,
870
+ cyclicSchemas,
871
+ nodes: printer?.nodes
872
+ });
873
+ return /* @__PURE__ */ jsxs(Fragment, { children: [mode === "split" && imports.map((imp) => /* @__PURE__ */ jsx(File.Import, {
874
+ root: meta.file.path,
875
+ path: imp.path,
876
+ name: imp.name
877
+ }, [
878
+ name,
879
+ imp.path,
880
+ imp.name
881
+ ].join("-"))), /* @__PURE__ */ jsx(Zod, {
882
+ name,
883
+ node: schema,
884
+ printer: schemaPrinter,
885
+ inferTypeName
886
+ })] });
887
+ }
888
+ const paramSchemas = params.map((param) => renderSchemaEntry({
889
+ schema: param.schema,
890
+ name: resolver.resolveParamName(node, param)
891
+ }));
892
+ const responseSchemas = node.responses.map((res) => renderSchemaEntry({
893
+ schema: res.schema,
894
+ name: resolver.resolveResponseStatusName(node, res.statusCode),
895
+ keysToOmit: res.keysToOmit
896
+ }));
897
+ const responsesWithSchema = node.responses.filter((res) => res.schema);
898
+ const responseUnionSchema = responsesWithSchema.length > 0 ? (() => {
899
+ const responseUnionName = resolver.resolveResponseName(node);
900
+ if (new Set(responsesWithSchema.flatMap((res) => res.schema ? adapter.getImports(res.schema, (schemaName) => ({
901
+ name: resolver.resolveSchemaName(schemaName),
902
+ path: ""
903
+ })).flatMap((imp) => Array.isArray(imp.name) ? imp.name : [imp.name]) : [])).has(responseUnionName)) return null;
904
+ const members = responsesWithSchema.map((res) => ast.createSchema({
905
+ type: "ref",
906
+ name: resolver.resolveResponseStatusName(node, res.statusCode)
907
+ }));
908
+ return renderSchemaEntry({
909
+ schema: members.length === 1 ? members[0] : ast.createSchema({
910
+ type: "union",
911
+ members
912
+ }),
913
+ name: responseUnionName
914
+ });
915
+ })() : null;
916
+ const requestSchema = node.requestBody?.content?.[0]?.schema ? renderSchemaEntry({
917
+ schema: {
918
+ ...node.requestBody.content[0].schema,
919
+ description: node.requestBody.description ?? node.requestBody.content[0].schema.description
920
+ },
921
+ name: resolver.resolveDataName(node),
922
+ keysToOmit: node.requestBody.content[0].keysToOmit
923
+ }) : null;
924
+ return /* @__PURE__ */ jsxs(File, {
925
+ baseName: meta.file.baseName,
926
+ path: meta.file.path,
927
+ meta: meta.file.meta,
928
+ banner: resolver.resolveBanner(adapter.inputNode, {
929
+ output,
930
+ config
931
+ }),
932
+ footer: resolver.resolveFooter(adapter.inputNode, {
933
+ output,
934
+ config
935
+ }),
936
+ children: [
937
+ /* @__PURE__ */ jsx(File.Import, {
938
+ name: isZodImport ? "z" : ["z"],
939
+ path: importPath,
940
+ isNameSpace: isZodImport
941
+ }),
942
+ paramSchemas,
943
+ responseSchemas,
944
+ responseUnionSchema,
945
+ requestSchema
946
+ ]
947
+ });
948
+ },
949
+ operations(nodes, ctx) {
950
+ const { adapter, config, resolver, root } = ctx;
951
+ const { output, importPath, group, operations, paramsCasing } = ctx.options;
952
+ if (!operations) return;
953
+ const isZodImport = ZOD_NAMESPACE_IMPORTS.has(importPath);
954
+ const meta = { file: resolver.resolveFile({
955
+ name: "operations",
956
+ extname: ".ts"
957
+ }, {
958
+ root,
959
+ output,
960
+ group
961
+ }) };
962
+ const transformedOperations = nodes.map((node) => {
963
+ return {
964
+ node,
965
+ data: buildSchemaNames(node, {
966
+ params: ast.caseParams(node.parameters, paramsCasing),
967
+ resolver
968
+ })
969
+ };
970
+ });
971
+ const imports = transformedOperations.flatMap(({ node, data }) => {
972
+ const names = [
973
+ data.request,
974
+ ...Object.values(data.responses),
975
+ ...Object.values(data.parameters)
976
+ ].filter(Boolean);
977
+ const opFile = resolver.resolveFile({
978
+ name: node.operationId,
979
+ extname: ".ts",
980
+ tag: node.tags[0] ?? "default",
981
+ path: node.path
982
+ }, {
983
+ root,
984
+ output,
985
+ group
986
+ });
987
+ return names.map((name) => /* @__PURE__ */ jsx(File.Import, {
988
+ name: [name],
989
+ root: meta.file.path,
990
+ path: opFile.path
991
+ }, [name, opFile.path].join("-")));
992
+ });
993
+ return /* @__PURE__ */ jsxs(File, {
994
+ baseName: meta.file.baseName,
995
+ path: meta.file.path,
996
+ meta: meta.file.meta,
997
+ banner: resolver.resolveBanner(adapter.inputNode, {
998
+ output,
999
+ config
1000
+ }),
1001
+ footer: resolver.resolveFooter(adapter.inputNode, {
1002
+ output,
1003
+ config
1004
+ }),
1005
+ children: [
1006
+ /* @__PURE__ */ jsx(File.Import, {
1007
+ isTypeOnly: true,
1008
+ name: isZodImport ? "z" : ["z"],
1009
+ path: importPath,
1010
+ isNameSpace: isZodImport
1011
+ }),
1012
+ imports,
1013
+ /* @__PURE__ */ jsx(Operations, {
1014
+ name: "operations",
1015
+ operations: transformedOperations
1016
+ })
1017
+ ]
1018
+ });
1019
+ }
1020
+ });
1021
+ //#endregion
1022
+ //#region src/resolvers/resolverZod.ts
1023
+ /**
1024
+ * Naming convention resolver for Zod plugin.
1025
+ *
1026
+ * Provides default naming helpers using camelCase with a `Schema` suffix for schemas.
1027
+ *
1028
+ * @example
1029
+ * `resolverZod.default('list pets', 'function') // → 'listPetsSchema'`
1030
+ */
1031
+ const resolverZod = defineResolver(() => {
1032
+ return {
1033
+ name: "default",
1034
+ pluginName: "plugin-zod",
1035
+ default(name, type) {
1036
+ return camelCase(name, {
1037
+ isFile: type === "file",
1038
+ suffix: type ? "schema" : void 0
1039
+ });
1040
+ },
1041
+ resolveSchemaName(name) {
1042
+ return camelCase(name, { suffix: "schema" });
1043
+ },
1044
+ resolveSchemaTypeName(name) {
1045
+ return pascalCase(name, { suffix: "schema" });
1046
+ },
1047
+ resolveTypeName(name) {
1048
+ return pascalCase(name);
1049
+ },
1050
+ resolvePathName(name, type) {
1051
+ return this.default(name, type);
1052
+ },
1053
+ resolveParamName(node, param) {
1054
+ return this.resolveSchemaName(`${node.operationId} ${param.in} ${param.name}`);
1055
+ },
1056
+ resolveResponseStatusName(node, statusCode) {
1057
+ return this.resolveSchemaName(`${node.operationId} Status ${statusCode}`);
1058
+ },
1059
+ resolveDataName(node) {
1060
+ return this.resolveSchemaName(`${node.operationId} Data`);
1061
+ },
1062
+ resolveResponsesName(node) {
1063
+ return this.resolveSchemaName(`${node.operationId} Responses`);
1064
+ },
1065
+ resolveResponseName(node) {
1066
+ return this.resolveSchemaName(`${node.operationId} Response`);
1067
+ },
1068
+ resolvePathParamsName(node, param) {
1069
+ return this.resolveParamName(node, param);
1070
+ },
1071
+ resolveQueryParamsName(node, param) {
1072
+ return this.resolveParamName(node, param);
1073
+ },
1074
+ resolveHeaderParamsName(node, param) {
1075
+ return this.resolveParamName(node, param);
1076
+ }
1077
+ };
1078
+ });
1079
+ //#endregion
63
1080
  //#region src/plugin.ts
1081
+ /**
1082
+ * Canonical plugin name for `@kubb/plugin-zod`, used in driver lookups and warnings.
1083
+ */
64
1084
  const pluginZodName = "plugin-zod";
65
- const pluginZod = createPlugin((options) => {
1085
+ /**
1086
+ * Generates Zod validation schemas from an OpenAPI specification.
1087
+ * Walks schemas and operations, delegates to generators, and writes barrel files
1088
+ * based on the configured `barrelType`.
1089
+ *
1090
+ * @example Zod schema generator
1091
+ * ```ts
1092
+ * import pluginZod from '@kubb/plugin-zod'
1093
+ * export default defineConfig({
1094
+ * plugins: [pluginZod({ output: { path: 'zod' } })]
1095
+ * })
1096
+ * ```
1097
+ */
1098
+ const pluginZod = definePlugin((options) => {
66
1099
  const { output = {
67
1100
  path: "zod",
68
1101
  barrelType: "named"
69
- }, group, exclude = [], include, override = [], transformers = {}, dateType = "string", unknownType = "any", emptySchemaType = unknownType, integerType = "number", typed = false, mapper = {}, operations = false, mini = false, version = mini ? "4" : new PackageManager().isValidSync("zod", ">=4") ? "4" : "3", guidType = "uuid", importPath = mini ? "zod/mini" : version === "4" ? "zod/v4" : "zod", coercion = false, inferred = false, generators = [zodGenerator, operations ? operationsGenerator : void 0].filter(Boolean), wrapOutput = void 0, contentType } = options;
1102
+ }, group, exclude = [], include, override = [], typed = false, operations = false, mini = false, guidType = "uuid", importPath = mini ? "zod/mini" : "zod", coercion = false, inferred = false, wrapOutput = void 0, paramsCasing, printer, resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = options;
1103
+ const groupConfig = group ? {
1104
+ ...group,
1105
+ name: (ctx) => {
1106
+ if (group.type === "path") return `${ctx.group.split("/")[1]}`;
1107
+ return `${camelCase(ctx.group)}Controller`;
1108
+ }
1109
+ } : void 0;
70
1110
  return {
71
1111
  name: pluginZodName,
72
- options: {
73
- output,
74
- transformers,
75
- include,
76
- exclude,
77
- override,
78
- typed,
79
- dateType,
80
- unknownType,
81
- emptySchemaType,
82
- integerType,
83
- mapper,
84
- importPath,
85
- coercion,
86
- operations,
87
- inferred,
88
- group,
89
- wrapOutput,
90
- version,
91
- guidType,
92
- mini,
93
- usedEnumNames: {}
94
- },
95
- pre: [pluginOasName, typed ? pluginTsName : void 0].filter(Boolean),
96
- resolvePath(baseName, pathMode, options) {
97
- const root = path.resolve(this.config.root, this.config.output.path);
98
- if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single")
99
- /**
100
- * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
101
- * Other plugins then need to call addOrAppend instead of just add from the fileManager class
102
- */
103
- return path.resolve(root, output.path);
104
- if (group && (options?.group?.path || options?.group?.tag)) {
105
- const groupName = group?.name ? group.name : (ctx) => {
106
- if (group?.type === "path") return `${ctx.group.split("/")[1]}`;
107
- return `${camelCase(ctx.group)}Controller`;
108
- };
109
- return path.resolve(root, output.path, groupName({ group: group.type === "path" ? options.group.path : options.group.tag }), baseName);
110
- }
111
- return path.resolve(root, output.path, baseName);
112
- },
113
- resolveName(name, type) {
114
- let resolvedName = camelCase(name, {
115
- suffix: type ? "schema" : void 0,
116
- isFile: type === "file"
117
- });
118
- if (type === "type") resolvedName = pascalCase(resolvedName);
119
- if (type) return transformers?.name?.(resolvedName, type) || resolvedName;
120
- return resolvedName;
121
- },
122
- async install() {
123
- const root = path.resolve(this.config.root, this.config.output.path);
124
- const mode = getMode(path.resolve(root, output.path));
125
- const oas = await this.getOas();
126
- if (this.plugin.options.typed && this.plugin.options.version === "3") await this.addFile({
127
- baseName: "ToZod.ts",
128
- path: path.resolve(root, ".kubb/ToZod.ts"),
129
- sources: [{
130
- name: "ToZod",
131
- value: source
132
- }],
133
- imports: [],
134
- exports: []
135
- });
136
- const schemaFiles = await new SchemaGenerator(this.plugin.options, {
137
- fabric: this.fabric,
138
- oas,
139
- driver: this.driver,
140
- events: this.events,
141
- plugin: this.plugin,
142
- contentType,
143
- include: void 0,
144
- override,
145
- mode,
146
- output: output.path
147
- }).build(...generators);
148
- await this.upsertFile(...schemaFiles);
149
- const operationFiles = await new OperationGenerator(this.plugin.options, {
150
- fabric: this.fabric,
151
- oas,
152
- driver: this.driver,
153
- events: this.events,
154
- plugin: this.plugin,
155
- contentType,
1112
+ options,
1113
+ hooks: { "kubb:plugin:setup"(ctx) {
1114
+ ctx.setOptions({
1115
+ output,
156
1116
  exclude,
157
1117
  include,
158
1118
  override,
159
- mode
160
- }).build(...generators);
161
- await this.upsertFile(...operationFiles);
162
- const barrelFiles = await getBarrelFiles(this.fabric.files, {
163
- type: output.barrelType ?? "named",
164
- root,
165
- output,
166
- meta: { pluginName: this.plugin.name }
1119
+ group: groupConfig,
1120
+ typed,
1121
+ importPath,
1122
+ coercion,
1123
+ operations,
1124
+ inferred,
1125
+ guidType,
1126
+ mini,
1127
+ wrapOutput,
1128
+ paramsCasing,
1129
+ printer
167
1130
  });
168
- await this.upsertFile(...barrelFiles);
169
- }
1131
+ ctx.setResolver(userResolver ? {
1132
+ ...resolverZod,
1133
+ ...userResolver
1134
+ } : resolverZod);
1135
+ if (userTransformer) ctx.setTransformer(userTransformer);
1136
+ ctx.addGenerator(zodGenerator);
1137
+ for (const gen of userGenerators) ctx.addGenerator(gen);
1138
+ } }
170
1139
  };
171
1140
  });
172
1141
  //#endregion
173
- export { pluginZod, pluginZodName };
1142
+ export { pluginZod as default, pluginZod, pluginZodName, printerZod, printerZodMini, resolverZod, zodGenerator };
174
1143
 
175
1144
  //# sourceMappingURL=index.js.map