@orval/zod 7.11.2 → 7.12.2

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.
package/dist/index.js CHANGED
@@ -1,942 +1,634 @@
1
- "use strict";
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+ //#region rolldown:runtime
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
9
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
19
18
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
29
23
 
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- builder: () => builder,
34
- default: () => index_default,
35
- generateZod: () => generateZod,
36
- generateZodValidationSchemaDefinition: () => generateZodValidationSchemaDefinition,
37
- getZodDependencies: () => getZodDependencies,
38
- parseZodValidationSchemaDefinition: () => parseZodValidationSchemaDefinition
39
- });
40
- module.exports = __toCommonJS(index_exports);
41
- var import_core2 = require("@orval/core");
24
+ //#endregion
25
+ let __orval_core = require("@orval/core");
26
+ __orval_core = __toESM(__orval_core);
27
+ let lodash_uniq = require("lodash.uniq");
28
+ lodash_uniq = __toESM(lodash_uniq);
29
+ require("openapi3-ts/oas30");
30
+ require("openapi3-ts/oas31");
42
31
 
43
- // src/compatibleV4.ts
44
- var import_core = require("@orval/core");
45
- var getZodPackageVersion = (packageJson) => {
46
- var _a, _b, _c, _d, _e;
47
- return (_e = (_c = (_a = packageJson.dependencies) == null ? void 0 : _a["zod"]) != null ? _c : (_b = packageJson.devDependencies) == null ? void 0 : _b["zod"]) != null ? _e : (_d = packageJson.peerDependencies) == null ? void 0 : _d["zod"];
32
+ //#region src/compatibleV4.ts
33
+ const getZodPackageVersion = (packageJson) => {
34
+ return packageJson.dependencies?.zod ?? packageJson.devDependencies?.zod ?? packageJson.peerDependencies?.zod;
48
35
  };
49
- var isZodVersionV4 = (packageJson) => {
50
- const version = getZodPackageVersion(packageJson);
51
- if (!version) {
52
- return false;
53
- }
54
- const withoutRc = version.split("-")[0];
55
- return (0, import_core.compareVersions)(withoutRc, "4.0.0");
36
+ const isZodVersionV4 = (packageJson) => {
37
+ const version = getZodPackageVersion(packageJson);
38
+ if (!version) return false;
39
+ const withoutRc = version.split("-")[0];
40
+ return (0, __orval_core.compareVersions)(withoutRc, "4.0.0");
56
41
  };
57
- var getZodDateFormat = (isZodV4) => {
58
- return isZodV4 ? "iso.date" : "date";
42
+ const getZodDateFormat = (isZodV4) => {
43
+ return isZodV4 ? "iso.date" : "date";
59
44
  };
60
- var getZodTimeFormat = (isZodV4) => {
61
- return isZodV4 ? "iso.time" : "time";
45
+ const getZodTimeFormat = (isZodV4) => {
46
+ return isZodV4 ? "iso.time" : "time";
62
47
  };
63
- var getZodDateTimeFormat = (isZodV4) => {
64
- return isZodV4 ? "iso.datetime" : "datetime";
48
+ const getZodDateTimeFormat = (isZodV4) => {
49
+ return isZodV4 ? "iso.datetime" : "datetime";
65
50
  };
66
- var getParameterFunctions = (isZodV4, strict, parameters) => {
67
- if (isZodV4 && strict) {
68
- return [["strictObject", parameters]];
69
- } else {
70
- return strict ? [
71
- ["object", parameters],
72
- ["strict", void 0]
73
- ] : [["object", parameters]];
74
- }
51
+ const getParameterFunctions = (isZodV4, strict, parameters) => {
52
+ if (isZodV4 && strict) return [["strictObject", parameters]];
53
+ else return strict ? [["object", parameters], ["strict", void 0]] : [["object", parameters]];
75
54
  };
76
- var getObjectFunctionName = (isZodV4, strict) => {
77
- return isZodV4 && strict ? "strictObject" : "object";
55
+ const getObjectFunctionName = (isZodV4, strict) => {
56
+ return isZodV4 && strict ? "strictObject" : "object";
78
57
  };
79
58
 
80
- // src/index.ts
81
- var import_lodash = __toESM(require("lodash.uniq"));
82
- var ZOD_DEPENDENCIES = [
83
- {
84
- exports: [
85
- {
86
- name: "z",
87
- alias: "zod",
88
- values: true
89
- }
90
- ],
91
- dependency: "zod"
92
- }
93
- ];
94
- var getZodDependencies = () => ZOD_DEPENDENCIES;
95
- var possibleSchemaTypes = [
96
- "integer",
97
- "number",
98
- "string",
99
- "boolean",
100
- "object",
101
- "strictObject",
102
- "null",
103
- "array"
104
- ];
105
- var resolveZodType = (schema) => {
106
- const schemaTypeValue = schema.type;
107
- const type = Array.isArray(schemaTypeValue) ? schemaTypeValue.find((t) => possibleSchemaTypes.includes(t)) : schemaTypeValue;
108
- if (schema.type === "array" && "prefixItems" in schema) {
109
- return "tuple";
110
- }
111
- switch (type) {
112
- case "integer":
113
- return "number";
114
- default:
115
- return type != null ? type : "any";
116
- }
59
+ //#endregion
60
+ //#region src/index.ts
61
+ const ZOD_DEPENDENCIES = [{
62
+ exports: [{
63
+ name: "z",
64
+ alias: "zod",
65
+ values: true
66
+ }],
67
+ dependency: "zod"
68
+ }];
69
+ const getZodDependencies = () => ZOD_DEPENDENCIES;
70
+ /**
71
+ * values that may appear in "type". Equals SchemaObjectType
72
+ */
73
+ const possibleSchemaTypes = new Set([
74
+ "integer",
75
+ "number",
76
+ "string",
77
+ "boolean",
78
+ "object",
79
+ "strictObject",
80
+ "null",
81
+ "array"
82
+ ]);
83
+ const resolveZodType = (schema) => {
84
+ const schemaTypeValue = schema.type;
85
+ const type = Array.isArray(schemaTypeValue) ? schemaTypeValue.find((t) => possibleSchemaTypes.has(t)) : schemaTypeValue;
86
+ if (schema.type === "array" && "prefixItems" in schema) return "tuple";
87
+ switch (type) {
88
+ case "integer": return "number";
89
+ default: return type ?? "any";
90
+ }
117
91
  };
118
- var constsUniqueCounter = {};
119
- var COERCIBLE_TYPES = ["string", "number", "boolean", "bigint", "date"];
120
- var minAndMaxTypes = ["number", "string", "array"];
121
- var removeReadOnlyProperties = (schema) => {
122
- if (schema.properties) {
123
- return {
124
- ...schema,
125
- properties: Object.entries(schema.properties).reduce((acc, [key, value]) => {
126
- if ("readOnly" in value && value.readOnly) return acc;
127
- acc[key] = value;
128
- return acc;
129
- }, {})
130
- };
131
- }
132
- if (schema.items && "properties" in schema.items) {
133
- return {
134
- ...schema,
135
- items: removeReadOnlyProperties(schema.items)
136
- };
137
- }
138
- return schema;
92
+ const constsUniqueCounter = {};
93
+ const COERCIBLE_TYPES = new Set([
94
+ "string",
95
+ "number",
96
+ "boolean",
97
+ "bigint",
98
+ "date"
99
+ ]);
100
+ const minAndMaxTypes = new Set([
101
+ "number",
102
+ "string",
103
+ "array"
104
+ ]);
105
+ const removeReadOnlyProperties = (schema) => {
106
+ if (schema.properties) return {
107
+ ...schema,
108
+ properties: Object.entries(schema.properties).reduce((acc, [key, value]) => {
109
+ if ("readOnly" in value && value.readOnly) return acc;
110
+ acc[key] = value;
111
+ return acc;
112
+ }, {})
113
+ };
114
+ if (schema.items && "properties" in schema.items) return {
115
+ ...schema,
116
+ items: removeReadOnlyProperties(schema.items)
117
+ };
118
+ return schema;
139
119
  };
140
- var generateZodValidationSchemaDefinition = (schema, context, name, strict, isZodV4, rules) => {
141
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
142
- if (!schema) return { functions: [], consts: [] };
143
- const consts = [];
144
- const constsCounter = typeof constsUniqueCounter[name] === "number" ? constsUniqueCounter[name] + 1 : 0;
145
- const constsCounterValue = constsCounter ? (0, import_core2.pascal)((0, import_core2.getNumberWord)(constsCounter)) : "";
146
- constsUniqueCounter[name] = constsCounter;
147
- const functions = [];
148
- const type = resolveZodType(schema);
149
- const required = (_a = rules == null ? void 0 : rules.required) != null ? _a : false;
150
- const nullable = "nullable" in schema && schema.nullable || Array.isArray(schema.type) && schema.type.includes("null");
151
- const min = (_c = (_b = schema.minimum) != null ? _b : schema.minLength) != null ? _c : schema.minItems;
152
- const max = (_e = (_d = schema.maximum) != null ? _d : schema.maxLength) != null ? _e : schema.maxItems;
153
- const matches = (_f = schema.pattern) != null ? _f : void 0;
154
- let defaultVarName;
155
- if (schema.default !== void 0) {
156
- defaultVarName = `${name}Default${constsCounterValue}`;
157
- let defaultValue;
158
- const isDateType = schema.type === "string" && (schema.format === "date" || schema.format === "date-time") && context.output.override.useDates;
159
- if (isDateType) {
160
- defaultValue = `new Date("${(0, import_core2.escape)(schema.default)}")`;
161
- } else if ((0, import_core2.isObject)(schema.default)) {
162
- const entries = Object.entries(schema.default).map(([key, value]) => {
163
- if ((0, import_core2.isString)(value)) {
164
- return `${key}: "${(0, import_core2.escape)(value)}"`;
165
- }
166
- if (Array.isArray(value)) {
167
- const arrayItems = value.map(
168
- (item) => (0, import_core2.isString)(item) ? `"${(0, import_core2.escape)(item)}"` : `${item}`
169
- );
170
- return `${key}: [${arrayItems.join(", ")}]`;
171
- }
172
- return `${key}: ${value}`;
173
- }).join(", ");
174
- defaultValue = `{ ${entries} }`;
175
- } else {
176
- const rawStringified = (0, import_core2.stringify)(schema.default);
177
- defaultValue = rawStringified === void 0 ? "null" : rawStringified.replace(/'/g, '"');
178
- }
179
- consts.push(`export const ${defaultVarName} = ${defaultValue};`);
180
- }
181
- switch (type) {
182
- case "tuple":
183
- if ("prefixItems" in schema) {
184
- const schema31 = schema;
185
- if (schema31.prefixItems && schema31.prefixItems.length > 0) {
186
- functions.push([
187
- "tuple",
188
- schema31.prefixItems.map(
189
- (item, idx) => generateZodValidationSchemaDefinition(
190
- deference(item, context),
191
- context,
192
- (0, import_core2.camel)(`${name}-${idx}-item`),
193
- isZodV4,
194
- strict,
195
- {
196
- required: true
197
- }
198
- )
199
- )
200
- ]);
201
- if (schema.items) {
202
- if ((max || Number.POSITIVE_INFINITY) > schema31.prefixItems.length) {
203
- functions.push([
204
- "rest",
205
- generateZodValidationSchemaDefinition(
206
- schema.items,
207
- context,
208
- (0, import_core2.camel)(`${name}-item`),
209
- strict,
210
- isZodV4,
211
- {
212
- required: true
213
- }
214
- )
215
- ]);
216
- }
217
- }
218
- }
219
- }
220
- break;
221
- case "array":
222
- functions.push([
223
- "array",
224
- generateZodValidationSchemaDefinition(
225
- schema.items,
226
- context,
227
- (0, import_core2.camel)(`${name}-item`),
228
- strict,
229
- isZodV4,
230
- {
231
- required: true
232
- }
233
- )
234
- ]);
235
- break;
236
- case "string": {
237
- if (schema.enum && type === "string") {
238
- break;
239
- }
240
- if (context.output.override.useDates && (schema.format === "date" || schema.format === "date-time")) {
241
- const formatAPI = getZodDateFormat(isZodV4);
242
- functions.push([formatAPI, void 0]);
243
- break;
244
- }
245
- if (schema.format === "binary") {
246
- functions.push(["instanceof", "File"]);
247
- break;
248
- }
249
- if (isZodV4) {
250
- if (![
251
- "date",
252
- "time",
253
- "date-time",
254
- "email",
255
- "uri",
256
- "hostname",
257
- "uuid"
258
- ].includes(schema.format || "")) {
259
- if ("const" in schema) {
260
- functions.push(["literal", `"${schema.const}"`]);
261
- } else {
262
- functions.push([type, void 0]);
263
- }
264
- break;
265
- }
266
- } else {
267
- if ("const" in schema) {
268
- functions.push(["literal", `"${schema.const}"`]);
269
- } else {
270
- functions.push([type, void 0]);
271
- }
272
- }
273
- if (schema.format === "date") {
274
- const formatAPI = getZodDateFormat(isZodV4);
275
- functions.push([formatAPI, void 0]);
276
- break;
277
- }
278
- if (schema.format === "time") {
279
- const options = (_g = context.output.override.zod) == null ? void 0 : _g.timeOptions;
280
- const formatAPI = getZodTimeFormat(isZodV4);
281
- functions.push([
282
- formatAPI,
283
- options ? JSON.stringify(options) : void 0
284
- ]);
285
- break;
286
- }
287
- if (schema.format === "date-time") {
288
- const options = (_h = context.output.override.zod) == null ? void 0 : _h.dateTimeOptions;
289
- const formatAPI = getZodDateTimeFormat(isZodV4);
290
- functions.push([
291
- formatAPI,
292
- options ? JSON.stringify(options) : void 0
293
- ]);
294
- break;
295
- }
296
- if (schema.format === "email") {
297
- functions.push(["email", void 0]);
298
- break;
299
- }
300
- if (schema.format === "uri" || schema.format === "hostname") {
301
- functions.push(["url", void 0]);
302
- break;
303
- }
304
- if (schema.format === "uuid") {
305
- functions.push(["uuid", void 0]);
306
- break;
307
- }
308
- break;
309
- }
310
- case "object":
311
- default: {
312
- if (schema.allOf || schema.oneOf || schema.anyOf) {
313
- const separator = schema.allOf ? "allOf" : schema.oneOf ? "oneOf" : "anyOf";
314
- const schemas = (_j = (_i = schema.allOf) != null ? _i : schema.oneOf) != null ? _j : schema.anyOf;
315
- functions.push([
316
- separator,
317
- schemas.map(
318
- (schema2) => generateZodValidationSchemaDefinition(
319
- schema2,
320
- context,
321
- (0, import_core2.camel)(name),
322
- strict,
323
- isZodV4,
324
- {
325
- required: true
326
- }
327
- )
328
- )
329
- ]);
330
- break;
331
- }
332
- if (schema.properties) {
333
- const objectType = getObjectFunctionName(isZodV4, strict);
334
- functions.push([
335
- objectType,
336
- Object.keys(schema.properties).map((key) => {
337
- var _a2, _b2;
338
- return {
339
- [key]: generateZodValidationSchemaDefinition(
340
- (_a2 = schema.properties) == null ? void 0 : _a2[key],
341
- context,
342
- (0, import_core2.camel)(`${name}-${key}`),
343
- strict,
344
- isZodV4,
345
- {
346
- required: (_b2 = schema.required) == null ? void 0 : _b2.includes(key)
347
- }
348
- )
349
- };
350
- }).reduce((acc, curr) => ({ ...acc, ...curr }), {})
351
- ]);
352
- if (strict && !isZodV4) {
353
- functions.push(["strict", void 0]);
354
- }
355
- break;
356
- }
357
- if (schema.additionalProperties) {
358
- functions.push([
359
- "additionalProperties",
360
- generateZodValidationSchemaDefinition(
361
- (0, import_core2.isBoolean)(schema.additionalProperties) ? {} : schema.additionalProperties,
362
- context,
363
- name,
364
- strict,
365
- isZodV4,
366
- {
367
- required: true
368
- }
369
- )
370
- ]);
371
- break;
372
- }
373
- if (schema.enum) {
374
- break;
375
- }
376
- functions.push([type, void 0]);
377
- break;
378
- }
379
- }
380
- if (minAndMaxTypes.includes(type)) {
381
- if (min !== void 0) {
382
- if (min === 1) {
383
- functions.push(["min", `${min}`]);
384
- } else {
385
- consts.push(`export const ${name}Min${constsCounterValue} = ${min};
386
- `);
387
- functions.push(["min", `${name}Min${constsCounterValue}`]);
388
- }
389
- }
390
- if (max !== void 0) {
391
- consts.push(`export const ${name}Max${constsCounterValue} = ${max};
392
- `);
393
- functions.push(["max", `${name}Max${constsCounterValue}`]);
394
- }
395
- }
396
- if (matches) {
397
- const isStartWithSlash = matches.startsWith("/");
398
- const isEndWithSlash = matches.endsWith("/");
399
- const regexp = `new RegExp('${(0, import_core2.jsStringEscape)(
400
- matches.slice(isStartWithSlash ? 1 : 0, isEndWithSlash ? -1 : void 0)
401
- )}')`;
402
- consts.push(
403
- `export const ${name}RegExp${constsCounterValue} = ${regexp};
404
- `
405
- );
406
- functions.push(["regex", `${name}RegExp${constsCounterValue}`]);
407
- }
408
- if (schema.enum) {
409
- if (schema.enum.every((value) => (0, import_core2.isString)(value))) {
410
- functions.push([
411
- "enum",
412
- `[${schema.enum.map((value) => `'${(0, import_core2.escape)(value)}'`).join(", ")}]`
413
- ]);
414
- } else {
415
- functions.push([
416
- "oneOf",
417
- schema.enum.map((value) => ({
418
- functions: [
419
- ["literal", (0, import_core2.isString)(value) ? `'${(0, import_core2.escape)(value)}'` : value]
420
- ],
421
- consts: []
422
- }))
423
- ]);
424
- }
425
- }
426
- if (!required && schema.default) {
427
- functions.push(["default", defaultVarName]);
428
- } else if (!required && nullable) {
429
- functions.push(["nullish", void 0]);
430
- } else if (nullable) {
431
- functions.push(["nullable", void 0]);
432
- } else if (!required) {
433
- functions.push(["optional", void 0]);
434
- }
435
- if (schema.description) {
436
- functions.push(["describe", `'${(0, import_core2.jsStringEscape)(schema.description)}'`]);
437
- }
438
- return { functions, consts: (0, import_lodash.default)(consts) };
120
+ const generateZodValidationSchemaDefinition = (schema, context, name, strict, isZodV4, rules) => {
121
+ if (!schema) return {
122
+ functions: [],
123
+ consts: []
124
+ };
125
+ const consts = [];
126
+ const constsCounter = typeof constsUniqueCounter[name] === "number" ? constsUniqueCounter[name] + 1 : 0;
127
+ const constsCounterValue = constsCounter ? (0, __orval_core.pascal)((0, __orval_core.getNumberWord)(constsCounter)) : "";
128
+ constsUniqueCounter[name] = constsCounter;
129
+ const functions = [];
130
+ const type = resolveZodType(schema);
131
+ const required = rules?.required ?? false;
132
+ const nullable = "nullable" in schema && schema.nullable || Array.isArray(schema.type) && schema.type.includes("null");
133
+ const min = schema.minimum ?? schema.minLength ?? schema.minItems;
134
+ const max = schema.maximum ?? schema.maxLength ?? schema.maxItems;
135
+ const matches = schema.pattern ?? void 0;
136
+ let defaultVarName;
137
+ if (schema.default !== void 0) {
138
+ defaultVarName = `${name}Default${constsCounterValue}`;
139
+ let defaultValue;
140
+ if (schema.type === "string" && (schema.format === "date" || schema.format === "date-time") && context.output.override.useDates) defaultValue = `new Date("${(0, __orval_core.escape)(schema.default)}")`;
141
+ else if ((0, __orval_core.isObject)(schema.default)) defaultValue = `{ ${Object.entries(schema.default).map(([key, value]) => {
142
+ if ((0, __orval_core.isString)(value)) return `${key}: "${(0, __orval_core.escape)(value)}"`;
143
+ if (Array.isArray(value)) {
144
+ const arrayItems = value.map((item) => (0, __orval_core.isString)(item) ? `"${(0, __orval_core.escape)(item)}"` : `${item}`);
145
+ return `${key}: [${arrayItems.join(", ")}]`;
146
+ }
147
+ return `${key}: ${value}`;
148
+ }).join(", ")} }`;
149
+ else {
150
+ const rawStringified = (0, __orval_core.stringify)(schema.default);
151
+ defaultValue = rawStringified === void 0 ? "null" : rawStringified.replaceAll("'", "\"");
152
+ }
153
+ consts.push(`export const ${defaultVarName} = ${defaultValue};`);
154
+ }
155
+ switch (type) {
156
+ case "tuple":
157
+ /**
158
+ *
159
+ * > 10.3.1.1. prefixItems
160
+ * > The value of "prefixItems" MUST be a non-empty array of valid JSON Schemas.
161
+ * >
162
+ * > Validation succeeds if each element of the instance validates against the schema at the same position, if any.
163
+ * > This keyword does not constrain the length of the array. If the array is longer than this keyword's value,
164
+ * > this keyword validates only the prefix of matching length.
165
+ * >
166
+ * > This keyword produces an annotation value which is the largest index to which this keyword applied a subschema.
167
+ * > The value MAY be a boolean true if a subschema was applied to every index of the instance, such as is produced by the "items" keyword.
168
+ * > This annotation affects the behavior of "items" and "unevaluatedItems".
169
+ * >
170
+ * > Omitting this keyword has the same assertion behavior as an empty array.
171
+ */
172
+ if ("prefixItems" in schema) {
173
+ const schema31 = schema;
174
+ if (schema31.prefixItems && schema31.prefixItems.length > 0) {
175
+ functions.push(["tuple", schema31.prefixItems.map((item, idx) => generateZodValidationSchemaDefinition(deference(item, context), context, (0, __orval_core.camel)(`${name}-${idx}-item`), isZodV4, strict, { required: true }))]);
176
+ if (schema.items && (max || Number.POSITIVE_INFINITY) > schema31.prefixItems.length) functions.push(["rest", generateZodValidationSchemaDefinition(schema.items, context, (0, __orval_core.camel)(`${name}-item`), strict, isZodV4, { required: true })]);
177
+ }
178
+ }
179
+ break;
180
+ case "array":
181
+ functions.push(["array", generateZodValidationSchemaDefinition(schema.items, context, (0, __orval_core.camel)(`${name}-item`), strict, isZodV4, { required: true })]);
182
+ break;
183
+ case "string":
184
+ if (schema.enum && type === "string") break;
185
+ if (context.output.override.useDates && (schema.format === "date" || schema.format === "date-time")) {
186
+ functions.push(["date", void 0]);
187
+ break;
188
+ }
189
+ if (schema.format === "binary") {
190
+ functions.push(["instanceof", "File"]);
191
+ break;
192
+ }
193
+ if (isZodV4) {
194
+ if (![
195
+ "date",
196
+ "time",
197
+ "date-time",
198
+ "email",
199
+ "uri",
200
+ "hostname",
201
+ "uuid"
202
+ ].includes(schema.format || "")) {
203
+ if ("const" in schema) functions.push(["literal", `"${schema.const}"`]);
204
+ else functions.push([type, void 0]);
205
+ break;
206
+ }
207
+ } else if ("const" in schema) functions.push(["literal", `"${schema.const}"`]);
208
+ else functions.push([type, void 0]);
209
+ if (schema.format === "date") {
210
+ const formatAPI = getZodDateFormat(isZodV4);
211
+ functions.push([formatAPI, void 0]);
212
+ break;
213
+ }
214
+ if (schema.format === "time") {
215
+ const options = context.output.override.zod?.timeOptions;
216
+ const formatAPI = getZodTimeFormat(isZodV4);
217
+ functions.push([formatAPI, options ? JSON.stringify(options) : void 0]);
218
+ break;
219
+ }
220
+ if (schema.format === "date-time") {
221
+ const options = context.output.override.zod?.dateTimeOptions;
222
+ const formatAPI = getZodDateTimeFormat(isZodV4);
223
+ functions.push([formatAPI, options ? JSON.stringify(options) : void 0]);
224
+ break;
225
+ }
226
+ if (schema.format === "email") {
227
+ functions.push(["email", void 0]);
228
+ break;
229
+ }
230
+ if (schema.format === "uri" || schema.format === "hostname") {
231
+ functions.push(["url", void 0]);
232
+ break;
233
+ }
234
+ if (schema.format === "uuid") {
235
+ functions.push(["uuid", void 0]);
236
+ break;
237
+ }
238
+ break;
239
+ case "object":
240
+ default:
241
+ if (schema.allOf || schema.oneOf || schema.anyOf) {
242
+ const separator = schema.allOf ? "allOf" : schema.oneOf ? "oneOf" : "anyOf";
243
+ const schemas = schema.allOf ?? schema.oneOf ?? schema.anyOf;
244
+ functions.push([separator, schemas.map((schema$1) => generateZodValidationSchemaDefinition(schema$1, context, (0, __orval_core.camel)(name), strict, isZodV4, { required: true }))]);
245
+ break;
246
+ }
247
+ if (schema.properties) {
248
+ const objectType = getObjectFunctionName(isZodV4, strict);
249
+ functions.push([objectType, Object.keys(schema.properties).map((key) => ({ [key]: generateZodValidationSchemaDefinition(schema.properties?.[key], context, (0, __orval_core.camel)(`${name}-${key}`), strict, isZodV4, { required: schema.required?.includes(key) }) })).reduce((acc, curr) => ({
250
+ ...acc,
251
+ ...curr
252
+ }), {})]);
253
+ if (strict && !isZodV4) functions.push(["strict", void 0]);
254
+ break;
255
+ }
256
+ if (schema.additionalProperties) {
257
+ functions.push(["additionalProperties", generateZodValidationSchemaDefinition((0, __orval_core.isBoolean)(schema.additionalProperties) ? {} : schema.additionalProperties, context, name, strict, isZodV4, { required: true })]);
258
+ break;
259
+ }
260
+ if (schema.enum) break;
261
+ functions.push([type, void 0]);
262
+ break;
263
+ }
264
+ if (minAndMaxTypes.has(type)) {
265
+ if (min !== void 0) if (min === 1) functions.push(["min", `${min}`]);
266
+ else {
267
+ consts.push(`export const ${name}Min${constsCounterValue} = ${min};\n`);
268
+ functions.push(["min", `${name}Min${constsCounterValue}`]);
269
+ }
270
+ if (max !== void 0) {
271
+ consts.push(`export const ${name}Max${constsCounterValue} = ${max};\n`);
272
+ functions.push(["max", `${name}Max${constsCounterValue}`]);
273
+ }
274
+ }
275
+ if (matches) {
276
+ const isStartWithSlash = matches.startsWith("/");
277
+ const isEndWithSlash = matches.endsWith("/");
278
+ const regexp = `new RegExp('${(0, __orval_core.jsStringEscape)(matches.slice(isStartWithSlash ? 1 : 0, isEndWithSlash ? -1 : void 0))}')`;
279
+ consts.push(`export const ${name}RegExp${constsCounterValue} = ${regexp};\n`);
280
+ functions.push(["regex", `${name}RegExp${constsCounterValue}`]);
281
+ }
282
+ if (schema.enum) if (schema.enum.every((value) => (0, __orval_core.isString)(value))) functions.push(["enum", `[${schema.enum.map((value) => `'${(0, __orval_core.escape)(value)}'`).join(", ")}]`]);
283
+ else functions.push(["oneOf", schema.enum.map((value) => ({
284
+ functions: [["literal", (0, __orval_core.isString)(value) ? `'${(0, __orval_core.escape)(value)}'` : value]],
285
+ consts: []
286
+ }))]);
287
+ if (!required && schema.default) functions.push(["default", defaultVarName]);
288
+ else if (!required && nullable) functions.push(["nullish", void 0]);
289
+ else if (nullable) functions.push(["nullable", void 0]);
290
+ else if (!required) functions.push(["optional", void 0]);
291
+ if (schema.description) functions.push(["describe", `'${(0, __orval_core.jsStringEscape)(schema.description)}'`]);
292
+ return {
293
+ functions,
294
+ consts: (0, lodash_uniq.default)(consts)
295
+ };
439
296
  };
440
- var parseZodValidationSchemaDefinition = (input, context, coerceTypes = false, strict, isZodV4, preprocess) => {
441
- if (!input.functions.length) {
442
- return { zod: "", consts: "" };
443
- }
444
- let consts = "";
445
- const parseProperty = (property) => {
446
- const [fn, args = ""] = property;
447
- if (fn === "allOf") {
448
- return args.reduce(
449
- (acc, {
450
- functions,
451
- consts: argConsts
452
- }) => {
453
- const value2 = functions.map(parseProperty).join("");
454
- const valueWithZod = `${value2.startsWith(".") ? "zod" : ""}${value2}`;
455
- if (argConsts.length) {
456
- consts += argConsts.join("\n");
457
- }
458
- if (!acc) {
459
- acc += valueWithZod;
460
- return acc;
461
- }
462
- acc += `.and(${valueWithZod})`;
463
- return acc;
464
- },
465
- ""
466
- );
467
- }
468
- if (fn === "oneOf" || fn === "anyOf") {
469
- if (args.length === 1) {
470
- return args[0].functions.map(parseProperty).join("");
471
- }
472
- const union = args.map(
473
- ({ functions }) => {
474
- const value2 = functions.map(parseProperty).join("");
475
- const valueWithZod = `${value2.startsWith(".") ? "zod" : ""}${value2}`;
476
- return valueWithZod;
477
- }
478
- );
479
- return `.union([${union}])`;
480
- }
481
- if (fn === "additionalProperties") {
482
- const value2 = args.functions.map(parseProperty).join("");
483
- const valueWithZod = `${value2.startsWith(".") ? "zod" : ""}${value2}`;
484
- consts += args.consts;
485
- return `zod.record(zod.string(), ${valueWithZod})`;
486
- }
487
- if (fn === "object" || fn === "strictObject") {
488
- const objectType = getObjectFunctionName(isZodV4, strict);
489
- return `zod.${objectType}({
490
- ${Object.entries(args).map(([key, schema2]) => {
491
- const value2 = schema2.functions.map(parseProperty).join("");
492
- consts += schema2.consts.join("\n");
493
- return ` "${key}": ${value2.startsWith(".") ? "zod" : ""}${value2}`;
494
- }).join(",\n")}
297
+ const parseZodValidationSchemaDefinition = (input, context, coerceTypes = false, strict, isZodV4, preprocess) => {
298
+ if (input.functions.length === 0) return {
299
+ zod: "",
300
+ consts: ""
301
+ };
302
+ let consts = "";
303
+ const parseProperty = (property) => {
304
+ const [fn, args = ""] = property;
305
+ if (fn === "allOf") return args.reduce((acc, { functions, consts: argConsts }) => {
306
+ const value$1 = functions.map(parseProperty).join("");
307
+ const valueWithZod = `${value$1.startsWith(".") ? "zod" : ""}${value$1}`;
308
+ if (argConsts.length > 0) consts += argConsts.join("\n");
309
+ if (!acc) {
310
+ acc += valueWithZod;
311
+ return acc;
312
+ }
313
+ acc += `.and(${valueWithZod})`;
314
+ return acc;
315
+ }, "");
316
+ if (fn === "oneOf" || fn === "anyOf") {
317
+ if (args.length === 1) return args[0].functions.map(parseProperty).join("");
318
+ return `.union([${args.map(({ functions, consts: argConsts }) => {
319
+ const value$1 = functions.map(parseProperty).join("");
320
+ const valueWithZod = `${value$1.startsWith(".") ? "zod" : ""}${value$1}`;
321
+ consts += argConsts?.join("\n");
322
+ return valueWithZod;
323
+ })}])`;
324
+ }
325
+ if (fn === "additionalProperties") {
326
+ const value$1 = args.functions.map(parseProperty).join("");
327
+ const valueWithZod = `${value$1.startsWith(".") ? "zod" : ""}${value$1}`;
328
+ consts += args.consts;
329
+ return `zod.record(zod.string(), ${valueWithZod})`;
330
+ }
331
+ if (fn === "object" || fn === "strictObject") return `zod.${getObjectFunctionName(isZodV4, strict)}({
332
+ ${Object.entries(args).map(([key, schema$1]) => {
333
+ const value$1 = schema$1.functions.map(parseProperty).join("");
334
+ consts += schema$1.consts.join("\n");
335
+ return ` "${key}": ${value$1.startsWith(".") ? "zod" : ""}${value$1}`;
336
+ }).join(",\n")}
495
337
  })`;
496
- }
497
- if (fn === "array") {
498
- const value2 = args.functions.map(parseProperty).join("");
499
- if (typeof args.consts === "string") {
500
- consts += args.consts;
501
- } else if (Array.isArray(args.consts)) {
502
- consts += args.consts.join("\n");
503
- }
504
- return `.array(${value2.startsWith(".") ? "zod" : ""}${value2})`;
505
- }
506
- if (fn === "strict" && !isZodV4) {
507
- return ".strict()";
508
- }
509
- if (fn === "tuple") {
510
- return `zod.tuple([${args.map((x) => {
511
- const value2 = x.functions.map(parseProperty).join("");
512
- return `${value2.startsWith(".") ? "zod" : ""}${value2}`;
513
- }).join(",\n")}])`;
514
- }
515
- if (fn === "rest") {
516
- return `.rest(zod${args.functions.map(parseProperty)})`;
517
- }
518
- const shouldCoerceType = coerceTypes && (Array.isArray(coerceTypes) ? coerceTypes.includes(fn) : COERCIBLE_TYPES.includes(fn));
519
- if (fn !== "date" && shouldCoerceType || fn === "date" && shouldCoerceType && context.output.override.useDates) {
520
- return `.coerce.${fn}(${args})`;
521
- }
522
- return `.${fn}(${args})`;
523
- };
524
- consts += input.consts.join("\n");
525
- const schema = input.functions.map(parseProperty).join("");
526
- const value = preprocess ? `.preprocess(${preprocess.name}, ${schema.startsWith(".") ? "zod" : ""}${schema})` : schema;
527
- const zod = `${value.startsWith(".") ? "zod" : ""}${value}`;
528
- return { zod, consts };
338
+ if (fn === "array") {
339
+ const value$1 = args.functions.map(parseProperty).join("");
340
+ if (typeof args.consts === "string") consts += args.consts;
341
+ else if (Array.isArray(args.consts)) consts += args.consts.join("\n");
342
+ return `.array(${value$1.startsWith(".") ? "zod" : ""}${value$1})`;
343
+ }
344
+ if (fn === "strict" && !isZodV4) return ".strict()";
345
+ if (fn === "tuple") return `zod.tuple([${args.map((x) => {
346
+ const value$1 = x.functions.map(parseProperty).join("");
347
+ return `${value$1.startsWith(".") ? "zod" : ""}${value$1}`;
348
+ }).join(",\n")}])`;
349
+ if (fn === "rest") return `.rest(zod${args.functions.map(parseProperty)})`;
350
+ const shouldCoerceType = coerceTypes && (Array.isArray(coerceTypes) ? coerceTypes.includes(fn) : COERCIBLE_TYPES.has(fn));
351
+ if (fn !== "date" && shouldCoerceType || fn === "date" && shouldCoerceType && context.output.override.useDates) return `.coerce.${fn}(${args})`;
352
+ return `.${fn}(${args})`;
353
+ };
354
+ consts += input.consts.join("\n");
355
+ const schema = input.functions.map(parseProperty).join("");
356
+ const value = preprocess ? `.preprocess(${preprocess.name}, ${schema.startsWith(".") ? "zod" : ""}${schema})` : schema;
357
+ const zod = `${value.startsWith(".") ? "zod" : ""}${value}`;
358
+ if (consts?.includes(",export")) consts = consts.replaceAll(",export", "\nexport");
359
+ return {
360
+ zod,
361
+ consts
362
+ };
529
363
  };
530
- var deferenceScalar = (value, context) => {
531
- if ((0, import_core2.isObject)(value)) {
532
- return deference(value, context);
533
- } else if (Array.isArray(value)) {
534
- return value.map((item) => deferenceScalar(item, context));
535
- } else {
536
- return value;
537
- }
364
+ const deferenceScalar = (value, context) => {
365
+ if ((0, __orval_core.isObject)(value)) return deference(value, context);
366
+ else if (Array.isArray(value)) return value.map((item) => deferenceScalar(item, context));
367
+ else return value;
538
368
  };
539
- var deference = (schema, context) => {
540
- var _a;
541
- const refName = "$ref" in schema ? schema.$ref : void 0;
542
- if (refName && ((_a = context.parents) == null ? void 0 : _a.includes(refName))) {
543
- return {};
544
- }
545
- const childContext = {
546
- ...context,
547
- ...refName ? { parents: [...context.parents || [], refName] } : void 0
548
- };
549
- const { schema: resolvedSchema } = (0, import_core2.resolveRef)(
550
- schema,
551
- childContext
552
- );
553
- const resolvedSpecKey = refName ? (0, import_core2.getRefInfo)(refName, context).specKey : void 0;
554
- const resolvedContext = {
555
- ...childContext,
556
- specKey: resolvedSpecKey != null ? resolvedSpecKey : childContext.specKey
557
- };
558
- return Object.entries(resolvedSchema).reduce((acc, [key, value]) => {
559
- if (key === "properties" && (0, import_core2.isObject)(value)) {
560
- acc[key] = Object.entries(value).reduce(
561
- (props, [propKey, propSchema]) => {
562
- props[propKey] = deference(
563
- propSchema,
564
- resolvedContext
565
- );
566
- return props;
567
- },
568
- {}
569
- );
570
- } else if (key === "default" || key === "example" || key === "examples") {
571
- acc[key] = value;
572
- } else {
573
- acc[key] = deferenceScalar(value, resolvedContext);
574
- }
575
- return acc;
576
- }, {});
369
+ const deference = (schema, context) => {
370
+ const refName = "$ref" in schema ? schema.$ref : void 0;
371
+ if (refName && context.parents?.includes(refName)) return {};
372
+ const childContext = {
373
+ ...context,
374
+ ...refName ? { parents: [...context.parents || [], refName] } : void 0
375
+ };
376
+ const { schema: resolvedSchema } = (0, __orval_core.resolveRef)(schema, childContext);
377
+ const resolvedSpecKey = refName ? (0, __orval_core.getRefInfo)(refName, context).specKey : void 0;
378
+ const resolvedContext = {
379
+ ...childContext,
380
+ specKey: resolvedSpecKey ?? childContext.specKey
381
+ };
382
+ return Object.entries(resolvedSchema).reduce((acc, [key, value]) => {
383
+ if (key === "properties" && (0, __orval_core.isObject)(value)) acc[key] = Object.entries(value).reduce((props, [propKey, propSchema]) => {
384
+ props[propKey] = deference(propSchema, resolvedContext);
385
+ return props;
386
+ }, {});
387
+ else if (key === "default" || key === "example" || key === "examples") acc[key] = value;
388
+ else acc[key] = deferenceScalar(value, resolvedContext);
389
+ return acc;
390
+ }, {});
577
391
  };
578
- var parseBodyAndResponse = ({
579
- data,
580
- context,
581
- name,
582
- strict,
583
- generate,
584
- isZodV4,
585
- parseType
586
- }) => {
587
- var _a, _b, _c, _d, _e, _f, _g, _h;
588
- if (!data || !generate) {
589
- return {
590
- input: { functions: [], consts: [] },
591
- isArray: false
592
- };
593
- }
594
- const resolvedRef = (0, import_core2.resolveRef)(
595
- data,
596
- context
597
- ).schema;
598
- const schema = ((_b = (_a = resolvedRef.content) == null ? void 0 : _a["application/json"]) == null ? void 0 : _b.schema) || ((_d = (_c = resolvedRef.content) == null ? void 0 : _c["multipart/form-data"]) == null ? void 0 : _d.schema);
599
- if (!schema) {
600
- return {
601
- input: { functions: [], consts: [] },
602
- isArray: false
603
- };
604
- }
605
- const resolvedJsonSchema = deference(schema, context);
606
- if (resolvedJsonSchema.items) {
607
- const min = (_f = (_e = resolvedJsonSchema.minimum) != null ? _e : resolvedJsonSchema.minLength) != null ? _f : resolvedJsonSchema.minItems;
608
- const max = (_h = (_g = resolvedJsonSchema.maximum) != null ? _g : resolvedJsonSchema.maxLength) != null ? _h : resolvedJsonSchema.maxItems;
609
- return {
610
- input: generateZodValidationSchemaDefinition(
611
- parseType === "body" ? removeReadOnlyProperties(resolvedJsonSchema.items) : resolvedJsonSchema.items,
612
- context,
613
- name,
614
- strict,
615
- isZodV4,
616
- {
617
- required: true
618
- }
619
- ),
620
- isArray: true,
621
- rules: {
622
- ...typeof min !== "undefined" ? { min } : {},
623
- ...typeof max !== "undefined" ? { max } : {}
624
- }
625
- };
626
- }
627
- return {
628
- input: generateZodValidationSchemaDefinition(
629
- parseType === "body" ? removeReadOnlyProperties(resolvedJsonSchema) : resolvedJsonSchema,
630
- context,
631
- name,
632
- strict,
633
- isZodV4,
634
- {
635
- required: true
636
- }
637
- ),
638
- isArray: false
639
- };
392
+ const parseBodyAndResponse = ({ data, context, name, strict, generate, isZodV4, parseType }) => {
393
+ if (!data || !generate) return {
394
+ input: {
395
+ functions: [],
396
+ consts: []
397
+ },
398
+ isArray: false
399
+ };
400
+ const resolvedRef = (0, __orval_core.resolveRef)(data, context).schema;
401
+ const schema = resolvedRef.content?.["application/json"]?.schema || resolvedRef.content?.["multipart/form-data"]?.schema;
402
+ if (!schema) return {
403
+ input: {
404
+ functions: [],
405
+ consts: []
406
+ },
407
+ isArray: false
408
+ };
409
+ const resolvedJsonSchema = deference(schema, context);
410
+ if (resolvedJsonSchema.items) {
411
+ const min = resolvedJsonSchema.minimum ?? resolvedJsonSchema.minLength ?? resolvedJsonSchema.minItems;
412
+ const max = resolvedJsonSchema.maximum ?? resolvedJsonSchema.maxLength ?? resolvedJsonSchema.maxItems;
413
+ return {
414
+ input: generateZodValidationSchemaDefinition(parseType === "body" ? removeReadOnlyProperties(resolvedJsonSchema.items) : resolvedJsonSchema.items, context, name, strict, isZodV4, { required: true }),
415
+ isArray: true,
416
+ rules: {
417
+ ...min === void 0 ? {} : { min },
418
+ ...max === void 0 ? {} : { max }
419
+ }
420
+ };
421
+ }
422
+ return {
423
+ input: generateZodValidationSchemaDefinition(parseType === "body" ? removeReadOnlyProperties(resolvedJsonSchema) : resolvedJsonSchema, context, name, strict, isZodV4, { required: true }),
424
+ isArray: false
425
+ };
640
426
  };
641
- var parseParameters = ({
642
- data,
643
- context,
644
- operationName,
645
- isZodV4,
646
- strict,
647
- generate
648
- }) => {
649
- if (!data) {
650
- return {
651
- headers: {
652
- functions: [],
653
- consts: []
654
- },
655
- queryParams: {
656
- functions: [],
657
- consts: []
658
- },
659
- params: {
660
- functions: [],
661
- consts: []
662
- }
663
- };
664
- }
665
- const defintionsByParameters = data.reduce(
666
- (acc, val) => {
667
- var _a;
668
- const { schema: parameter } = (0, import_core2.resolveRef)(val, context);
669
- if (!parameter.schema) {
670
- return acc;
671
- }
672
- const schema = deference(parameter.schema, context);
673
- schema.description = parameter.description;
674
- const mapStrict = {
675
- path: strict.param,
676
- query: strict.query,
677
- header: strict.header
678
- };
679
- const mapGenerate = {
680
- path: generate.param,
681
- query: generate.query,
682
- header: generate.header
683
- };
684
- const definition = generateZodValidationSchemaDefinition(
685
- schema,
686
- context,
687
- (0, import_core2.camel)(`${operationName}-${parameter.in}-${parameter.name}`),
688
- (_a = mapStrict[parameter.in]) != null ? _a : false,
689
- isZodV4,
690
- {
691
- required: parameter.required
692
- }
693
- );
694
- if (parameter.in === "header" && mapGenerate.header) {
695
- return {
696
- ...acc,
697
- headers: { ...acc.headers, [parameter.name]: definition }
698
- };
699
- }
700
- if (parameter.in === "query" && mapGenerate.query) {
701
- return {
702
- ...acc,
703
- queryParams: { ...acc.queryParams, [parameter.name]: definition }
704
- };
705
- }
706
- if (parameter.in === "path" && mapGenerate.path) {
707
- return {
708
- ...acc,
709
- params: { ...acc.params, [parameter.name]: definition }
710
- };
711
- }
712
- return acc;
713
- },
714
- {
715
- headers: {},
716
- queryParams: {},
717
- params: {}
718
- }
719
- );
720
- const headers = {
721
- functions: [],
722
- consts: []
723
- };
724
- if (Object.keys(defintionsByParameters.headers).length) {
725
- const parameterFunctions = getParameterFunctions(
726
- isZodV4,
727
- strict.header,
728
- defintionsByParameters.headers
729
- );
730
- headers.functions.push(...parameterFunctions);
731
- }
732
- const queryParams = {
733
- functions: [],
734
- consts: []
735
- };
736
- if (Object.keys(defintionsByParameters.queryParams).length) {
737
- const parameterFunctions = getParameterFunctions(
738
- isZodV4,
739
- strict.query,
740
- defintionsByParameters.queryParams
741
- );
742
- queryParams.functions.push(...parameterFunctions);
743
- }
744
- const params = {
745
- functions: [],
746
- consts: []
747
- };
748
- if (Object.keys(defintionsByParameters.params).length) {
749
- const parameterFunctions = getParameterFunctions(
750
- isZodV4,
751
- strict.param,
752
- defintionsByParameters.params
753
- );
754
- params.functions.push(...parameterFunctions);
755
- }
756
- return {
757
- headers,
758
- queryParams,
759
- params
760
- };
427
+ const parseParameters = ({ data, context, operationName, isZodV4, strict, generate }) => {
428
+ if (!data) return {
429
+ headers: {
430
+ functions: [],
431
+ consts: []
432
+ },
433
+ queryParams: {
434
+ functions: [],
435
+ consts: []
436
+ },
437
+ params: {
438
+ functions: [],
439
+ consts: []
440
+ }
441
+ };
442
+ const defintionsByParameters = data.reduce((acc, val) => {
443
+ const { schema: parameter } = (0, __orval_core.resolveRef)(val, context);
444
+ if (!parameter.schema) return acc;
445
+ const schema = deference(parameter.schema, context);
446
+ schema.description = parameter.description;
447
+ const mapStrict = {
448
+ path: strict.param,
449
+ query: strict.query,
450
+ header: strict.header
451
+ };
452
+ const mapGenerate = {
453
+ path: generate.param,
454
+ query: generate.query,
455
+ header: generate.header
456
+ };
457
+ const definition = generateZodValidationSchemaDefinition(schema, context, (0, __orval_core.camel)(`${operationName}-${parameter.in}-${parameter.name}`), mapStrict[parameter.in] ?? false, isZodV4, { required: parameter.required });
458
+ if (parameter.in === "header" && mapGenerate.header) return {
459
+ ...acc,
460
+ headers: {
461
+ ...acc.headers,
462
+ [parameter.name]: definition
463
+ }
464
+ };
465
+ if (parameter.in === "query" && mapGenerate.query) return {
466
+ ...acc,
467
+ queryParams: {
468
+ ...acc.queryParams,
469
+ [parameter.name]: definition
470
+ }
471
+ };
472
+ if (parameter.in === "path" && mapGenerate.path) return {
473
+ ...acc,
474
+ params: {
475
+ ...acc.params,
476
+ [parameter.name]: definition
477
+ }
478
+ };
479
+ return acc;
480
+ }, {
481
+ headers: {},
482
+ queryParams: {},
483
+ params: {}
484
+ });
485
+ const headers = {
486
+ functions: [],
487
+ consts: []
488
+ };
489
+ if (Object.keys(defintionsByParameters.headers).length > 0) {
490
+ const parameterFunctions = getParameterFunctions(isZodV4, strict.header, defintionsByParameters.headers);
491
+ headers.functions.push(...parameterFunctions);
492
+ }
493
+ const queryParams = {
494
+ functions: [],
495
+ consts: []
496
+ };
497
+ if (Object.keys(defintionsByParameters.queryParams).length > 0) {
498
+ const parameterFunctions = getParameterFunctions(isZodV4, strict.query, defintionsByParameters.queryParams);
499
+ queryParams.functions.push(...parameterFunctions);
500
+ }
501
+ const params = {
502
+ functions: [],
503
+ consts: []
504
+ };
505
+ if (Object.keys(defintionsByParameters.params).length > 0) {
506
+ const parameterFunctions = getParameterFunctions(isZodV4, strict.param, defintionsByParameters.params);
507
+ params.functions.push(...parameterFunctions);
508
+ }
509
+ return {
510
+ headers,
511
+ queryParams,
512
+ params
513
+ };
761
514
  };
762
- var generateZodRoute = async ({ operationName, verb, override }, { pathRoute, context, output }) => {
763
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
764
- const isZodV4 = !!context.output.packageJson && isZodVersionV4(context.output.packageJson);
765
- const spec = context.specs[context.specKey].paths[pathRoute];
766
- const parameters = (_a = spec == null ? void 0 : spec[verb]) == null ? void 0 : _a.parameters;
767
- const parsedParameters = parseParameters({
768
- data: parameters,
769
- context,
770
- operationName,
771
- isZodV4,
772
- strict: override.zod.strict,
773
- generate: override.zod.generate
774
- });
775
- const requestBody = (_b = spec == null ? void 0 : spec[verb]) == null ? void 0 : _b.requestBody;
776
- const parsedBody = parseBodyAndResponse({
777
- data: requestBody,
778
- context,
779
- name: (0, import_core2.camel)(`${operationName}-body`),
780
- strict: override.zod.strict.body,
781
- generate: override.zod.generate.body,
782
- isZodV4,
783
- parseType: "body"
784
- });
785
- const responses = context.output.override.zod.generateEachHttpStatus ? Object.entries((_d = (_c = spec == null ? void 0 : spec[verb]) == null ? void 0 : _c.responses) != null ? _d : {}) : [["", (_e = spec == null ? void 0 : spec[verb]) == null ? void 0 : _e.responses[200]]];
786
- const parsedResponses = responses.map(
787
- ([code, response]) => parseBodyAndResponse({
788
- data: response,
789
- context,
790
- name: (0, import_core2.camel)(`${operationName}-${code}-response`),
791
- strict: override.zod.strict.response,
792
- generate: override.zod.generate.response,
793
- isZodV4,
794
- parseType: "response"
795
- })
796
- );
797
- const preprocessParams = ((_f = override.zod.preprocess) == null ? void 0 : _f.param) ? await (0, import_core2.generateMutator)({
798
- output,
799
- mutator: override.zod.preprocess.response,
800
- name: `${operationName}PreprocessParams`,
801
- workspace: context.workspace,
802
- tsconfig: context.output.tsconfig
803
- }) : void 0;
804
- const inputParams = parseZodValidationSchemaDefinition(
805
- parsedParameters.params,
806
- context,
807
- override.zod.coerce.param,
808
- override.zod.strict.param,
809
- isZodV4,
810
- preprocessParams
811
- );
812
- if (override.coerceTypes) {
813
- console.warn(
814
- "override.coerceTypes is deprecated, please use override.zod.coerce instead."
815
- );
816
- }
817
- const preprocessQueryParams = ((_g = override.zod.preprocess) == null ? void 0 : _g.query) ? await (0, import_core2.generateMutator)({
818
- output,
819
- mutator: override.zod.preprocess.response,
820
- name: `${operationName}PreprocessQueryParams`,
821
- workspace: context.workspace,
822
- tsconfig: context.output.tsconfig
823
- }) : void 0;
824
- const inputQueryParams = parseZodValidationSchemaDefinition(
825
- parsedParameters.queryParams,
826
- context,
827
- (_h = override.zod.coerce.query) != null ? _h : override.coerceTypes,
828
- override.zod.strict.query,
829
- isZodV4,
830
- preprocessQueryParams
831
- );
832
- const preprocessHeader = ((_i = override.zod.preprocess) == null ? void 0 : _i.header) ? await (0, import_core2.generateMutator)({
833
- output,
834
- mutator: override.zod.preprocess.response,
835
- name: `${operationName}PreprocessHeader`,
836
- workspace: context.workspace,
837
- tsconfig: context.output.tsconfig
838
- }) : void 0;
839
- const inputHeaders = parseZodValidationSchemaDefinition(
840
- parsedParameters.headers,
841
- context,
842
- override.zod.coerce.header,
843
- override.zod.strict.header,
844
- isZodV4,
845
- preprocessHeader
846
- );
847
- const preprocessBody = ((_j = override.zod.preprocess) == null ? void 0 : _j.body) ? await (0, import_core2.generateMutator)({
848
- output,
849
- mutator: override.zod.preprocess.response,
850
- name: `${operationName}PreprocessBody`,
851
- workspace: context.workspace,
852
- tsconfig: context.output.tsconfig
853
- }) : void 0;
854
- const inputBody = parseZodValidationSchemaDefinition(
855
- parsedBody.input,
856
- context,
857
- override.zod.coerce.body,
858
- override.zod.strict.body,
859
- isZodV4,
860
- preprocessBody
861
- );
862
- const preprocessResponse = ((_k = override.zod.preprocess) == null ? void 0 : _k.response) ? await (0, import_core2.generateMutator)({
863
- output,
864
- mutator: override.zod.preprocess.response,
865
- name: `${operationName}PreprocessResponse`,
866
- workspace: context.workspace,
867
- tsconfig: context.output.tsconfig
868
- }) : void 0;
869
- const inputResponses = parsedResponses.map(
870
- (parsedResponse) => parseZodValidationSchemaDefinition(
871
- parsedResponse.input,
872
- context,
873
- override.zod.coerce.response,
874
- override.zod.strict.response,
875
- isZodV4,
876
- preprocessResponse
877
- )
878
- );
879
- if (!inputParams.zod && !inputQueryParams.zod && !inputHeaders.zod && !inputBody.zod && !inputResponses.some((inputResponse) => inputResponse.zod)) {
880
- return {
881
- implemtation: "",
882
- mutators: []
883
- };
884
- }
885
- return {
886
- implementation: [
887
- ...inputParams.consts ? [inputParams.consts] : [],
888
- ...inputParams.zod ? [`export const ${operationName}Params = ${inputParams.zod}`] : [],
889
- ...inputQueryParams.consts ? [inputQueryParams.consts] : [],
890
- ...inputQueryParams.zod ? [`export const ${operationName}QueryParams = ${inputQueryParams.zod}`] : [],
891
- ...inputHeaders.consts ? [inputHeaders.consts] : [],
892
- ...inputHeaders.zod ? [`export const ${operationName}Header = ${inputHeaders.zod}`] : [],
893
- ...inputBody.consts ? [inputBody.consts] : [],
894
- ...inputBody.zod ? [
895
- parsedBody.isArray ? `export const ${operationName}BodyItem = ${inputBody.zod}
896
- export const ${operationName}Body = zod.array(${operationName}BodyItem)${((_l = parsedBody.rules) == null ? void 0 : _l.min) ? `.min(${(_m = parsedBody.rules) == null ? void 0 : _m.min})` : ""}${((_n = parsedBody.rules) == null ? void 0 : _n.max) ? `.max(${(_o = parsedBody.rules) == null ? void 0 : _o.max})` : ""}` : `export const ${operationName}Body = ${inputBody.zod}`
897
- ] : [],
898
- ...inputResponses.map((inputResponse, index) => {
899
- var _a2, _b2, _c2, _d2;
900
- const operationResponse = (0, import_core2.camel)(
901
- `${operationName}-${responses[index][0]}-response`
902
- );
903
- return [
904
- ...inputResponse.consts ? [inputResponse.consts] : [],
905
- ...inputResponse.zod ? [
906
- parsedResponses[index].isArray ? `export const ${operationResponse}Item = ${inputResponse.zod}
907
- export const ${operationResponse} = zod.array(${operationResponse}Item)${((_a2 = parsedResponses[index].rules) == null ? void 0 : _a2.min) ? `.min(${(_b2 = parsedResponses[index].rules) == null ? void 0 : _b2.min})` : ""}${((_c2 = parsedResponses[index].rules) == null ? void 0 : _c2.max) ? `.max(${(_d2 = parsedResponses[index].rules) == null ? void 0 : _d2.max})` : ""}` : `export const ${operationResponse} = ${inputResponse.zod}`
908
- ] : []
909
- ];
910
- }).flat()
911
- ].join("\n\n"),
912
- mutators: preprocessResponse ? [preprocessResponse] : []
913
- };
515
+ const generateZodRoute = async ({ operationName, verb, override }, { pathRoute, context, output }) => {
516
+ const isZodV4 = !!context.output.packageJson && isZodVersionV4(context.output.packageJson);
517
+ const spec = context.specs[context.specKey].paths[pathRoute];
518
+ const parameters = spec?.[verb]?.parameters;
519
+ const parsedParameters = parseParameters({
520
+ data: parameters,
521
+ context,
522
+ operationName,
523
+ isZodV4,
524
+ strict: override.zod.strict,
525
+ generate: override.zod.generate
526
+ });
527
+ const requestBody = spec?.[verb]?.requestBody;
528
+ const parsedBody = parseBodyAndResponse({
529
+ data: requestBody,
530
+ context,
531
+ name: (0, __orval_core.camel)(`${operationName}-body`),
532
+ strict: override.zod.strict.body,
533
+ generate: override.zod.generate.body,
534
+ isZodV4,
535
+ parseType: "body"
536
+ });
537
+ const responses = context.output.override.zod.generateEachHttpStatus ? Object.entries(spec?.[verb]?.responses ?? {}) : [["", spec?.[verb]?.responses[200]]];
538
+ const parsedResponses = responses.map(([code, response]) => parseBodyAndResponse({
539
+ data: response,
540
+ context,
541
+ name: (0, __orval_core.camel)(`${operationName}-${code}-response`),
542
+ strict: override.zod.strict.response,
543
+ generate: override.zod.generate.response,
544
+ isZodV4,
545
+ parseType: "response"
546
+ }));
547
+ const preprocessParams = override.zod.preprocess?.param ? await (0, __orval_core.generateMutator)({
548
+ output,
549
+ mutator: override.zod.preprocess.response,
550
+ name: `${operationName}PreprocessParams`,
551
+ workspace: context.workspace,
552
+ tsconfig: context.output.tsconfig
553
+ }) : void 0;
554
+ const inputParams = parseZodValidationSchemaDefinition(parsedParameters.params, context, override.zod.coerce.param, override.zod.strict.param, isZodV4, preprocessParams);
555
+ if (override.coerceTypes) console.warn("override.coerceTypes is deprecated, please use override.zod.coerce instead.");
556
+ const preprocessQueryParams = override.zod.preprocess?.query ? await (0, __orval_core.generateMutator)({
557
+ output,
558
+ mutator: override.zod.preprocess.response,
559
+ name: `${operationName}PreprocessQueryParams`,
560
+ workspace: context.workspace,
561
+ tsconfig: context.output.tsconfig
562
+ }) : void 0;
563
+ const inputQueryParams = parseZodValidationSchemaDefinition(parsedParameters.queryParams, context, override.zod.coerce.query ?? override.coerceTypes, override.zod.strict.query, isZodV4, preprocessQueryParams);
564
+ const preprocessHeader = override.zod.preprocess?.header ? await (0, __orval_core.generateMutator)({
565
+ output,
566
+ mutator: override.zod.preprocess.response,
567
+ name: `${operationName}PreprocessHeader`,
568
+ workspace: context.workspace,
569
+ tsconfig: context.output.tsconfig
570
+ }) : void 0;
571
+ const inputHeaders = parseZodValidationSchemaDefinition(parsedParameters.headers, context, override.zod.coerce.header, override.zod.strict.header, isZodV4, preprocessHeader);
572
+ const preprocessBody = override.zod.preprocess?.body ? await (0, __orval_core.generateMutator)({
573
+ output,
574
+ mutator: override.zod.preprocess.response,
575
+ name: `${operationName}PreprocessBody`,
576
+ workspace: context.workspace,
577
+ tsconfig: context.output.tsconfig
578
+ }) : void 0;
579
+ const inputBody = parseZodValidationSchemaDefinition(parsedBody.input, context, override.zod.coerce.body, override.zod.strict.body, isZodV4, preprocessBody);
580
+ const preprocessResponse = override.zod.preprocess?.response ? await (0, __orval_core.generateMutator)({
581
+ output,
582
+ mutator: override.zod.preprocess.response,
583
+ name: `${operationName}PreprocessResponse`,
584
+ workspace: context.workspace,
585
+ tsconfig: context.output.tsconfig
586
+ }) : void 0;
587
+ const inputResponses = parsedResponses.map((parsedResponse) => parseZodValidationSchemaDefinition(parsedResponse.input, context, override.zod.coerce.response, override.zod.strict.response, isZodV4, preprocessResponse));
588
+ if (!inputParams.zod && !inputQueryParams.zod && !inputHeaders.zod && !inputBody.zod && !inputResponses.some((inputResponse) => inputResponse.zod)) return {
589
+ implemtation: "",
590
+ mutators: []
591
+ };
592
+ return {
593
+ implementation: [
594
+ ...inputParams.consts ? [inputParams.consts] : [],
595
+ ...inputParams.zod ? [`export const ${operationName}Params = ${inputParams.zod}`] : [],
596
+ ...inputQueryParams.consts ? [inputQueryParams.consts] : [],
597
+ ...inputQueryParams.zod ? [`export const ${operationName}QueryParams = ${inputQueryParams.zod}`] : [],
598
+ ...inputHeaders.consts ? [inputHeaders.consts] : [],
599
+ ...inputHeaders.zod ? [`export const ${operationName}Header = ${inputHeaders.zod}`] : [],
600
+ ...inputBody.consts ? [inputBody.consts] : [],
601
+ ...inputBody.zod ? [parsedBody.isArray ? `export const ${operationName}BodyItem = ${inputBody.zod}
602
+ export const ${operationName}Body = zod.array(${operationName}BodyItem)${parsedBody.rules?.min ? `.min(${parsedBody.rules?.min})` : ""}${parsedBody.rules?.max ? `.max(${parsedBody.rules?.max})` : ""}` : `export const ${operationName}Body = ${inputBody.zod}`] : [],
603
+ ...inputResponses.flatMap((inputResponse, index) => {
604
+ const operationResponse = (0, __orval_core.camel)(`${operationName}-${responses[index][0]}-response`);
605
+ return [...inputResponse.consts ? [inputResponse.consts] : [], ...inputResponse.zod ? [parsedResponses[index].isArray ? `export const ${operationResponse}Item = ${inputResponse.zod}
606
+ export const ${operationResponse} = zod.array(${operationResponse}Item)${parsedResponses[index].rules?.min ? `.min(${parsedResponses[index].rules?.min})` : ""}${parsedResponses[index].rules?.max ? `.max(${parsedResponses[index].rules?.max})` : ""}` : `export const ${operationResponse} = ${inputResponse.zod}`] : []];
607
+ })
608
+ ].join("\n\n"),
609
+ mutators: preprocessResponse ? [preprocessResponse] : []
610
+ };
914
611
  };
915
- var generateZod = async (verbOptions, options) => {
916
- const { implementation, mutators } = await generateZodRoute(
917
- verbOptions,
918
- options
919
- );
920
- return {
921
- implementation: implementation ? `${implementation}
922
-
923
- ` : "",
924
- imports: [],
925
- mutators
926
- };
612
+ const generateZod = async (verbOptions, options) => {
613
+ const { implementation, mutators } = await generateZodRoute(verbOptions, options);
614
+ return {
615
+ implementation: implementation ? `${implementation}\n\n` : "",
616
+ imports: [],
617
+ mutators
618
+ };
927
619
  };
928
- var zodClientBuilder = {
929
- client: generateZod,
930
- dependencies: getZodDependencies
620
+ const zodClientBuilder = {
621
+ client: generateZod,
622
+ dependencies: getZodDependencies
931
623
  };
932
- var builder = () => () => zodClientBuilder;
933
- var index_default = builder;
934
- // Annotate the CommonJS export names for ESM import in node:
935
- 0 && (module.exports = {
936
- builder,
937
- generateZod,
938
- generateZodValidationSchemaDefinition,
939
- getZodDependencies,
940
- parseZodValidationSchemaDefinition
941
- });
624
+ const builder = () => () => zodClientBuilder;
625
+ var src_default = builder;
626
+
627
+ //#endregion
628
+ exports.builder = builder;
629
+ exports.default = src_default;
630
+ exports.generateZod = generateZod;
631
+ exports.generateZodValidationSchemaDefinition = generateZodValidationSchemaDefinition;
632
+ exports.getZodDependencies = getZodDependencies;
633
+ exports.parseZodValidationSchemaDefinition = parseZodValidationSchemaDefinition;
942
634
  //# sourceMappingURL=index.js.map