@povio/openapi-codegen-cli 3.3.0-rc.1 → 4.0.0-rc.1

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 (68) hide show
  1. package/README.md +97 -9
  2. package/dist/AuthGuard-GbtTDXs0.d.mts +32 -0
  3. package/dist/AuthGuard-qpAtHaBz.mjs +24 -0
  4. package/dist/acl.d.mts +6 -19
  5. package/dist/acl.mjs +7 -7
  6. package/dist/{auth.context-BAz8frX9.mjs → auth.context-COWO6ssl.mjs} +1 -18
  7. package/dist/auth.d.mts +2 -0
  8. package/dist/auth.mjs +3 -0
  9. package/dist/axios.d.mts +2 -0
  10. package/dist/axios.mjs +2 -0
  11. package/dist/{config-BQqze8rU.d.mts → config-CiLFKLAY.d.mts} +1 -2
  12. package/dist/config.d.mts +4 -0
  13. package/dist/config.mjs +5 -0
  14. package/dist/{error-handling-D6ZYITQ3.d.mts → error-handling-LPEPQV1V.d.mts} +3 -42
  15. package/dist/{error-handling-CsnufAil.mjs → error-handling-uS0DgYUR.mjs} +23 -47
  16. package/dist/errors.d.mts +3 -0
  17. package/dist/errors.mjs +2 -0
  18. package/dist/generate.runner-BtPpBVj9.mjs +1667 -0
  19. package/dist/generate.utils-BJxdEik8.cjs +2269 -0
  20. package/dist/{generateCodeFromOpenAPIDoc-KQT4kYxY.mjs → generateCodeFromOpenAPIDoc-CGoR73wh.cjs} +1335 -2237
  21. package/dist/generateCodeFromOpenAPIDoc-D1H6MZiS.mjs +2101 -0
  22. package/dist/generator.d.mts +3 -10
  23. package/dist/generator.mjs +6 -4
  24. package/dist/getDataFromOpenAPIDoc-fJCwtr-2.mjs +2016 -0
  25. package/dist/i18n-B_brQh4X.d.mts +38 -0
  26. package/dist/i18n-D-FesqFb.mjs +36 -0
  27. package/dist/index.d.mts +12 -198
  28. package/dist/index.mjs +12 -256
  29. package/dist/metro.cjs +117 -4861
  30. package/dist/metro.d.mts +3 -4
  31. package/dist/metro.mjs +3 -3
  32. package/dist/native-rest-interceptor-BX45GDWd.d.mts +49 -0
  33. package/dist/native-rest-interceptor-Np4Ov54n.mjs +215 -0
  34. package/dist/native.d.mts +3 -0
  35. package/dist/native.mjs +3 -0
  36. package/dist/openapi-codegen-native-darwin-arm64.node +0 -0
  37. package/dist/openapi-codegen-native-linux-x64.node +0 -0
  38. package/dist/openapi-codegen-native-win32-x64.node +0 -0
  39. package/dist/{openapi-codegen.runner-nPBssrBL.mjs → openapi-codegen.runner-BpykceyD.mjs} +2 -2
  40. package/dist/{openapi-source.runner-B6KKrXw7.d.mts → openapi-source.runner-DIOvAX_R.d.mts} +2 -8
  41. package/dist/{openapi-source.runner-8kCe-g9S.mjs → openapi-source.runner-DPUNTduQ.mjs} +25 -11
  42. package/dist/{options-DdQJ9BSc.d.mts → options-X0zju7gw.d.mts} +8 -1
  43. package/dist/query.d.mts +3 -0
  44. package/dist/query.mjs +3 -0
  45. package/dist/queryConfig.context-CldQ5YL9.mjs +34 -0
  46. package/dist/queryConfig.context-aO4QOLru.d.mts +24 -0
  47. package/dist/rest-client-BSXsrOff.d.mts +55 -0
  48. package/dist/rest-interceptor-Dm9DFErh.mjs +115 -0
  49. package/dist/rest-transport.types-DM5-qyOJ.d.mts +66 -0
  50. package/dist/rest-transport.types-DxitRtsB.mjs +11 -0
  51. package/dist/rest.d.mts +2 -0
  52. package/dist/rest.mjs +2 -0
  53. package/dist/rest.utils-DpiFIdhF.d.mts +9 -0
  54. package/dist/router.context-EPlMBk3G.mjs +21 -0
  55. package/dist/sh.d.mts +1 -1
  56. package/dist/sh.mjs +52 -59
  57. package/dist/tiny.d.mts +1 -1
  58. package/dist/tiny.mjs +1 -1
  59. package/dist/useMutationEffects-D_wEEF6-.d.mts +29 -0
  60. package/dist/useMutationEffects-PB1fvKWM.mjs +68 -0
  61. package/dist/vite.d.mts +3 -4
  62. package/dist/vite.mjs +5 -4
  63. package/dist/workspace.context-XWvQ_7Hg.mjs +26 -0
  64. package/dist/workspace.context-isVY9ves.d.mts +23 -0
  65. package/dist/zod.d.mts +2 -7
  66. package/dist/zod.mjs +1 -1
  67. package/package.json +70 -22
  68. package/dist/generate.runner-BeCGJ1ar.mjs +0 -87
@@ -0,0 +1,2016 @@
1
+ import { $t as isPrimitiveType, Bn as getMostCommonAdjacentCombinationSplit, Ct as getParamZodSchemaName, Et as getZodSchemaOperationName, Fn as isTagIncluded, Gt as getParameterEnumNames, Hn as removeWord, Ht as getNamespaceName, Jt as isErrorStatus, Kt as getSchemaNameByRef, Mn as formatTag, Nn as getEndpointTag, On as BODY_PARAMETER_NAME, Ot as isNamedZodSchema, Pn as getOperationTag, Qt as isPathExcluded, Rn as capitalize, Sn as VOID_SCHEMA, St as getEnumZodSchemaName, Tt as getZodSchemaName, Un as snakeToCamel, Ut as autocorrectRef, Wn as Profiler, Wt as escapeControlCharacters, Xt as isMediaTypeAllowed, Yt as isMainResponseStatus, Zt as isParamMediaTypeAllowed, _n as INT_SCHEMA, an as wrapWithQuotesIfNeeded, bn as URL_SCHEMA, bt as invalidVariableNameCharactersToCamel, cn as isReferenceObject, d as isQuery, dn as ALLOWED_PATH_IN, en as isSortingParameterObject, fn as ANY_SCHEMA, gn as ENUM_SCHEMA, hn as EMAIL_SCHEMA, in as unwrapQuotesIfNeeded, kn as JSON_APPLICATION_FORMAT, ln as isSchemaObject, lt as iterateSchema, mn as DATETIME_SCHEMA, nn as pathToVariableName, on as inferRequiredSchema, pn as BLOB_SCHEMA, qt as getSchemaRef, rn as replaceHyphenatedPath, s as pick, sn as isArraySchemaObject, tn as pathParamToVariableName, un as ALLOWED_METHODS, ut as getUniqueArray, vn as NUMBER_SCHEMA, wt as getResponseZodSchemaName, xn as UUID_SCHEMA, xt as getBodyZodSchemaName, yn as STRING_SCHEMA, zn as decapitalize } from "./generate.runner-BtPpBVj9.mjs";
2
+ //#region src/generators/const/validation.const.ts
3
+ const HTTP_STATUS_CODES = {
4
+ "100": "Continue",
5
+ "101": "Switching Protocols",
6
+ "102": "Processing",
7
+ "103": "Early Hints",
8
+ "200": "OK",
9
+ "201": "Created",
10
+ "202": "Accepted",
11
+ "203": "Non-Authoritative Information",
12
+ "204": "No Content",
13
+ "205": "Reset Content",
14
+ "206": "Partial Content",
15
+ "300": "Ambiguous",
16
+ "301": "Moved Permanently",
17
+ "302": "Found",
18
+ "303": "See Other",
19
+ "304": "Not Modified",
20
+ "307": "Temporary Redirect",
21
+ "308": "Permanent Redirect",
22
+ "400": "Bad Request",
23
+ "401": "Unauthorized",
24
+ "402": "Payment Required",
25
+ "403": "Forbidden",
26
+ "404": "Not Found",
27
+ "405": "Method Not Allowed",
28
+ "406": "Not Acceptable",
29
+ "407": "Proxy Authentication Required",
30
+ "408": "Request Timeout",
31
+ "409": "Conflict",
32
+ "410": "Gone",
33
+ "411": "Length Required",
34
+ "412": "Precondition Failed",
35
+ "413": "Payload Too Large",
36
+ "414": "URI Too Long",
37
+ "415": "Unsupported Media Type",
38
+ "416": "Requested Range Not Satisfiable",
39
+ "417": "Expectation Failed",
40
+ "418": "I Am a Teapot",
41
+ "421": "Misdirected Request",
42
+ "422": "Unprocessable Entity",
43
+ "424": "Failed Dependency",
44
+ "428": "Precondition Required",
45
+ "429": "Too Many Requests",
46
+ "500": "Internal Server Error",
47
+ "501": "Not Implemented",
48
+ "502": "Bad Gateway",
49
+ "503": "Service Unavailable",
50
+ "504": "Gateway Timeout",
51
+ "505": "HTTP Version Not Supported"
52
+ };
53
+ const VALIDATION_ERROR_TYPE_TITLE = {
54
+ "invalid-schema": "Invalid OpenAPI Schemas",
55
+ "invalid-operation-id": "Invalid Operation IDs",
56
+ "missing-path-parameter": "Missing Path Parameters",
57
+ "not-allowed-inline-enum": "Not Allowed Inline Enums",
58
+ "not-allowed-circular-schema": "Not Allowed Circular Schemas",
59
+ "missing-acl-condition-property": "Missing x-acl Condition Properties",
60
+ "missing-status-code": "Missing HTTP Status Codes",
61
+ "invalid-status-code": "Invalid HTTP Status Codes",
62
+ "multiple-success-status-codes": "Multiple Success HTTP Status Codes"
63
+ };
64
+ //#endregion
65
+ //#region src/generators/core/zod/getZodChain.ts
66
+ const zodChainCache = /* @__PURE__ */ new WeakMap();
67
+ function getZodChain({ schema, meta, options }) {
68
+ let optionsCache = zodChainCache.get(options);
69
+ if (!optionsCache) {
70
+ optionsCache = /* @__PURE__ */ new WeakMap();
71
+ zodChainCache.set(options, optionsCache);
72
+ }
73
+ let schemaCache = optionsCache.get(schema);
74
+ if (!schemaCache) {
75
+ schemaCache = /* @__PURE__ */ new Map();
76
+ optionsCache.set(schema, schemaCache);
77
+ }
78
+ const cacheKey = `${Boolean(meta?.isRequired)}|${Boolean(meta?.isParentPartial)}`;
79
+ const cached = schemaCache.get(cacheKey);
80
+ if (cached !== void 0) return cached;
81
+ const chains = [];
82
+ if (schema.type === "string") chains.push(getZodChainableStringValidations(schema));
83
+ else if (schema.type === "number" || schema.type === "integer") chains.push(getZodChainableNumberValidations(schema));
84
+ else if (schema.type === "array") chains.push(getZodChainableArrayValidations(schema));
85
+ if (typeof schema.description === "string" && schema.description !== "" && options.withDescription) chains.push(`describe(${JSON.stringify(schema.description)})`);
86
+ const output = chains.concat(getZodChainablePresence({
87
+ schema,
88
+ meta,
89
+ options
90
+ }), options.withDefaultValues !== false ? getZodChainableDefault(schema) : []).filter(Boolean).join(".");
91
+ const chain = output ? `.${output}` : "";
92
+ schemaCache.set(cacheKey, chain);
93
+ return chain;
94
+ }
95
+ function getZodChainablePresence({ schema, meta, options }) {
96
+ if (schema.nullable && !meta?.isRequired) return "nullish()";
97
+ if (schema.nullable || options.replaceOptionalWithNullish && meta?.isParentPartial) return "nullable()";
98
+ if (!meta?.isRequired) return options.replaceOptionalWithNullish ? "nullish()" : "optional()";
99
+ return "";
100
+ }
101
+ function getZodChainableDefault(schema) {
102
+ if (schema.default !== void 0) return `default(${schema.type === "number" || schema.type === "integer" ? unwrapQuotesIfNeeded(schema.default) : JSON.stringify(schema.default)})`;
103
+ return "";
104
+ }
105
+ function getZodChainableStringValidations(schema) {
106
+ const validations = [];
107
+ if (!schema.enum) {
108
+ if (schema.minLength !== void 0) validations.push(`min(${schema.minLength})`);
109
+ if (schema.maxLength !== void 0) validations.push(`max(${schema.maxLength})`);
110
+ }
111
+ if (schema.pattern) validations.push(`regex(${formatPatternIfNeeded(schema.pattern)})`);
112
+ return validations.join(".");
113
+ }
114
+ function formatPatternIfNeeded(pattern) {
115
+ if (pattern.startsWith("/") && pattern.endsWith("/")) pattern = pattern.slice(1, -1);
116
+ pattern = escapeControlCharacters(pattern);
117
+ return `/${pattern}/`;
118
+ }
119
+ function getZodChainableNumberValidations(schema) {
120
+ const validations = [];
121
+ if (schema.enum) return "";
122
+ if (schema.minimum !== void 0) {
123
+ if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
124
+ else validations.push(`gte(${schema.minimum})`);
125
+ } else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
126
+ if (schema.maximum !== void 0) {
127
+ if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
128
+ else validations.push(`lte(${schema.maximum})`);
129
+ } else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
130
+ if (schema.multipleOf) validations.push(`multipleOf(${schema.multipleOf})`);
131
+ return validations.join(".");
132
+ }
133
+ function getZodChainableArrayValidations(schema) {
134
+ const validations = [];
135
+ if (schema.minItems) validations.push(`min(${schema.minItems})`);
136
+ if (schema.maxItems) validations.push(`max(${schema.maxItems})`);
137
+ return validations.join(".");
138
+ }
139
+ //#endregion
140
+ //#region src/generators/core/zod/getZodSchemaRefs.ts
141
+ function getZodSchemaRefs(resolver, zodSchemaName) {
142
+ const schemaRef = resolver.getRefByZodSchemaName(zodSchemaName);
143
+ if (schemaRef) {
144
+ const refs = Array.from(resolver.dependencyGraph.refsDependencyGraph[schemaRef] ?? []).map((ref) => resolver.getZodSchemaNameByRef(ref));
145
+ const enumRefs = resolver.getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef);
146
+ return [...refs, ...enumRefs];
147
+ }
148
+ const zodSchema = resolver.getCompositeZodSchemaByZodSchemaName(zodSchemaName);
149
+ if (zodSchema) return Array.from(getSchemaRefs(zodSchema)).map((schemaRef) => resolver.getZodSchemaNameByRef(schemaRef));
150
+ return [];
151
+ }
152
+ function getSchemaRefs(zodSchema, { skipObjectSchema = false } = {}) {
153
+ return zodSchema.children.reduce((acc, child) => {
154
+ const ref = child.ref ?? child.enumRef;
155
+ if (ref) acc.add(ref);
156
+ if (child.children.length > 0 && (!skipObjectSchema || !isSchemaObject(child.schema) || child.schema.type !== "object")) getSchemaRefs(child).forEach((ref) => acc.add(ref));
157
+ return acc;
158
+ }, /* @__PURE__ */ new Set());
159
+ }
160
+ //#endregion
161
+ //#region src/generators/utils/math.utils.ts
162
+ const sum = (arr) => arr.reduce((acc, item) => acc + item, 0);
163
+ //#endregion
164
+ //#region src/generators/core/openapi/getOpenAPISchemaComplexity.ts
165
+ function getOpenAPISchemaComplexity(current, schema) {
166
+ if (!schema) return current;
167
+ if (isReferenceObject(schema)) return current + 2;
168
+ if (Array.isArray(schema.type)) {
169
+ if (schema.type.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, {
170
+ ...schema,
171
+ type: schema.type[0]
172
+ });
173
+ return current + complexityByComposite("oneOf") + sum(schema.type.map((prop) => getOpenAPISchemaComplexity(0, {
174
+ ...schema,
175
+ type: prop
176
+ })));
177
+ }
178
+ if (schema.oneOf) {
179
+ if (schema.oneOf.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, schema.oneOf[0]);
180
+ return current + complexityByComposite("oneOf") + sum(schema.oneOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
181
+ }
182
+ if (schema.anyOf) {
183
+ if (schema.anyOf.length === 1) return complexityByComposite("anyOf") + getOpenAPISchemaComplexity(current, schema.anyOf[0]);
184
+ return current + complexityByComposite("anyOf") + sum(schema.anyOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
185
+ }
186
+ if (schema.allOf) {
187
+ if (schema.allOf.length === 1) return complexityByComposite("allOf") + getOpenAPISchemaComplexity(current, schema.allOf[0]);
188
+ return current + complexityByComposite("allOf") + sum(schema.allOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
189
+ }
190
+ if (!schema.type) return current;
191
+ if (isPrimitiveType(schema.type)) {
192
+ if (schema.enum) return current + complexityByType(schema) + complexityByComposite("enum") + sum(schema.enum.map((prop) => getOpenAPISchemaComplexity(0, prop)));
193
+ return current + complexityByType(schema);
194
+ }
195
+ if (schema.type === "array") {
196
+ if (schema.items) return complexityByComposite("array") + getOpenAPISchemaComplexity(current, schema.items);
197
+ return complexityByComposite("array") + getOpenAPISchemaComplexity(current);
198
+ }
199
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
200
+ if (schema.properties) {
201
+ const props = Object.values(schema.properties);
202
+ current += complexityByComposite("object") + sum(props.map((prop) => getOpenAPISchemaComplexity(0, prop)));
203
+ } else current += complexityByComposite("empty-object");
204
+ if (schema.additionalProperties) {
205
+ if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
206
+ else current += getOpenAPISchemaComplexity(1);
207
+ }
208
+ }
209
+ return current;
210
+ }
211
+ function complexityByType(schema) {
212
+ return schema.type === "string" || schema.type === "number" || schema.type === "integer" || schema.type === "boolean" ? 1 : 0;
213
+ }
214
+ function complexityByComposite(type) {
215
+ switch (type) {
216
+ case "anyOf": return 3;
217
+ case "oneOf":
218
+ case "allOf":
219
+ case "object": return 2;
220
+ case "enum":
221
+ case "array":
222
+ case "empty-object": return 1;
223
+ default: return 0;
224
+ }
225
+ }
226
+ //#endregion
227
+ //#region src/generators/core/zod/ZodSchema.class.ts
228
+ var ZodSchema = class {
229
+ schema;
230
+ resolver;
231
+ code;
232
+ ref;
233
+ enumRef;
234
+ children = [];
235
+ meta;
236
+ constructor(schema, resolver, meta = { referencedBy: [] }, enumRef) {
237
+ this.schema = schema;
238
+ this.resolver = resolver;
239
+ if (isReferenceObject(schema)) this.ref = schema.$ref;
240
+ if (enumRef) this.enumRef = enumRef;
241
+ this.meta = {
242
+ ...meta,
243
+ referencedBy: [...meta?.referencedBy ?? []]
244
+ };
245
+ if (this.ref) this.meta.referencedBy.push(this);
246
+ }
247
+ getCodeString(tag, options) {
248
+ if (!this.ref && this.code) return this.code;
249
+ if (!this.ref) throw new Error("Zod schema is missing both ref and code");
250
+ const zodSchemaName = this.resolver?.getZodSchemaNameByRef(this.ref);
251
+ if (!zodSchemaName) return this.ref;
252
+ const zodSchemaTag = this.resolver?.getTagByZodSchemaName(zodSchemaName);
253
+ if (options?.tsNamespaces && zodSchemaTag && zodSchemaTag !== tag) return `${getNamespaceName({
254
+ type: "models",
255
+ tag: zodSchemaTag,
256
+ options
257
+ })}.${zodSchemaName}`;
258
+ return zodSchemaName;
259
+ }
260
+ get complexity() {
261
+ return getOpenAPISchemaComplexity(0, this.schema);
262
+ }
263
+ assign(code) {
264
+ this.code = code;
265
+ return this;
266
+ }
267
+ inherit(parent) {
268
+ if (parent) parent.children.push(this);
269
+ return this;
270
+ }
271
+ };
272
+ function getParentRef(meta) {
273
+ if (!meta) return;
274
+ if (meta.parent?.ref) return meta.parent.ref;
275
+ return getParentRef(meta.parent?.meta);
276
+ }
277
+ //#endregion
278
+ //#region src/generators/core/zod/getZodSchema.ts
279
+ /**
280
+ * @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject
281
+ * @see https://github.com/colinhacks/zod
282
+ */
283
+ function getZodSchema({ schema, resolver, meta: inheritedMeta, tag }) {
284
+ const zodSchema = new ZodSchema(schema, resolver, inheritedMeta);
285
+ const meta = {
286
+ parent: zodSchema.inherit(inheritedMeta?.parent),
287
+ referencedBy: [...zodSchema.meta.referencedBy]
288
+ };
289
+ const params = {
290
+ resolver,
291
+ meta,
292
+ tag
293
+ };
294
+ if (isReferenceObject(schema)) return getReferenceZodSchema({
295
+ schema,
296
+ zodSchema,
297
+ resolver,
298
+ meta,
299
+ tag
300
+ });
301
+ const arrayZodSchema = getArrayZodSchema({
302
+ schema,
303
+ zodSchema,
304
+ resolver,
305
+ meta,
306
+ tag
307
+ });
308
+ if (arrayZodSchema) return arrayZodSchema;
309
+ const oneOfZodSchema = getOneOfZodSchema({
310
+ schema,
311
+ zodSchema,
312
+ resolver,
313
+ meta,
314
+ tag
315
+ });
316
+ if (oneOfZodSchema) return oneOfZodSchema;
317
+ const anyOfZodSchema = getAnyOfZodSchema({
318
+ schema,
319
+ zodSchema,
320
+ resolver,
321
+ meta,
322
+ tag
323
+ });
324
+ if (anyOfZodSchema) return anyOfZodSchema;
325
+ const allOfZodSchema = getAllOfZodSchema({
326
+ schema,
327
+ zodSchema,
328
+ resolver,
329
+ meta,
330
+ tag
331
+ });
332
+ if (allOfZodSchema) return allOfZodSchema;
333
+ const primitiveZodSchema = getPrimitiveZodSchema({
334
+ schema,
335
+ zodSchema,
336
+ resolver,
337
+ meta,
338
+ tag
339
+ });
340
+ if (primitiveZodSchema) return primitiveZodSchema;
341
+ const readonly = resolver.options.allReadonly ? ".readonly()" : "";
342
+ if (isArraySchemaObject(schema)) {
343
+ if (schema.items) return zodSchema.assign(`z.array(${getZodSchema({
344
+ ...params,
345
+ schema: schema.items
346
+ }).getCodeString(tag, resolver.options)}${getZodChain({
347
+ schema: schema.items,
348
+ meta: {
349
+ ...meta,
350
+ isRequired: true
351
+ },
352
+ options: resolver.options
353
+ })})${readonly}`);
354
+ return zodSchema.assign(`z.array(${ANY_SCHEMA})${readonly}`);
355
+ }
356
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
357
+ if (schemaType === "object" || schema.properties || schema.additionalProperties) {
358
+ const hasRequiredArray = schema.required && schema.required.length > 0;
359
+ const isPartial = resolver.options.withImplicitRequiredProps ? false : schema.properties && !schema.required?.length;
360
+ let properties = "{}";
361
+ if (schema.properties) properties = `{ ${Object.entries(schema.properties).map(([prop, propSchema]) => {
362
+ const propMetadata = {
363
+ ...meta,
364
+ isRequired: isPartial ? true : hasRequiredArray ? schema.required?.includes(prop) : resolver.options.withImplicitRequiredProps,
365
+ name: prop,
366
+ isParentPartial: isPartial
367
+ };
368
+ let propActualSchema = propSchema;
369
+ if (isReferenceObject(propSchema) && resolver) {
370
+ propActualSchema = resolver.getSchemaByRef(propSchema.$ref);
371
+ if (!propActualSchema) throw new Error(`Schema ${propSchema.$ref} not found`);
372
+ }
373
+ const zodSchema = getZodSchema({
374
+ ...params,
375
+ schema: propSchema,
376
+ meta: propMetadata
377
+ });
378
+ const propZodSchema = zodSchema.getCodeString(tag, resolver.options) + getZodChain({
379
+ schema: propActualSchema,
380
+ meta: propMetadata,
381
+ options: resolver.options
382
+ });
383
+ let isCircular = false;
384
+ const parentRef = getParentRef(inheritedMeta);
385
+ if (parentRef) isCircular = [...isReferenceObject(propSchema) ? [propSchema.$ref] : [], ...getSchemaRefs(zodSchema, { skipObjectSchema: true })].some((ref) => resolver.dependencyGraph.deepDependencyGraph[ref]?.has(parentRef));
386
+ return [
387
+ prop,
388
+ propZodSchema,
389
+ isCircular
390
+ ];
391
+ }).map(([prop, propSchema, isCircular]) => isCircular ? `${wrapWithQuotesIfNeeded(prop)}: z.lazy(() => ${propSchema})` : `${wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
392
+ let additionalPropsSchema = "";
393
+ if (schema.additionalProperties) additionalPropsSchema = `.catchall(${typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0 ? getZodSchema({
394
+ ...params,
395
+ schema: schema.additionalProperties
396
+ }).getCodeString(tag, resolver.options) + getZodChain({
397
+ schema: schema.additionalProperties,
398
+ meta: {
399
+ ...meta,
400
+ isRequired: true
401
+ },
402
+ options: resolver.options
403
+ }) : ANY_SCHEMA})`;
404
+ const zodObject = `z.object(${properties})${isPartial ? ".partial()" : ""}${additionalPropsSchema}${readonly}`;
405
+ return zodSchema.assign(zodObject);
406
+ }
407
+ if (schemaType === "any") return zodSchema.assign(ANY_SCHEMA);
408
+ if (schemaType === "null") return zodSchema.assign("z.null()");
409
+ if (!schemaType) return zodSchema.assign("z.unknown()");
410
+ throw new Error(`Unsupported schema type: ${schemaType}`);
411
+ }
412
+ function getReferenceZodSchema({ schema, zodSchema, resolver, meta, tag }) {
413
+ if (!isReferenceObject(schema)) return;
414
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schema.$ref);
415
+ if (zodSchema.meta.referencedBy.length > 2) {
416
+ const refsPath = zodSchema.meta.referencedBy.slice(0, -1).map((prev) => prev.ref ? resolver.getZodSchemaNameByRef(prev.ref) ?? prev.ref : void 0).filter(Boolean);
417
+ if (refsPath.length > 1 && refsPath.includes(zodSchemaName)) return zodSchema.assign(resolver.getCodeByZodSchemaName(zodSchema.ref));
418
+ }
419
+ let result = resolver.getCodeByZodSchemaName(schema.$ref);
420
+ if (!result) {
421
+ const actualSchema = resolver.getSchemaByRef(schema.$ref);
422
+ if (!actualSchema) throw new Error(`Schema ${schema.$ref} not found`);
423
+ result = getZodSchema({
424
+ schema: actualSchema,
425
+ resolver,
426
+ meta,
427
+ tag
428
+ }).getCodeString(tag, resolver.options);
429
+ }
430
+ if (resolver.getCodeByZodSchemaName(zodSchemaName)) return zodSchema;
431
+ resolver.setZodSchema(zodSchemaName, result, tag);
432
+ return zodSchema;
433
+ }
434
+ function getOneOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
435
+ if (!isSchemaObject(schema) || !schema.oneOf) return;
436
+ if (schema.oneOf.length === 1) {
437
+ const type = getZodSchema({
438
+ schema: schema.oneOf[0],
439
+ resolver,
440
+ meta,
441
+ tag
442
+ });
443
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
444
+ }
445
+ const hasMultipleAllOf = schema.oneOf?.some((obj) => isSchemaObject(obj) && (obj?.allOf || []).length > 1);
446
+ if (schema.discriminator && !hasMultipleAllOf) {
447
+ const propertyName = schema.discriminator.propertyName;
448
+ return zodSchema.assign(`
449
+ z.discriminatedUnion("${propertyName}", [${schema.oneOf.map((schema) => getZodSchema({
450
+ schema,
451
+ resolver,
452
+ meta,
453
+ tag
454
+ }).getCodeString(tag, resolver.options)).join(", ")}])
455
+ `);
456
+ }
457
+ return zodSchema.assign(`z.union([${schema.oneOf.map((schema) => getZodSchema({
458
+ schema,
459
+ resolver,
460
+ meta,
461
+ tag
462
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
463
+ }
464
+ function getArrayZodSchema({ schema, zodSchema, resolver, meta, tag }) {
465
+ if (!isSchemaObject(schema) || !Array.isArray(schema.type)) return;
466
+ if (schema.type.length === 1) return getZodSchema({
467
+ schema: {
468
+ ...schema,
469
+ type: schema.type[0]
470
+ },
471
+ resolver,
472
+ meta,
473
+ tag
474
+ });
475
+ return zodSchema.assign(`z.union([${schema.type.map((prop) => getZodSchema({
476
+ schema: {
477
+ ...schema,
478
+ type: prop
479
+ },
480
+ resolver,
481
+ meta,
482
+ tag
483
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
484
+ }
485
+ function getAnyOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
486
+ if (!isSchemaObject(schema) || !schema.anyOf) return;
487
+ if (schema.anyOf.length === 1) {
488
+ const type = getZodSchema({
489
+ schema: schema.anyOf[0],
490
+ resolver,
491
+ meta,
492
+ tag
493
+ });
494
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
495
+ }
496
+ const types = schema.anyOf.map((schema) => getZodSchema({
497
+ schema,
498
+ resolver,
499
+ meta,
500
+ tag
501
+ })).map((type) => type.getCodeString(tag, resolver.options)).join(", ");
502
+ return zodSchema.assign(`z.union([${types}])`);
503
+ }
504
+ function getAllOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
505
+ if (!isSchemaObject(schema) || !schema.allOf) return;
506
+ if (schema.allOf.length === 1) {
507
+ const type = getZodSchema({
508
+ schema: schema.allOf[0],
509
+ resolver,
510
+ meta,
511
+ tag
512
+ });
513
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
514
+ }
515
+ const { patchRequiredSchemaInLoop, noRequiredOnlyAllof, composedRequiredSchema } = inferRequiredSchema(schema);
516
+ const types = noRequiredOnlyAllof.map((schema) => {
517
+ const type = getZodSchema({
518
+ schema,
519
+ resolver,
520
+ meta,
521
+ tag
522
+ });
523
+ if (resolver) patchRequiredSchemaInLoop(schema, resolver.getSchemaByRef.bind(resolver));
524
+ return type;
525
+ });
526
+ if (composedRequiredSchema.required.length) types.push(getZodSchema({
527
+ schema: composedRequiredSchema,
528
+ resolver,
529
+ meta,
530
+ tag
531
+ }));
532
+ const first = types.at(0);
533
+ const rest = types.slice(1).map((type) => `...${type.getCodeString(tag, resolver.options)}.shape`).join(", ");
534
+ return zodSchema.assign(`z.object({ ...${first.getCodeString(tag, resolver.options)}.shape, ${rest} })`);
535
+ }
536
+ function getPrimitiveZodSchema({ schema, zodSchema, resolver, meta, tag }) {
537
+ if (!isSchemaObject(schema)) return;
538
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
539
+ if (schemaType && isPrimitiveType(schemaType)) {
540
+ if (schema.enum) {
541
+ if (schemaType === "string") return getEnumZodSchema({
542
+ schema,
543
+ zodSchema,
544
+ resolver,
545
+ meta,
546
+ tag
547
+ });
548
+ if (schema.enum.some((e) => typeof e === "string")) return zodSchema.assign("z.never()");
549
+ if (schema.enum.length === 1) {
550
+ const value = schema.enum[0];
551
+ return zodSchema.assign(`z.literal(${value === null ? "null" : value})`);
552
+ }
553
+ return zodSchema.assign(`z.union([${schema.enum.map((value) => `z.literal(${value === null ? "null" : value})`).join(", ")}])`);
554
+ }
555
+ if (schemaType === "integer") return zodSchema.assign(schema.type === "integer" ? INT_SCHEMA : NUMBER_SCHEMA);
556
+ if (schemaType === "string") {
557
+ let stringSchema = STRING_SCHEMA;
558
+ switch (schema.format) {
559
+ case "binary":
560
+ stringSchema = BLOB_SCHEMA;
561
+ break;
562
+ case "email":
563
+ stringSchema = EMAIL_SCHEMA;
564
+ break;
565
+ case "hostname":
566
+ case "uri":
567
+ stringSchema = URL_SCHEMA;
568
+ break;
569
+ case "uuid":
570
+ stringSchema = UUID_SCHEMA;
571
+ break;
572
+ case "date-time": stringSchema = DATETIME_SCHEMA;
573
+ }
574
+ return zodSchema.assign(stringSchema);
575
+ }
576
+ return zodSchema.assign(`z.${schemaType}()`);
577
+ }
578
+ }
579
+ function getEnumZodSchema({ resolver, schema, zodSchema, meta, tag }) {
580
+ if (!isSchemaObject(schema)) return;
581
+ const code = getEnumZodSchemaCode(schema);
582
+ if (!resolver.options.extractEnums || resolver.options.modelsInModules && schema.enum?.length === 1) return zodSchema.assign(code);
583
+ const enumZodSchema = resolver.getEnumZodSchemaDataByCode(code);
584
+ if (enumZodSchema) {
585
+ if (zodSchema.meta.parent?.ref === resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName)) return zodSchema.assign(enumZodSchema.code);
586
+ return new ZodSchema({ $ref: resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName) }, resolver, meta).inherit(zodSchema).assign(code);
587
+ }
588
+ const extractedEnumZodSchema = resolver.getExtractedEnumZodSchemaDataByCode(code);
589
+ if (!extractedEnumZodSchema) return zodSchema.assign(code);
590
+ if (!extractedEnumZodSchema.zodSchemaName || !extractedEnumZodSchema.tag) throw new Error(`Enum zod schema name or tag not resolved for code: ${code}`);
591
+ const namespacePrefix = resolver.options.tsNamespaces && extractedEnumZodSchema.tag !== tag ? `${getNamespaceName({
592
+ type: "models",
593
+ tag: extractedEnumZodSchema.tag,
594
+ options: resolver.options
595
+ })}.` : "";
596
+ return zodSchema.assign(`${namespacePrefix}${extractedEnumZodSchema.zodSchemaName}`);
597
+ }
598
+ function getEnumZodSchemaCode(schema) {
599
+ const values = schema.enum?.filter((value) => value !== null) ?? [];
600
+ return `${ENUM_SCHEMA}([${values.map((value) => `"${value}"`).join(", ")}])`;
601
+ }
602
+ function getEnumZodSchemaCodeFromEnumNames(enumNames) {
603
+ return `${ENUM_SCHEMA}([${enumNames.map((value) => `"${value}"`).join(", ")}])`;
604
+ }
605
+ //#endregion
606
+ //#region src/generators/core/zod/resolveZodSchemaName.ts
607
+ const resolverResolveZodSchemaNameCache = /* @__PURE__ */ new WeakMap();
608
+ function resolveZodSchemaName({ schema, zodSchema, fallbackName, resolver, tag }) {
609
+ const result = zodSchema.getCodeString();
610
+ const cacheKey = `${zodSchema.ref ?? ""}|${fallbackName ?? ""}|${tag}|${zodSchema.complexity}|${result}`;
611
+ let cacheForResolver = resolverResolveZodSchemaNameCache.get(resolver);
612
+ if (!cacheForResolver) {
613
+ cacheForResolver = /* @__PURE__ */ new Map();
614
+ resolverResolveZodSchemaNameCache.set(resolver, cacheForResolver);
615
+ }
616
+ const cachedName = cacheForResolver.get(cacheKey);
617
+ if (cachedName) return cachedName;
618
+ if ((!isNamedZodSchema(result) || zodSchema.ref === void 0) && fallbackName) {
619
+ if (zodSchema.complexity < 2) return result;
620
+ const zodSchemaName = getZodSchemaName(fallbackName, resolver.options.schemaSuffix);
621
+ while (resolver.getCodeByZodSchemaName(zodSchemaName)) if (resolver.getZodSchemaNamesByCompositeCode(result)?.includes(zodSchemaName)) return zodSchemaName;
622
+ else if (resolver.getCodeByZodSchemaName(zodSchemaName) === zodSchemaName) return zodSchemaName;
623
+ else throw new Error(`Can't uniquely resolve zod schema name: ${zodSchemaName}`);
624
+ resolver.setZodSchema(zodSchemaName, result, tag);
625
+ resolver.addZodSchemaForCompositeCode(result, zodSchema, zodSchemaName, schema);
626
+ cacheForResolver.set(cacheKey, zodSchemaName);
627
+ return zodSchemaName;
628
+ }
629
+ let resolvedSchema = resolver.getCodeByZodSchemaName(result);
630
+ if (!resolvedSchema && zodSchema.ref) resolvedSchema = resolver.getCodeByZodSchemaName(resolver.getZodSchemaNameByRef(zodSchema.ref));
631
+ if (zodSchema.ref && resolvedSchema) {
632
+ if (getOpenAPISchemaComplexity(0, resolver.getSchemaByRef(zodSchema.ref)) < 2) {
633
+ const resolvedName = resolver.getCodeByZodSchemaName(result);
634
+ cacheForResolver.set(cacheKey, resolvedName);
635
+ return resolvedName;
636
+ }
637
+ cacheForResolver.set(cacheKey, result);
638
+ return result;
639
+ }
640
+ if (zodSchema.ref) {
641
+ const resolvedRefName = resolver.getZodSchemaNameByRef(zodSchema.ref);
642
+ cacheForResolver.set(cacheKey, resolvedRefName);
643
+ return resolvedRefName;
644
+ }
645
+ throw new Error(`Invalid ref: ${zodSchema.ref}`);
646
+ }
647
+ //#endregion
648
+ //#region src/generators/utils/validation.utils.ts
649
+ function getInvalidSchemaError(message) {
650
+ return {
651
+ type: "invalid-schema",
652
+ message
653
+ };
654
+ }
655
+ function getInvalidOperationIdError(operationId) {
656
+ return {
657
+ type: "invalid-operation-id",
658
+ message: `Operation ${operationId}`
659
+ };
660
+ }
661
+ function getMissingPathParameterError(params, path) {
662
+ return {
663
+ type: "missing-path-parameter",
664
+ message: `Path ${path} is missing [${params.map(({ name }) => name).join(", ")}]`
665
+ };
666
+ }
667
+ function getNotAllowedInlineEnumError(enumProperty) {
668
+ return {
669
+ type: "not-allowed-inline-enum",
670
+ message: `${enumProperty} is missing @IsEnum() and @ApiProperty(enum:, enumName:)`
671
+ };
672
+ }
673
+ function getMissingAclConditionPropertyError(propertyName, operation, endpoint) {
674
+ return {
675
+ type: "missing-acl-condition-property",
676
+ message: `Condition property ${propertyName} is not found in parameters or body in operation ${getOperationDescriptor(operation, endpoint)}`
677
+ };
678
+ }
679
+ function getMissingStatusCodeError(statusCode, operation, endpoint) {
680
+ return {
681
+ type: "missing-status-code",
682
+ message: `Missing HTTP status code ${getStatusCodeDescription(statusCode)} in operation ${getOperationDescriptor(operation, endpoint)}`
683
+ };
684
+ }
685
+ function getInvalidStatusCodeError(statusCode, operation, endpoint) {
686
+ return {
687
+ type: "invalid-status-code",
688
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} expected HTTP status code ${getStatusCodeDescription(statusCode.expected)} but received ${getStatusCodeDescription(statusCode.received)}`
689
+ };
690
+ }
691
+ function getMultipleSuccessStatusCodesError(statusCodes, operation, endpoint) {
692
+ return {
693
+ type: "multiple-success-status-codes",
694
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} has multiple success HTTP status codes: ${statusCodes.map(getStatusCodeDescription).join(", ")}`
695
+ };
696
+ }
697
+ function getOperationDescriptor(operation, endpoint) {
698
+ return operation.operationId ?? `${endpoint.method} ${endpoint.path}`;
699
+ }
700
+ function getStatusCodeDescription(statusCode) {
701
+ return `${statusCode} (${HTTP_STATUS_CODES[statusCode]})`;
702
+ }
703
+ function groupByType(validationErrors) {
704
+ return validationErrors.reduce((acc, err) => ({
705
+ ...acc,
706
+ [err.type]: [...acc[err.type] ?? [], err.message]
707
+ }), {});
708
+ }
709
+ //#endregion
710
+ //#region src/generators/core/endpoints/getEndpointAcl.ts
711
+ function getEndpointAcl({ resolver, endpoint, operation }) {
712
+ const acl = operation["x-acl"];
713
+ return acl?.map((item) => {
714
+ const conditionsTypes = Object.keys(item.conditions ?? {}).reduce((acc, name) => {
715
+ const propertyType = getEndpointAclConditionPropertyType({
716
+ resolver,
717
+ endpoint,
718
+ acl,
719
+ name
720
+ });
721
+ if (!propertyType) {
722
+ resolver.validationErrors.push(getMissingAclConditionPropertyError(name, operation, endpoint));
723
+ return acc;
724
+ }
725
+ return [...acc, propertyType];
726
+ }, []);
727
+ return {
728
+ ...item,
729
+ conditionsTypes
730
+ };
731
+ });
732
+ }
733
+ function getEndpointAclConditionPropertyType({ resolver, endpoint, acl, name }) {
734
+ const conditionPropertyPath = acl[0]?.conditions?.[name];
735
+ if (!conditionPropertyPath) return;
736
+ const pathSplits = conditionPropertyPath.replace(/^\$[^.]*\./, "").split(".");
737
+ let schema = void 0;
738
+ let required = void 0;
739
+ let info = void 0;
740
+ let index = 0;
741
+ const parameter = endpoint.parameters.find(({ name }) => name === pathSplits[index]);
742
+ if (parameter) {
743
+ required = parameter.parameterObject?.required;
744
+ schema = parameter.parameterObject?.schema;
745
+ info = `${parameter.name} ${decapitalize(parameter.type)} parameter`;
746
+ index++;
747
+ } else {
748
+ const bodyParameter = endpoint.parameters.find(({ bodyObject }) => !!bodyObject);
749
+ const matchingMediaType = Object.keys(bodyParameter?.bodyObject?.content ?? {}).find(isParamMediaTypeAllowed);
750
+ if (matchingMediaType) {
751
+ schema = bodyParameter?.bodyObject?.content?.[matchingMediaType]?.schema;
752
+ required = bodyParameter?.bodyObject?.required;
753
+ info = `${isQuery(endpoint) ? "query" : "mutation"} data`;
754
+ if (pathSplits[index]?.startsWith("$")) index++;
755
+ }
756
+ }
757
+ while (schema && index < pathSplits.length) {
758
+ const resolvedSchema = resolver.resolveObject(schema);
759
+ schema = Object.entries(resolvedSchema.properties ?? {}).find(([key]) => key === pathSplits[index])?.[1];
760
+ required = resolvedSchema.required?.includes(pathSplits[index]) ?? false;
761
+ index++;
762
+ }
763
+ if (!schema) return;
764
+ return {
765
+ name,
766
+ type: isReferenceObject(schema) ? void 0 : schema.type,
767
+ zodSchemaName: isReferenceObject(schema) ? resolver.getZodSchemaNameByRef(schema.$ref) : void 0,
768
+ required,
769
+ info
770
+ };
771
+ }
772
+ //#endregion
773
+ //#region src/generators/core/endpoints/resolveEndpointZodSchema.ts
774
+ const resolverEndpointZodSchemaCache = /* @__PURE__ */ new WeakMap();
775
+ function getResolverSchemaCache(resolver) {
776
+ let schemaCache = resolverEndpointZodSchemaCache.get(resolver);
777
+ if (!schemaCache) {
778
+ schemaCache = {
779
+ byObject: /* @__PURE__ */ new WeakMap(),
780
+ byRef: /* @__PURE__ */ new Map()
781
+ };
782
+ resolverEndpointZodSchemaCache.set(resolver, schemaCache);
783
+ }
784
+ return schemaCache;
785
+ }
786
+ function getOrCreateSchemaEntries(schemaCache, schema) {
787
+ if (isReferenceObject(schema)) {
788
+ let entries = schemaCache.byRef.get(schema.$ref);
789
+ if (!entries) {
790
+ entries = /* @__PURE__ */ new Map();
791
+ schemaCache.byRef.set(schema.$ref, entries);
792
+ }
793
+ return entries;
794
+ }
795
+ let entries = schemaCache.byObject.get(schema);
796
+ if (!entries) {
797
+ entries = /* @__PURE__ */ new Map();
798
+ schemaCache.byObject.set(schema, entries);
799
+ }
800
+ return entries;
801
+ }
802
+ function resolveEndpointZodSchema({ resolver, schema, meta, tag, fallbackName, composeBeforeResolve }) {
803
+ const entries = getOrCreateSchemaEntries(getResolverSchemaCache(resolver), schema);
804
+ const isRefSchema = isReferenceObject(schema);
805
+ const normalizedFallbackName = isRefSchema ? "" : fallbackName ?? "";
806
+ const normalizedTag = isRefSchema ? "" : tag;
807
+ const metaKey = `required:${Boolean(meta.isRequired)}|name:${meta.name ?? ""}|parentPartial:${Boolean(meta.isParentPartial)}|fallback:${normalizedFallbackName}|tag:${normalizedTag}|compose:${composeBeforeResolve ? 1 : 0}`;
808
+ const cached = entries.get(metaKey);
809
+ if (cached) return cached;
810
+ const zodSchema = getZodSchema({
811
+ schema,
812
+ resolver,
813
+ meta,
814
+ tag
815
+ });
816
+ const schemaObject = resolver.resolveObject(schema);
817
+ const zodChain = getZodChain({
818
+ schema: schemaObject,
819
+ meta: zodSchema.meta,
820
+ options: resolver.options
821
+ });
822
+ const resolved = composeBeforeResolve ? resolveZodSchemaName({
823
+ schema: schemaObject,
824
+ zodSchema: zodSchema.assign(zodSchema.getCodeString(tag) + zodChain),
825
+ fallbackName,
826
+ resolver,
827
+ tag
828
+ }) : (() => {
829
+ const name = resolveZodSchemaName({
830
+ schema: schemaObject,
831
+ zodSchema,
832
+ fallbackName,
833
+ resolver,
834
+ tag
835
+ });
836
+ return isNamedZodSchema(name) ? name : name + zodChain;
837
+ })();
838
+ entries.set(metaKey, resolved);
839
+ return resolved;
840
+ }
841
+ //#endregion
842
+ //#region src/generators/core/endpoints/getEndpointBody.ts
843
+ function getEndpointBody({ resolver, operation, operationName, isUniqueOperationName, tag }) {
844
+ const requestBodyObj = resolver.resolveObject(operation.requestBody);
845
+ if (!requestBodyObj) return;
846
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
847
+ if (!matchingMediaType) return;
848
+ const schema = requestBodyObj.content?.[matchingMediaType]?.schema;
849
+ if (!schema) return;
850
+ const zodSchema = resolveEndpointZodSchema({
851
+ resolver,
852
+ schema,
853
+ meta: { isRequired: requestBodyObj.required ?? true },
854
+ tag,
855
+ fallbackName: getBodyZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag)),
856
+ composeBeforeResolve: false
857
+ });
858
+ return {
859
+ endpointParameter: {
860
+ name: BODY_PARAMETER_NAME,
861
+ type: "Body",
862
+ description: requestBodyObj.description,
863
+ zodSchema,
864
+ bodyObject: requestBodyObj
865
+ },
866
+ requestFormat: matchingMediaType
867
+ };
868
+ }
869
+ //#endregion
870
+ //#region src/generators/core/endpoints/getEndpointParameter.ts
871
+ function getEndpointParameter({ resolver, param, operationName, isUniqueOperationName, tag }) {
872
+ const paramObj = resolver.resolveObject(param);
873
+ if (!ALLOWED_PATH_IN.includes(paramObj.in)) return;
874
+ let schema = {};
875
+ if (paramObj.content) {
876
+ const mediaTypes = Object.keys(paramObj.content ?? {});
877
+ const matchingMediaType = mediaTypes.find(isParamMediaTypeAllowed);
878
+ if (!matchingMediaType) throw new Error(`Unsupported media type for param ${paramObj.name}: ${mediaTypes.join(", ")}`);
879
+ const mediaTypeObject = paramObj.content?.[matchingMediaType];
880
+ if (!mediaTypeObject) throw new Error(`No content with media type for param ${paramObj.name}: ${matchingMediaType}`);
881
+ schema = mediaTypeObject?.schema ?? mediaTypeObject;
882
+ } else if (paramObj.schema) schema = paramObj.schema;
883
+ if (resolver.options.withDescription && schema) schema.description = (paramObj.description ?? "").trim();
884
+ const fallbackName = getParamZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag), paramObj.name);
885
+ let parameterSortingEnumSchemaName = void 0;
886
+ if (isSortingParameterObject(paramObj, schema, resolver)) {
887
+ const enumZodSchemaName = getEnumZodSchemaName(fallbackName, resolver.options.enumSuffix, resolver.options.schemaSuffix);
888
+ const code = getEnumZodSchemaCodeFromEnumNames(getParameterEnumNames(paramObj, schema) ?? []);
889
+ resolver.setZodSchema(enumZodSchemaName, code, tag);
890
+ parameterSortingEnumSchemaName = enumZodSchemaName;
891
+ }
892
+ const zodSchema = getZodSchema({
893
+ schema,
894
+ resolver,
895
+ meta: { isRequired: paramObj.in === "path" ? true : paramObj.required ?? false },
896
+ tag
897
+ });
898
+ const schemaObject = resolver.resolveObject(schema);
899
+ const zodChain = getZodChain({
900
+ schema: schemaObject,
901
+ meta: (paramObj.in === "query" || paramObj.in === "header") && !paramObj.required && isSchemaObject(schemaObject) && (schemaObject.type === "object" || !!schemaObject.properties && Object.keys(schemaObject.properties).length > 0) ? {
902
+ ...zodSchema.meta,
903
+ isRequired: true
904
+ } : zodSchema.meta,
905
+ options: resolver.options
906
+ });
907
+ const zodSchemaName = resolveZodSchemaName({
908
+ schema: schemaObject,
909
+ zodSchema: zodSchema.assign(zodSchema.getCodeString(tag) + zodChain),
910
+ fallbackName,
911
+ resolver,
912
+ tag
913
+ });
914
+ return {
915
+ name: paramObj.in === "path" ? pathParamToVariableName(paramObj.name) : paramObj.name,
916
+ type: paramObj.in === "header" ? "Header" : paramObj.in === "query" ? "Query" : "Path",
917
+ zodSchema: zodSchemaName,
918
+ parameterObject: paramObj,
919
+ ...parameterSortingEnumSchemaName !== void 0 ? { parameterSortingEnumSchemaName } : {}
920
+ };
921
+ }
922
+ //#endregion
923
+ //#region src/generators/core/endpoints/getEndpointsFromOpenAPIDoc.ts
924
+ function getEndpointsFromOpenAPIDoc(resolver, profiler = new Profiler(false)) {
925
+ const endpoints = [];
926
+ const responseSchemaByRefAndTag = /* @__PURE__ */ new Map();
927
+ for (const context of resolver.getOperationContexts()) {
928
+ const { path, method, operation, operationName, isUniqueOperationName, tag, parameters, responses } = context;
929
+ const invalidOperationId = operation.operationId && operation.operationId !== invalidVariableNameCharactersToCamel(operation.operationId);
930
+ if (operation.operationId && invalidOperationId) resolver.validationErrors.push(getInvalidOperationIdError(operation.operationId));
931
+ const endpoint = {
932
+ method,
933
+ path: replaceHyphenatedPath(path),
934
+ operationName,
935
+ description: operation.description,
936
+ summary: operation.summary,
937
+ tags: operation.tags?.map(formatTag),
938
+ requestFormat: JSON_APPLICATION_FORMAT,
939
+ parameters: [],
940
+ response: "",
941
+ errors: [],
942
+ responseStatusCodes: [],
943
+ mediaUpload: !!operation["x-media-upload"],
944
+ mediaDownload: !!operation["x-media-download"]
945
+ };
946
+ if (operation.requestBody) {
947
+ const body = profiler.runSync("endpoints.body", () => getEndpointBody({
948
+ resolver,
949
+ operation,
950
+ operationName,
951
+ isUniqueOperationName,
952
+ tag
953
+ }));
954
+ if (body) {
955
+ endpoint.parameters.push(body.endpointParameter);
956
+ endpoint.requestFormat = body.requestFormat;
957
+ }
958
+ }
959
+ for (const param of parameters) {
960
+ const endpointParameter = profiler.runSync("endpoints.parameter", () => getEndpointParameter({
961
+ resolver,
962
+ param,
963
+ operationName,
964
+ isUniqueOperationName,
965
+ tag
966
+ }));
967
+ if (endpointParameter) endpoint.parameters.push(endpointParameter);
968
+ }
969
+ const missingPathParameters = getMissingPathParameters(endpoint.path, endpoint.parameters);
970
+ endpoint.parameters.push(...missingPathParameters);
971
+ if (missingPathParameters.length > 0) resolver.validationErrors.push(getMissingPathParameterError(missingPathParameters, path));
972
+ for (const { statusCode, responseObj, matchingMediaType, schema } of responses) {
973
+ endpoint.responseStatusCodes.push(statusCode);
974
+ if (matchingMediaType) {
975
+ const statusNum = Number(statusCode);
976
+ if (isMainResponseStatus(statusNum) || statusCode === "default" && !endpoint.responseFormat) endpoint.responseFormat = matchingMediaType;
977
+ } else if (statusCode === "200") resolver.validationErrors.push(getInvalidStatusCodeError({
978
+ received: "200",
979
+ expected: "204"
980
+ }, operation, endpoint));
981
+ if (schema) {
982
+ const responseCacheKey = isReferenceObject(schema) ? `${schema.$ref}|${tag}` : void 0;
983
+ let resolvedResponse = responseCacheKey ? responseSchemaByRefAndTag.get(responseCacheKey) : void 0;
984
+ if (!resolvedResponse) {
985
+ const zodSchema = profiler.runSync("endpoints.response.zod", () => getZodSchema({
986
+ schema,
987
+ resolver,
988
+ meta: { isRequired: true },
989
+ tag
990
+ }));
991
+ const schemaObject = resolver.resolveObject(schema);
992
+ resolvedResponse = {
993
+ schemaObject,
994
+ responseZodSchema: resolveZodSchemaName({
995
+ schema: schemaObject,
996
+ zodSchema,
997
+ fallbackName: zodSchema.ref ? void 0 : getResponseZodSchemaName({
998
+ statusCode,
999
+ operationName,
1000
+ isUniqueOperationName,
1001
+ tag
1002
+ }),
1003
+ resolver,
1004
+ tag
1005
+ }) + getZodChain({
1006
+ schema: schemaObject,
1007
+ meta: zodSchema.meta,
1008
+ options: resolver.options
1009
+ })
1010
+ };
1011
+ if (responseCacheKey) responseSchemaByRefAndTag.set(responseCacheKey, resolvedResponse);
1012
+ }
1013
+ const { schemaObject, responseZodSchema } = resolvedResponse;
1014
+ const status = Number(statusCode);
1015
+ if (isMainResponseStatus(status) && !endpoint.response) {
1016
+ endpoint.response = responseZodSchema;
1017
+ endpoint.responseObject = responseObj;
1018
+ endpoint.responseDescription = responseObj?.description;
1019
+ } else if (statusCode === "default" && !endpoint.response) {
1020
+ endpoint.response = responseZodSchema;
1021
+ endpoint.responseObject = responseObj;
1022
+ endpoint.responseDescription = responseObj?.description;
1023
+ } else if (statusCode !== "default" && !Number.isNaN(status) && isErrorStatus(status)) {
1024
+ const rawSchema = schemaObject;
1025
+ const domainStr = rawSchema["x-domain-error-domain"];
1026
+ const domainName = rawSchema["x-domain-error-name"];
1027
+ const codeEnumArr = ((rawSchema?.properties)?.code)?.enum;
1028
+ const domainCode = Array.isArray(codeEnumArr) && codeEnumArr.length === 1 && (typeof codeEnumArr[0] === "number" || typeof codeEnumArr[0] === "string") ? codeEnumArr[0] : void 0;
1029
+ endpoint.errors.push({
1030
+ zodSchema: responseZodSchema,
1031
+ status,
1032
+ description: responseObj?.description,
1033
+ ...typeof domainStr === "string" && domainCode !== void 0 ? { domainError: {
1034
+ domain: domainStr,
1035
+ code: domainCode,
1036
+ ...typeof domainName === "string" ? { name: domainName } : {}
1037
+ } } : {}
1038
+ });
1039
+ }
1040
+ } else {
1041
+ const status = Number(statusCode);
1042
+ const responseZodSchema = VOID_SCHEMA;
1043
+ if (statusCode !== "default" && !Number.isNaN(status) && isErrorStatus(status)) endpoint.errors.push({
1044
+ zodSchema: responseZodSchema,
1045
+ status,
1046
+ description: responseObj?.description
1047
+ });
1048
+ }
1049
+ }
1050
+ if (!endpoint.response) endpoint.response = VOID_SCHEMA;
1051
+ const mainStatusCodes = [];
1052
+ for (const { statusCode } of responses) {
1053
+ const status = Number(statusCode);
1054
+ if (isMainResponseStatus(status)) mainStatusCodes.push(status);
1055
+ }
1056
+ if (mainStatusCodes.length > 1) resolver.validationErrors.push(getMultipleSuccessStatusCodesError(mainStatusCodes.map(String), operation, endpoint));
1057
+ const resolvedAcl = getEndpointAcl({
1058
+ resolver,
1059
+ endpoint,
1060
+ operation
1061
+ });
1062
+ if (resolvedAcl?.length) endpoint.acl = resolvedAcl;
1063
+ if (operation.security?.[0].Authorization && !endpoint.responseStatusCodes.includes("401")) resolver.validationErrors.push(getMissingStatusCodeError("401", operation, endpoint));
1064
+ if (endpoint.acl?.[0] && !endpoint.responseStatusCodes.includes("403")) resolver.validationErrors.push(getMissingStatusCodeError("403", operation, endpoint));
1065
+ endpoints.push(endpoint);
1066
+ }
1067
+ return endpoints;
1068
+ }
1069
+ function getMissingPathParameters(path, parameters) {
1070
+ if (!path.includes(":")) return [];
1071
+ const parameterNames = new Set(parameters.map(({ name }) => name));
1072
+ const missingParameters = [];
1073
+ for (const match of path.matchAll(/:([a-zA-Z0-9_]+)/g)) {
1074
+ const name = match[1];
1075
+ if (name && !parameterNames.has(name)) missingParameters.push(getPathParameterFromName(name));
1076
+ }
1077
+ return missingParameters;
1078
+ }
1079
+ function getPathParameterFromName(name) {
1080
+ return {
1081
+ name,
1082
+ type: "Path",
1083
+ zodSchema: STRING_SCHEMA,
1084
+ parameterObject: {
1085
+ name,
1086
+ required: true,
1087
+ in: "path",
1088
+ schema: { type: "string" }
1089
+ }
1090
+ };
1091
+ }
1092
+ //#endregion
1093
+ //#region src/generators/const/js.const.ts
1094
+ const RESERVED_WORDS = [
1095
+ "break",
1096
+ "case",
1097
+ "catch",
1098
+ "class",
1099
+ "const",
1100
+ "continue",
1101
+ "debugger",
1102
+ "default",
1103
+ "delete",
1104
+ "do",
1105
+ "else",
1106
+ "export",
1107
+ "extends",
1108
+ "false",
1109
+ "finally",
1110
+ "for",
1111
+ "function",
1112
+ "if",
1113
+ "import",
1114
+ "in",
1115
+ "instanceof",
1116
+ "new",
1117
+ "null",
1118
+ "return",
1119
+ "super",
1120
+ "switch",
1121
+ "this",
1122
+ "throw",
1123
+ "true",
1124
+ "try",
1125
+ "typeof",
1126
+ "var",
1127
+ "void",
1128
+ "while",
1129
+ "with"
1130
+ ];
1131
+ //#endregion
1132
+ //#region src/generators/utils/operation.utils.ts
1133
+ function isOperationExcluded(operation, options) {
1134
+ const isDeprecated = operation.deprecated && !options.withDeprecatedEndpoints;
1135
+ const tag = getOperationTag(operation, options);
1136
+ const isIncluded = isTagIncluded(tag, options);
1137
+ return isDeprecated || !isIncluded;
1138
+ }
1139
+ function getOperationName({ path, method, operation, options, tag, keepOperationTag, keepOperationPrefix }) {
1140
+ return resolveOperationName({
1141
+ path,
1142
+ method,
1143
+ operation,
1144
+ options,
1145
+ tag,
1146
+ keepOperationTag,
1147
+ keepOperationPrefix
1148
+ }).name;
1149
+ }
1150
+ function resolveOperationName({ path, method, operation, options, tag, keepOperationTag, keepOperationPrefix }) {
1151
+ const usesPathAsSource = !operation.operationId;
1152
+ let pathOperationName;
1153
+ let operationName;
1154
+ if (operation.operationId) operationName = invalidVariableNameCharactersToCamel(operation.operationId);
1155
+ else {
1156
+ pathOperationName = `${method}${pathToVariableName(path)}`;
1157
+ operationName = pathOperationName;
1158
+ }
1159
+ if (options.removeOperationPrefixEndingWith && keepOperationPrefix) operationName = operationName.split(options.removeOperationPrefixEndingWith).map((split, index) => index === 0 ? split : capitalize(split)).join("");
1160
+ else if (options.removeOperationPrefixEndingWith && !keepOperationPrefix) {
1161
+ const regex = new RegExp(`^.*${options.removeOperationPrefixEndingWith}`);
1162
+ operationName = operationName.replace(regex, "");
1163
+ }
1164
+ if ((options.tsNamespaces || options.treeShakeableNamespaces) && !keepOperationTag) {
1165
+ const operationNameWithoutTag = removeWord(operationName, tag);
1166
+ if (operationNameWithoutTag === "") operationName = method.toLowerCase();
1167
+ else if (!RESERVED_WORDS.includes(operationNameWithoutTag)) operationName = operationNameWithoutTag;
1168
+ }
1169
+ const usesReservedWordFallback = RESERVED_WORDS.includes(operationName);
1170
+ if (usesReservedWordFallback && pathOperationName === void 0) pathOperationName = `${method}${pathToVariableName(path)}`;
1171
+ return {
1172
+ name: usesReservedWordFallback ? pathOperationName : operationName,
1173
+ usesPathAsSource,
1174
+ usesReservedWordFallback
1175
+ };
1176
+ }
1177
+ function createOperationNameIndex({ operations, options, tag, keepOperationTag }) {
1178
+ const index = {
1179
+ stableCounts: /* @__PURE__ */ new Map(),
1180
+ pathSourceCount: 0,
1181
+ reservedFallbackCount: 0
1182
+ };
1183
+ for (const operation of operations) {
1184
+ if (!operation.operationId) {
1185
+ index.pathSourceCount++;
1186
+ continue;
1187
+ }
1188
+ const result = resolveOperationName({
1189
+ path: "",
1190
+ method: "",
1191
+ operation,
1192
+ options,
1193
+ tag,
1194
+ keepOperationTag
1195
+ });
1196
+ if (result.usesReservedWordFallback) index.reservedFallbackCount++;
1197
+ else index.stableCounts.set(result.name, (index.stableCounts.get(result.name) ?? 0) + 1);
1198
+ }
1199
+ return index;
1200
+ }
1201
+ function getUniqueOperationName({ operationsByTag, nameIndexes, ...params }) {
1202
+ const { operation, options } = params;
1203
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
1204
+ const operationName = (keepOperationTag, nameIndex) => {
1205
+ const name = getOperationName({
1206
+ ...params,
1207
+ tag,
1208
+ keepOperationTag
1209
+ });
1210
+ if (nameIndex) {
1211
+ const pathSourceMatches = nameIndex.pathSourceCount > 0 && getOperationName({
1212
+ ...params,
1213
+ operation: {},
1214
+ tag,
1215
+ keepOperationTag
1216
+ }) === name;
1217
+ const pathFallbackMatches = nameIndex.reservedFallbackCount > 0 && `${params.method}${pathToVariableName(params.path)}` === name;
1218
+ return (nameIndex.stableCounts.get(name) ?? 0) + (pathSourceMatches ? nameIndex.pathSourceCount : 0) + (pathFallbackMatches ? nameIndex.reservedFallbackCount : 0) === 1 ? name : void 0;
1219
+ }
1220
+ let matchingOperations = 0;
1221
+ for (const candidate of operationsByTag[tag]) if (getOperationName({
1222
+ ...params,
1223
+ operation: candidate,
1224
+ tag,
1225
+ keepOperationTag
1226
+ }) === name) {
1227
+ matchingOperations++;
1228
+ if (matchingOperations > 1) return;
1229
+ }
1230
+ if (matchingOperations === 1) return name;
1231
+ };
1232
+ return operationName(void 0, nameIndexes?.[0]) ?? operationName(true, nameIndexes?.[1]) ?? getOperationName({
1233
+ ...params,
1234
+ tag,
1235
+ keepOperationTag: true,
1236
+ keepOperationPrefix: true
1237
+ });
1238
+ }
1239
+ function getUniqueOperationNamesFromIndex(indexedOperations, operationsByTag, options, operationNameByOperation) {
1240
+ const operationNames = [];
1241
+ const nameIndexesByTag = /* @__PURE__ */ new Map();
1242
+ for (const { path, method, operation, tag } of indexedOperations) {
1243
+ let nameIndexes = nameIndexesByTag.get(tag);
1244
+ if (!nameIndexes) {
1245
+ const operations = operationsByTag[tag];
1246
+ nameIndexes = [createOperationNameIndex({
1247
+ operations,
1248
+ options,
1249
+ tag
1250
+ }), createOperationNameIndex({
1251
+ operations,
1252
+ options,
1253
+ tag,
1254
+ keepOperationTag: true
1255
+ })];
1256
+ nameIndexesByTag.set(tag, nameIndexes);
1257
+ }
1258
+ const operationName = getUniqueOperationName({
1259
+ path,
1260
+ method,
1261
+ operation,
1262
+ operationsByTag,
1263
+ options,
1264
+ nameIndexes
1265
+ });
1266
+ operationNameByOperation?.set(operation, operationName);
1267
+ operationNames.push(operationName);
1268
+ }
1269
+ return operationNames;
1270
+ }
1271
+ function getOperationIndex(openApiDoc, options) {
1272
+ const operationsByTag = {};
1273
+ const indexedOperations = [];
1274
+ for (const path in openApiDoc.paths) {
1275
+ if (isPathExcluded(path, options)) continue;
1276
+ const pathItemObj = openApiDoc.paths[path];
1277
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
1278
+ for (const method in pathItem) {
1279
+ const operation = pathItem[method];
1280
+ if (!operation || isOperationExcluded(operation, options)) continue;
1281
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
1282
+ (operationsByTag[tag] ??= []).push(operation);
1283
+ indexedOperations.push({
1284
+ path,
1285
+ method,
1286
+ operation,
1287
+ tag,
1288
+ pathParameters: pathItemObj.parameters
1289
+ });
1290
+ }
1291
+ }
1292
+ const operationNameByOperation = /* @__PURE__ */ new WeakMap();
1293
+ return {
1294
+ operationsByTag,
1295
+ operationNames: getUniqueOperationNamesFromIndex(indexedOperations, operationsByTag, options, operationNameByOperation),
1296
+ operationNameByOperation,
1297
+ indexedOperations
1298
+ };
1299
+ }
1300
+ //#endregion
1301
+ //#region src/generators/core/openapi/getOpenAPISchemaDependencyGraph.ts
1302
+ function getOpenAPISchemaDependencyGraph(schemaRef, getSchemaByRef) {
1303
+ const refsDependencyGraph = getRefsDependencyGraph(schemaRef, getSchemaByRef);
1304
+ return {
1305
+ refsDependencyGraph,
1306
+ deepDependencyGraph: getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph)
1307
+ };
1308
+ }
1309
+ function getRefsDependencyGraph(schemaRef, getSchemaByRef) {
1310
+ const visitedRefs = {};
1311
+ const refsDependencyGraph = {};
1312
+ schemaRef.forEach((ref) => getSchemaRefsDependencyGraph({
1313
+ schema: getSchemaByRef(ref),
1314
+ fromRef: ref,
1315
+ getSchemaByRef,
1316
+ visitedRefs,
1317
+ refsDependencyGraph
1318
+ }));
1319
+ return refsDependencyGraph;
1320
+ }
1321
+ function getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph) {
1322
+ const visitedDeepRefs = {};
1323
+ const deepDependencyGraph = {};
1324
+ const visit = (dep, ref) => {
1325
+ deepDependencyGraph[ref].add(dep);
1326
+ if (refsDependencyGraph[dep] && ref !== dep) refsDependencyGraph[dep].forEach((transitive) => {
1327
+ const refName = `${ref}__${transitive}`;
1328
+ if (visitedDeepRefs[refName]) return;
1329
+ visitedDeepRefs[refName] = true;
1330
+ visit(transitive, ref);
1331
+ });
1332
+ };
1333
+ schemaRef.forEach((ref) => {
1334
+ const deps = refsDependencyGraph[ref];
1335
+ if (!deps) return;
1336
+ if (!deepDependencyGraph[ref]) deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
1337
+ deps.forEach((dep) => visit(dep, ref));
1338
+ });
1339
+ return deepDependencyGraph;
1340
+ }
1341
+ function getSchemaRefsDependencyGraph({ schema, fromRef, getSchemaByRef, visitedRefs = {}, refsDependencyGraph = {} }) {
1342
+ const onSchema = (callbackData) => {
1343
+ if (callbackData.type !== "reference" || !callbackData.data) return;
1344
+ const { schema, data } = callbackData;
1345
+ if (!refsDependencyGraph[data.fromRef]) refsDependencyGraph[data.fromRef] = /* @__PURE__ */ new Set();
1346
+ refsDependencyGraph[data.fromRef].add(schema.$ref);
1347
+ if (visitedRefs[schema.$ref]) return true;
1348
+ visitedRefs[data.fromRef] = true;
1349
+ iterateSchema(getSchemaByRef(schema.$ref), {
1350
+ data: { fromRef: schema.$ref },
1351
+ onSchema
1352
+ });
1353
+ };
1354
+ iterateSchema(schema, {
1355
+ data: { fromRef },
1356
+ onSchema
1357
+ });
1358
+ return {
1359
+ visitedRefs,
1360
+ refsDependencyGraph
1361
+ };
1362
+ }
1363
+ //#endregion
1364
+ //#region src/generators/core/openapi/getSchemaRefObjs.ts
1365
+ function getSchemaRefObjs(resolver, schema, schemaInfo) {
1366
+ const schemaRefObjs = [];
1367
+ const onSchema = (data) => {
1368
+ if (data.type === "reference") schemaRefObjs.push(data.schema);
1369
+ else if (isReferenceObject(data.parentSchema)) {
1370
+ if (data.type === "property") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and properties`));
1371
+ else if (data.type === "additionalProperties") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and additionalProperties`));
1372
+ else if (data.type === "array") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} is both reference and array schema`));
1373
+ else if (data.type === "composite") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and composite keyword`));
1374
+ }
1375
+ };
1376
+ iterateSchema(schema, { onSchema });
1377
+ return schemaRefObjs;
1378
+ }
1379
+ function getDeepSchemaRefObjs(resolver, schemaRefs) {
1380
+ return schemaRefs.map((schemaRef) => autocorrectRef(schemaRef.$ref)).reduce((acc, schemaRef) => {
1381
+ const refs = resolver.dependencyGraph.deepDependencyGraph[schemaRef];
1382
+ return [
1383
+ ...acc,
1384
+ schemaRef,
1385
+ ...Array.from(refs ?? [])
1386
+ ];
1387
+ }, []);
1388
+ }
1389
+ //#endregion
1390
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.ts
1391
+ function resolveExtractedEnumZodSchemaNames(resolver) {
1392
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
1393
+ const lastSegements = enumData.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - 1]).filter(Boolean);
1394
+ const mostCommonLastSegment = getMostCommonAdjacentCombinationSplit(lastSegements);
1395
+ if (!mostCommonLastSegment) throw new Error(`No common last segment found for enum: ${enumData.code}`);
1396
+ enumData.zodSchemaName = getEnumZodSchemaName(mostCommonLastSegment, resolver.options.enumSuffix, resolver.options.schemaSuffix);
1397
+ });
1398
+ let nameResolutionIterationsCounter = 0;
1399
+ while (nameResolutionIterationsCounter < 5) {
1400
+ if (allExtractedEnumZodSchemaNamesAreUnique(resolver)) break;
1401
+ additionalResolveExtractedEnumZodSchemaName(resolver, nameResolutionIterationsCounter + 2);
1402
+ nameResolutionIterationsCounter++;
1403
+ }
1404
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) resolver.extractedEnumZodSchemaData.filter((enumData) => !isUnique(resolver, enumData)).forEach((enumData) => {
1405
+ enumData.zodSchemaName = getEnumZodSchemaName(enumData.meta.zodSchemaNameSegments[0].map((name) => sanitizeName(capitalize(name))).join(""), resolver.options.enumSuffix, resolver.options.schemaSuffix);
1406
+ });
1407
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) throw new Error("Failed to resolve unique names for enum zod schemas");
1408
+ }
1409
+ function allExtractedEnumZodSchemaNamesAreUnique(resolver) {
1410
+ return resolver.extractedEnumZodSchemaData.every((enumData) => isUnique(resolver, enumData));
1411
+ }
1412
+ function additionalResolveExtractedEnumZodSchemaName(resolver, index) {
1413
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
1414
+ const enumsDataWithSameName = resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName);
1415
+ if (enumsDataWithSameName.length === 1) return;
1416
+ suffixWithPreviousSegmentName(enumsDataWithSameName, index);
1417
+ });
1418
+ }
1419
+ function suffixWithPreviousSegmentName(enumsData, index = 2) {
1420
+ enumsData.forEach((data) => {
1421
+ const precedingLastFragments = data.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - index]).filter(Boolean);
1422
+ if (precedingLastFragments.length === 1) data.zodSchemaName = [sanitizeName(capitalize(precedingLastFragments[0])), data.zodSchemaName].filter(Boolean).join("");
1423
+ else {
1424
+ const secondLastFragmentSplit = getMostCommonAdjacentCombinationSplit(precedingLastFragments);
1425
+ data.zodSchemaName = [secondLastFragmentSplit ? sanitizeName(capitalize(secondLastFragmentSplit)) : "", data.zodSchemaName].filter(Boolean).join("");
1426
+ }
1427
+ });
1428
+ }
1429
+ function isUnique(resolver, enumData) {
1430
+ return resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName).length === 1;
1431
+ }
1432
+ function sanitizeName(name) {
1433
+ return name.replace(/(Dto|DTO|Response|Request)/g, "");
1434
+ }
1435
+ //#endregion
1436
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.ts
1437
+ function resolveExtractedEnumZodSchemaTags(resolver) {
1438
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
1439
+ const tags = getUniqueArray(enumData.meta.tags);
1440
+ enumData.tag = tags.length === 1 ? tags[0] : resolver.options.defaultTag;
1441
+ });
1442
+ }
1443
+ //#endregion
1444
+ //#region src/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.ts
1445
+ function updateExtractedEnumZodSchemaData({ schema, nameSegments = [], includeSelf, ...params }) {
1446
+ if (!isReferenceObject(schema) && schema?.["x-domain-error-domain"]) return;
1447
+ if (includeSelf) handleExtractedEnumZodSchemaDataUpdate({
1448
+ schema,
1449
+ nameSegments,
1450
+ ...params
1451
+ });
1452
+ const onSchema = (data) => {
1453
+ if (data.type === "reference") return true;
1454
+ const segments = [...data.data?.nameSegments ?? []];
1455
+ if (data.type === "property") segments.push(data.propertyName);
1456
+ handleExtractedEnumZodSchemaDataUpdate({
1457
+ schema: data.schema,
1458
+ nameSegments: [...segments],
1459
+ ...params
1460
+ });
1461
+ };
1462
+ iterateSchema(schema, {
1463
+ data: { nameSegments },
1464
+ onSchema
1465
+ });
1466
+ }
1467
+ function handleExtractedEnumZodSchemaDataUpdate({ resolver, schema, schemaRef, schemaInfo, tags, nameSegments = [] }) {
1468
+ if (!schema || isReferenceObject(schema) || !schema.enum) return;
1469
+ const code = getEnumZodSchemaCode(schema);
1470
+ const enumZodSchema = resolver.extractedEnumZodSchemaData.find((data) => data.code === code);
1471
+ if (enumZodSchema) {
1472
+ enumZodSchema.meta.zodSchemaNameSegments.push(nameSegments);
1473
+ enumZodSchema.meta.tags.push(...tags);
1474
+ enumZodSchema.meta.schemaRefs.push(...schemaRef ? [schemaRef] : []);
1475
+ enumZodSchema.meta.schemas.push(...schema ? [schema] : []);
1476
+ } else resolver.extractedEnumZodSchemaData.push({
1477
+ code,
1478
+ meta: {
1479
+ zodSchemaNameSegments: [nameSegments],
1480
+ tags: [...tags],
1481
+ schemaRefs: schemaRef ? [schemaRef] : [],
1482
+ schemas: schema ? [schema] : []
1483
+ }
1484
+ });
1485
+ resolver.validationErrors.push(getNotAllowedInlineEnumError(schemaRef ? `${getSchemaNameByRef(schemaRef)}.${nameSegments[nameSegments.length - 1]}` : schemaInfo ?? nameSegments.join(".")));
1486
+ }
1487
+ //#endregion
1488
+ //#region src/generators/core/zod/getZodSchemasFromOpenAPIDoc.ts
1489
+ function getZodSchemasFromOpenAPIDoc(resolver, profiler) {
1490
+ const p = profiler ?? new Profiler(false);
1491
+ const zodSchemas = {};
1492
+ const enumZodSchemas = {};
1493
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => p.runSync("zod.extract.schemaEntry", () => {
1494
+ const schemaData = resolver.getSchemaDataByName(name);
1495
+ if (resolver.options.excludeRedundantZodSchemas && (!schemaData || schemaData.deepRefOperations.length === 0 && schemaData.tags.length === 0)) return;
1496
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
1497
+ if (zodSchemas[zodSchemaName]) return;
1498
+ const tag = resolver.getTagByZodSchemaName(zodSchemaName);
1499
+ const schemaObject = resolver.resolveObject(schema);
1500
+ if (schemaObject.enum) enumZodSchemas[zodSchemaName] = getEnumZodSchemaCode(schemaObject);
1501
+ else {
1502
+ const existingCode = resolver.getCodeByZodSchemaName(zodSchemaName);
1503
+ if (existingCode !== void 0) {
1504
+ zodSchemas[zodSchemaName] = existingCode;
1505
+ return;
1506
+ }
1507
+ zodSchemas[zodSchemaName] = p.runSync("zod.extract.schemaToCode", () => getZodSchema({
1508
+ schema,
1509
+ resolver,
1510
+ tag
1511
+ }).getCodeString(tag));
1512
+ }
1513
+ }));
1514
+ return {
1515
+ zodSchemas,
1516
+ enumZodSchemas
1517
+ };
1518
+ }
1519
+ function getEnumZodSchemasFromOpenAPIDoc(resolver) {
1520
+ const enumZodSchemas = [];
1521
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => {
1522
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
1523
+ const schemaObject = resolver.resolveObject(schema);
1524
+ if (schemaObject.enum) enumZodSchemas.push({
1525
+ zodSchemaName,
1526
+ code: getEnumZodSchemaCode(schemaObject)
1527
+ });
1528
+ });
1529
+ return enumZodSchemas;
1530
+ }
1531
+ //#endregion
1532
+ //#region src/generators/core/SchemaResolver.class.ts
1533
+ var SchemaResolver = class {
1534
+ openApiDoc;
1535
+ options;
1536
+ profiler;
1537
+ schemaData = [];
1538
+ zodSchemaData = [];
1539
+ compositeZodSchemaData = [];
1540
+ schemaRefs;
1541
+ schemaByRef = /* @__PURE__ */ new Map();
1542
+ schemaDataByRef = /* @__PURE__ */ new Map();
1543
+ schemaDataByName = /* @__PURE__ */ new Map();
1544
+ refByZodSchemaName = /* @__PURE__ */ new Map();
1545
+ zodSchemaDataByName = /* @__PURE__ */ new Map();
1546
+ compositeByCode = /* @__PURE__ */ new Map();
1547
+ compositeSchemaByZodSchemaName = /* @__PURE__ */ new Map();
1548
+ dependencyGraph;
1549
+ enumZodSchemas = [];
1550
+ extractedEnumZodSchemaData = [];
1551
+ operationsByTag = {};
1552
+ operationNames = [];
1553
+ operationNameCounts = /* @__PURE__ */ new Map();
1554
+ operationNameByOperation;
1555
+ indexedOperations;
1556
+ operationContexts = [];
1557
+ zodSchemaTagCache;
1558
+ validationErrors = [];
1559
+ get docSchemas() {
1560
+ return this.openApiDoc.components?.schemas ?? {};
1561
+ }
1562
+ constructor(openApiDoc, options, profiler) {
1563
+ this.openApiDoc = openApiDoc;
1564
+ this.options = options;
1565
+ this.profiler = profiler;
1566
+ const p = profiler ?? new Profiler(false);
1567
+ this.schemaRefs = p.runSync("resolver.construct.schemaRefs", () => Object.keys(this.docSchemas).map(getSchemaRef));
1568
+ this.dependencyGraph = p.runSync("resolver.construct.dependencyGraph", () => getOpenAPISchemaDependencyGraph(this.schemaRefs, this.getSchemaByRef.bind(this)));
1569
+ this.enumZodSchemas = p.runSync("resolver.construct.enums", () => getEnumZodSchemasFromOpenAPIDoc(this));
1570
+ const operationIndex = p.runSync("resolver.construct.operationIndex", () => getOperationIndex(openApiDoc, options));
1571
+ this.operationsByTag = operationIndex.operationsByTag;
1572
+ this.operationNames = operationIndex.operationNames;
1573
+ this.operationNameByOperation = operationIndex.operationNameByOperation;
1574
+ this.indexedOperations = operationIndex.indexedOperations;
1575
+ p.runSync("resolver.construct.operationNameCounts", () => {
1576
+ for (const name of this.operationNames) this.operationNameCounts.set(name, (this.operationNameCounts.get(name) ?? 0) + 1);
1577
+ });
1578
+ this.initialize();
1579
+ }
1580
+ getSchemaByRef(ref) {
1581
+ const correctRef = autocorrectRef(ref);
1582
+ const cachedSchema = this.schemaByRef.get(correctRef);
1583
+ if (cachedSchema) return cachedSchema;
1584
+ const schema = this.docSchemas[getSchemaNameByRef(correctRef)];
1585
+ this.schemaByRef.set(correctRef, schema);
1586
+ return schema;
1587
+ }
1588
+ getSchemaDataByName(name) {
1589
+ return this.schemaDataByName.get(name);
1590
+ }
1591
+ getZodSchemaNameByRef(ref) {
1592
+ const zodSchemaName = this.getSchemaDataByRef(autocorrectRef(ref))?.zodSchemaName ?? this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === ref)?.zodSchemaName;
1593
+ if (!zodSchemaName) throw new Error(`Zod schema not found for ref: ${ref}`);
1594
+ return zodSchemaName;
1595
+ }
1596
+ getRefByZodSchemaName(zodSchemaName) {
1597
+ return this.refByZodSchemaName.get(zodSchemaName);
1598
+ }
1599
+ getTagByZodSchemaName(zodSchemaName) {
1600
+ const cachedTag = this.zodSchemaTagCache?.get(zodSchemaName);
1601
+ if (cachedTag) return cachedTag;
1602
+ const tag = this.resolveTagByZodSchemaName(zodSchemaName);
1603
+ this.zodSchemaTagCache?.set(zodSchemaName, tag);
1604
+ return tag;
1605
+ }
1606
+ getTagsByZodSchemaName(zodSchemaName) {
1607
+ if (!this.options.splitByTags) return [formatTag(this.options.defaultTag)];
1608
+ const extractedEnum = this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === zodSchemaName);
1609
+ if (extractedEnum) {
1610
+ const tags = getUniqueArray(extractedEnum.meta.tags);
1611
+ return (tags.length > 0 ? tags : [extractedEnum.tag ?? this.options.defaultTag]).map(formatTag);
1612
+ }
1613
+ const schemaRef = this.getRefByZodSchemaName(zodSchemaName);
1614
+ const tags = getUniqueArray(schemaRef ? this.getSchemaDataByRef(schemaRef)?.tags ?? [] : [], this.zodSchemaDataByName.get(zodSchemaName)?.tags ?? []);
1615
+ return (tags.length > 0 ? tags : [this.options.defaultTag]).map(formatTag);
1616
+ }
1617
+ enableZodSchemaTagCache() {
1618
+ this.zodSchemaTagCache = /* @__PURE__ */ new Map();
1619
+ }
1620
+ resolveTagByZodSchemaName(zodSchemaName) {
1621
+ if (!this.options.splitByTags) return this.options.defaultTag;
1622
+ if (this.options.modelsInCommon) return formatTag(this.options.defaultTag);
1623
+ const extractedEnumZodSchema = this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === zodSchemaName);
1624
+ if (extractedEnumZodSchema) return formatTag(extractedEnumZodSchema.tag ?? this.options.defaultTag);
1625
+ const schemaRef = this.getRefByZodSchemaName(zodSchemaName);
1626
+ const schemaTags = schemaRef ? this.getSchemaDataByRef(schemaRef)?.tags ?? [] : [];
1627
+ const zodSchemaTags = this.zodSchemaDataByName.get(zodSchemaName)?.tags ?? [];
1628
+ const tags = getUniqueArray(schemaTags, zodSchemaTags);
1629
+ const tag = tags.length === 1 ? tags[0] : this.options.defaultTag;
1630
+ return formatTag(tag ?? this.options.defaultTag);
1631
+ }
1632
+ getCodeByZodSchemaName(name) {
1633
+ return this.zodSchemaDataByName.get(name)?.code;
1634
+ }
1635
+ getZodSchemaNamesByCompositeCode(code) {
1636
+ return this.compositeByCode.get(code)?.zodSchemas.map((schema) => schema.zodSchemaName);
1637
+ }
1638
+ setZodSchema(name, code, tag) {
1639
+ const zodSchema = this.zodSchemaDataByName.get(name);
1640
+ if (zodSchema) {
1641
+ zodSchema.code = code;
1642
+ zodSchema.tags = (zodSchema.tags ?? []).concat(tag);
1643
+ } else {
1644
+ const newZodSchemaData = {
1645
+ zodSchemaName: name,
1646
+ code,
1647
+ tags: [tag]
1648
+ };
1649
+ this.zodSchemaData.push(newZodSchemaData);
1650
+ this.zodSchemaDataByName.set(name, newZodSchemaData);
1651
+ }
1652
+ }
1653
+ addZodSchemaForCompositeCode(code, zodSchema, zodSchemaName, schema) {
1654
+ const compositeZodSchema = {
1655
+ zodSchemaName,
1656
+ zodSchema,
1657
+ schema
1658
+ };
1659
+ const compositeData = this.compositeByCode.get(code);
1660
+ if (compositeData) compositeData.zodSchemas.push(compositeZodSchema);
1661
+ else {
1662
+ const newCompositeData = {
1663
+ code,
1664
+ zodSchemas: [compositeZodSchema]
1665
+ };
1666
+ this.compositeZodSchemaData.push(newCompositeData);
1667
+ this.compositeByCode.set(code, newCompositeData);
1668
+ }
1669
+ this.compositeSchemaByZodSchemaName.set(zodSchemaName, {
1670
+ zodSchema,
1671
+ schema
1672
+ });
1673
+ }
1674
+ getCompositeZodSchemaByZodSchemaName(zodSchemaName) {
1675
+ return this.compositeSchemaByZodSchemaName.get(zodSchemaName)?.zodSchema;
1676
+ }
1677
+ getSchemaByCompositeZodSchemaName(compositeZodSchemaName) {
1678
+ return this.compositeSchemaByZodSchemaName.get(compositeZodSchemaName)?.schema;
1679
+ }
1680
+ getEnumZodSchemaDataByCode(code) {
1681
+ return this.enumZodSchemas.find((data) => data.code === code);
1682
+ }
1683
+ getExtractedEnumZodSchemaDataByCode(code) {
1684
+ return this.extractedEnumZodSchemaData.find((data) => data.code === code);
1685
+ }
1686
+ getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef) {
1687
+ return this.extractedEnumZodSchemaData.reduce((acc, { zodSchemaName, meta }) => {
1688
+ if (zodSchemaName && meta.schemaRefs.includes(schemaRef)) return [...acc, zodSchemaName];
1689
+ return acc;
1690
+ }, []);
1691
+ }
1692
+ getZodSchemas() {
1693
+ const zodSchemas = {};
1694
+ for (const { zodSchemaName, code } of this.zodSchemaData) zodSchemas[zodSchemaName] = code;
1695
+ return zodSchemas;
1696
+ }
1697
+ getExtractedEnumZodSchemas() {
1698
+ const zodSchemas = {};
1699
+ for (const { zodSchemaName, code } of this.extractedEnumZodSchemaData) if (zodSchemaName) zodSchemas[zodSchemaName] = code;
1700
+ return zodSchemas;
1701
+ }
1702
+ resolveObject(obj) {
1703
+ return isReferenceObject(obj) ? this.getSchemaByRef(obj.$ref) : obj;
1704
+ }
1705
+ isSchemaCircular(ref) {
1706
+ return this.dependencyGraph.deepDependencyGraph[ref]?.has(ref);
1707
+ }
1708
+ getCircularSchemaChain(ref, currentRef = ref, chain = [], visited = []) {
1709
+ if (visited.includes(currentRef)) return [];
1710
+ visited.push(currentRef);
1711
+ if (this.dependencyGraph.refsDependencyGraph[currentRef]?.has(ref)) return [
1712
+ ...chain,
1713
+ currentRef,
1714
+ ref
1715
+ ];
1716
+ return Array.from(this.dependencyGraph.refsDependencyGraph[currentRef]?.values() ?? []).flatMap((childRef) => {
1717
+ const childChain = this.getCircularSchemaChain(ref, childRef, chain, visited);
1718
+ return childChain.length > 0 ? [currentRef, ...childChain] : childChain;
1719
+ });
1720
+ }
1721
+ getBaseUrl() {
1722
+ const serverUrl = this.openApiDoc.servers?.[0]?.url;
1723
+ if (this.options.baseUrl === "" && serverUrl) return serverUrl;
1724
+ return this.options.baseUrl;
1725
+ }
1726
+ isOperationNameUnique(operationName) {
1727
+ return (this.operationNameCounts.get(operationName) ?? 0) <= 1;
1728
+ }
1729
+ getOperationContexts() {
1730
+ return this.operationContexts;
1731
+ }
1732
+ getZodSchemaObj(zodSchemaName) {
1733
+ const ref = this.getRefByZodSchemaName(zodSchemaName);
1734
+ if (ref) return this.getSchemaByRef(ref);
1735
+ const schema = this.getSchemaByCompositeZodSchemaName(zodSchemaName);
1736
+ if (schema) return schema;
1737
+ const enumZodSchemaData = this.getExtractedEnumZodSchemaDataByName(zodSchemaName);
1738
+ if (enumZodSchemaData) {
1739
+ const schemaObject = {};
1740
+ for (const schema of enumZodSchemaData.meta.schemas) Object.assign(schemaObject, this.resolveObject(schema));
1741
+ return schemaObject;
1742
+ }
1743
+ }
1744
+ getSchemaDataByRef(ref) {
1745
+ return this.schemaDataByRef.get(ref);
1746
+ }
1747
+ getExtractedEnumZodSchemaDataByName(enumZodSchemaName) {
1748
+ return this.extractedEnumZodSchemaData.find(({ zodSchemaName }) => zodSchemaName === enumZodSchemaName);
1749
+ }
1750
+ initialize() {
1751
+ const p = this.profiler ?? new Profiler(false);
1752
+ p.runSync("resolver.init.seedSchemas", () => {
1753
+ this.schemaRefs.forEach((ref) => {
1754
+ const correctRef = autocorrectRef(ref);
1755
+ const name = getSchemaNameByRef(correctRef);
1756
+ const zodSchemaName = getZodSchemaName(name, this.options.schemaSuffix);
1757
+ const data = {
1758
+ ref: correctRef,
1759
+ name,
1760
+ zodSchemaName,
1761
+ tags: [],
1762
+ deepRefOperations: []
1763
+ };
1764
+ this.schemaData.push(data);
1765
+ this.schemaDataByRef.set(correctRef, data);
1766
+ this.schemaDataByName.set(name, data);
1767
+ this.refByZodSchemaName.set(zodSchemaName, correctRef);
1768
+ });
1769
+ });
1770
+ p.runSync("resolver.init.operationsLoop", () => {
1771
+ let currentPath = "";
1772
+ let pathParameters = {};
1773
+ for (const { path, method, operation, pathParameters: rawPathParameters } of this.indexedOperations) {
1774
+ if (path !== currentPath) {
1775
+ currentPath = path;
1776
+ pathParameters = this.getParameters(rawPathParameters ?? []);
1777
+ }
1778
+ const tag = getOperationTag(operation, this.options);
1779
+ const operationName = this.operationNameByOperation.get(operation);
1780
+ const isUniqueOperationName = this.isOperationNameUnique(operationName);
1781
+ const parameters = p.runSync("resolver.init.parameters.mergeResolve", () => Object.entries({
1782
+ ...pathParameters,
1783
+ ...this.getParameters(operation.parameters ?? [])
1784
+ }).map(([, param]) => this.resolveObject(param)));
1785
+ const responses = p.runSync("resolver.init.responses.prepare", () => Object.entries(operation.responses).map(([statusCode, response]) => {
1786
+ const responseObj = this.resolveObject(response);
1787
+ const mediaTypes = Object.keys(responseObj?.content ?? {});
1788
+ const matchingMediaType = mediaTypes.find((mediaType) => responseObj.content?.[mediaType]?.schema) ?? mediaTypes.find(isMediaTypeAllowed);
1789
+ return {
1790
+ statusCode,
1791
+ responseObj,
1792
+ matchingMediaType,
1793
+ schema: matchingMediaType ? responseObj.content?.[matchingMediaType]?.schema : void 0
1794
+ };
1795
+ }));
1796
+ const zodSchemaOperationName = snakeToCamel(getZodSchemaOperationName(operationName, isUniqueOperationName, tag));
1797
+ const schemaRefObjs = [];
1798
+ p.runSync("resolver.init.parameters.refs", () => {
1799
+ parameters.forEach((parameter) => {
1800
+ const parameterObject = this.resolveObject(parameter);
1801
+ const parameterSchema = parameterObject.schema;
1802
+ const schemaInfo = `Operation ${operation.operationId ?? path} parameter ${parameterObject.name}`;
1803
+ schemaRefObjs.push(...getSchemaRefObjs(this, parameterSchema, schemaInfo));
1804
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
1805
+ resolver: this,
1806
+ schema: parameterSchema,
1807
+ schemaInfo,
1808
+ tags: [tag],
1809
+ nameSegments: [zodSchemaOperationName, parameterObject.name],
1810
+ includeSelf: true
1811
+ });
1812
+ });
1813
+ });
1814
+ p.runSync("resolver.init.requestBody.refs", () => {
1815
+ if (operation.requestBody) {
1816
+ const requestBodyObj = this.resolveObject(operation.requestBody);
1817
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
1818
+ if (matchingMediaType) {
1819
+ const matchingMediaSchema = requestBodyObj.content?.[matchingMediaType]?.schema;
1820
+ const schemaInfo = `Operation ${operation.operationId} request body`;
1821
+ schemaRefObjs.push(...getSchemaRefObjs(this, matchingMediaSchema, schemaInfo));
1822
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
1823
+ resolver: this,
1824
+ schema: matchingMediaSchema,
1825
+ schemaInfo,
1826
+ tags: [tag],
1827
+ nameSegments: [getBodyZodSchemaName(zodSchemaOperationName)]
1828
+ });
1829
+ }
1830
+ }
1831
+ });
1832
+ p.runSync("resolver.init.responses.refs", () => {
1833
+ for (const responseData of responses) {
1834
+ if (!responseData.matchingMediaType) continue;
1835
+ const schemaInfo = `Operation ${operation.operationId} response body`;
1836
+ schemaRefObjs.push(...getSchemaRefObjs(this, responseData.schema, schemaInfo));
1837
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
1838
+ resolver: this,
1839
+ schema: responseData.schema,
1840
+ schemaInfo,
1841
+ tags: [tag],
1842
+ nameSegments: [getResponseZodSchemaName({
1843
+ statusCode: responseData.statusCode,
1844
+ operationName,
1845
+ isUniqueOperationName,
1846
+ tag
1847
+ })]
1848
+ });
1849
+ }
1850
+ });
1851
+ const deepRefs = p.runSync("resolver.init.deepRefs", () => getDeepSchemaRefObjs(this, schemaRefObjs));
1852
+ const operationContext = {
1853
+ path,
1854
+ method,
1855
+ operation,
1856
+ tag,
1857
+ operationName,
1858
+ isUniqueOperationName,
1859
+ parameters,
1860
+ deepRefs,
1861
+ responses
1862
+ };
1863
+ this.operationContexts.push(operationContext);
1864
+ deepRefs.forEach((schemaRef) => {
1865
+ const schemaData = this.getSchemaDataByRef(schemaRef);
1866
+ if (schemaData) {
1867
+ schemaData.tags.push(tag);
1868
+ schemaData.deepRefOperations.push(operation);
1869
+ }
1870
+ });
1871
+ }
1872
+ });
1873
+ if (this.options.extractEnums) p.runSync("resolver.init.enums.finalize", () => {
1874
+ this.schemaRefs.forEach((ref) => {
1875
+ const schemaRef = autocorrectRef(ref);
1876
+ updateExtractedEnumZodSchemaData({
1877
+ resolver: this,
1878
+ schema: this.getSchemaByRef(schemaRef),
1879
+ schemaRef,
1880
+ tags: this.getSchemaDataByRef(schemaRef)?.tags ?? [],
1881
+ nameSegments: [getSchemaNameByRef(schemaRef)]
1882
+ });
1883
+ });
1884
+ resolveExtractedEnumZodSchemaTags(this);
1885
+ this.handleDuplicateEnumZodSchemas();
1886
+ resolveExtractedEnumZodSchemaNames(this);
1887
+ });
1888
+ }
1889
+ handleDuplicateEnumZodSchemas() {
1890
+ const codes = new Set(this.enumZodSchemas.map(({ code }) => code));
1891
+ const duplicates = this.enumZodSchemas.filter(({ code }) => codes.has(code));
1892
+ this.schemaData.forEach((schemaData) => {
1893
+ const duplicateCode = duplicates.find(({ zodSchemaName }) => zodSchemaName === schemaData.zodSchemaName)?.code;
1894
+ if (!duplicateCode) return;
1895
+ const duplicate = this.extractedEnumZodSchemaData.find(({ code }) => code === duplicateCode);
1896
+ if (!duplicate || this.getEnumZodSchemaDataByCode(duplicate.code)?.zodSchemaName !== schemaData.zodSchemaName) return;
1897
+ schemaData.tags.push(...duplicate.meta.tags ?? []);
1898
+ duplicate.meta.schemaRefs.forEach((ref) => {
1899
+ if (!this.dependencyGraph.refsDependencyGraph[ref]) this.dependencyGraph.refsDependencyGraph[ref] = /* @__PURE__ */ new Set();
1900
+ this.dependencyGraph.refsDependencyGraph[ref].add(schemaData.ref);
1901
+ if (!this.dependencyGraph.deepDependencyGraph[ref]) this.dependencyGraph.deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
1902
+ this.dependencyGraph.deepDependencyGraph[ref].add(schemaData.ref);
1903
+ });
1904
+ });
1905
+ this.extractedEnumZodSchemaData.splice(0, this.extractedEnumZodSchemaData.length, ...this.extractedEnumZodSchemaData.filter(({ code }) => !codes.has(code)));
1906
+ }
1907
+ getParameters(parameters) {
1908
+ return Object.fromEntries((parameters ?? []).map((param) => [isReferenceObject(param) ? param.$ref : param.name, param]));
1909
+ }
1910
+ };
1911
+ //#endregion
1912
+ //#region src/generators/utils/sort.utils.ts
1913
+ /** @see https://gist.github.com/RubyTuesdayDONO/5006455 */
1914
+ function topologicalSort(graph) {
1915
+ const sorted = [];
1916
+ const sortedNames = /* @__PURE__ */ new Set();
1917
+ const visited = /* @__PURE__ */ new Set();
1918
+ function visit(name, ancestors) {
1919
+ ancestors.add(name);
1920
+ visited.add(name);
1921
+ if (graph[name]) graph[name].forEach((dep) => {
1922
+ if (ancestors.has(dep)) return;
1923
+ if (visited.has(dep)) return;
1924
+ visit(dep, ancestors);
1925
+ });
1926
+ ancestors.delete(name);
1927
+ if (!sortedNames.has(name)) {
1928
+ sortedNames.add(name);
1929
+ sorted.push(name);
1930
+ }
1931
+ }
1932
+ Object.keys(graph).forEach((name) => visit(name, /* @__PURE__ */ new Set()));
1933
+ return sorted;
1934
+ }
1935
+ /** Sort object keys using a reference order array, sort keys not in reference order in lasts positions */
1936
+ function sortObjKeysFromArray(obj, orderedKeys) {
1937
+ const entries = Object.entries(obj);
1938
+ const keyRanks = new Map(orderedKeys.map((key, index) => [key, index]));
1939
+ const orderedEntries = [];
1940
+ const remainingEntries = [];
1941
+ for (const entry of entries) (keyRanks.has(entry[0]) ? orderedEntries : remainingEntries).push(entry);
1942
+ orderedEntries.sort(([a], [b]) => keyRanks.get(a) - keyRanks.get(b));
1943
+ return Object.fromEntries(orderedEntries.concat(remainingEntries));
1944
+ }
1945
+ //#endregion
1946
+ //#region src/generators/core/zod/sortZodSchemasByTopology.ts
1947
+ function sortZodSchemasByTopology(resolver, zodSchemas) {
1948
+ return sortObjKeysFromArray(zodSchemas, topologicalSort(resolver.dependencyGraph.deepDependencyGraph).map((ref) => resolver.getZodSchemaNameByRef(ref)));
1949
+ }
1950
+ //#endregion
1951
+ //#region src/generators/core/getDataFromOpenAPIDoc.ts
1952
+ function getDataFromOpenAPIDoc(openApiDoc, options, profiler) {
1953
+ const p = profiler ?? new Profiler(false);
1954
+ const resolver = p.runSync("data.resolver.init", () => new SchemaResolver(openApiDoc, options, p));
1955
+ const endpoints = p.runSync("data.endpoints.extract", () => getEndpointsFromOpenAPIDoc(resolver, p));
1956
+ const zodSchemasFromDocSchemas = p.runSync("data.zod.extract", () => getZodSchemasFromOpenAPIDoc(resolver, p));
1957
+ resolver.enableZodSchemaTagCache();
1958
+ let zodSchemas = {
1959
+ ...zodSchemasFromDocSchemas.zodSchemas,
1960
+ ...resolver.getZodSchemas(),
1961
+ ...zodSchemasFromDocSchemas.enumZodSchemas
1962
+ };
1963
+ zodSchemas = p.runSync("data.zod.sortTopology", () => sortZodSchemasByTopology(resolver, zodSchemas));
1964
+ zodSchemas = {
1965
+ ...resolver.getExtractedEnumZodSchemas(),
1966
+ ...zodSchemas
1967
+ };
1968
+ return {
1969
+ resolver,
1970
+ data: p.runSync("data.splitByTags", () => splitDataByTags({
1971
+ resolver,
1972
+ endpoints,
1973
+ zodSchemas,
1974
+ options
1975
+ }))
1976
+ };
1977
+ }
1978
+ function splitDataByTags({ resolver, endpoints, zodSchemas, options }) {
1979
+ const data = /* @__PURE__ */ new Map();
1980
+ if (!options.splitByTags) {
1981
+ data.set(options.defaultTag, {
1982
+ endpoints,
1983
+ zodSchemas
1984
+ });
1985
+ return data;
1986
+ }
1987
+ endpoints.forEach((endpoint) => {
1988
+ getTagElement(getEndpointTag(endpoint, options), data).endpoints.push(endpoint);
1989
+ });
1990
+ Object.entries(zodSchemas).forEach(([zodSchemaName, zodSchemaCode]) => {
1991
+ if (options.modelsInModules) {
1992
+ for (const tag of resolver.getTagsByZodSchemaName(zodSchemaName)) getTagElement(tag, data).zodSchemas[zodSchemaName] = zodSchemaCode;
1993
+ return;
1994
+ }
1995
+ const tag = options.modelsInCommon ? options.defaultTag : resolver.getTagByZodSchemaName(zodSchemaName);
1996
+ if (tag) getTagElement(tag, data).zodSchemas[zodSchemaName] = zodSchemaCode;
1997
+ });
1998
+ if (options.modelsInModules) for (const tagData of data.values()) {
1999
+ const pending = Object.keys(tagData.zodSchemas);
2000
+ for (let index = 0; index < pending.length; index++) for (const dependencyName of getZodSchemaRefs(resolver, pending[index])) {
2001
+ if (tagData.zodSchemas[dependencyName] || !zodSchemas[dependencyName]) continue;
2002
+ tagData.zodSchemas[dependencyName] = zodSchemas[dependencyName];
2003
+ pending.push(dependencyName);
2004
+ }
2005
+ }
2006
+ return data;
2007
+ }
2008
+ function getTagElement(tag, data) {
2009
+ if (!data.has(tag)) data.set(tag, {
2010
+ endpoints: [],
2011
+ zodSchemas: {}
2012
+ });
2013
+ return data.get(tag);
2014
+ }
2015
+ //#endregion
2016
+ export { VALIDATION_ERROR_TYPE_TITLE as i, groupByType as n, getZodSchemaRefs as r, getDataFromOpenAPIDoc as t };