@povio/openapi-codegen-cli 2.0.8-rc.2 → 2.0.8-rc.20

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 (191) hide show
  1. package/README.md +63 -0
  2. package/dist/acl.d.mts +59 -0
  3. package/dist/acl.mjs +73 -7
  4. package/dist/auth.context-Bu5KW2sI.mjs +59 -0
  5. package/dist/config-BHkVxL6S.d.mts +6 -0
  6. package/dist/error-handling-CXeVTk1T.d.mts +38 -0
  7. package/dist/error-handling-DkPY7Asf.mjs +187 -0
  8. package/dist/generate.runner-DmZ5LVHf.mjs +130 -0
  9. package/dist/generateCodeFromOpenAPIDoc-DZ5swy4U.mjs +4465 -0
  10. package/dist/generator.d.mts +65 -0
  11. package/dist/generator.mjs +144 -0
  12. package/dist/index.d.mts +230 -0
  13. package/dist/index.mjs +251 -22
  14. package/dist/options-BNqkO_OS.d.mts +91 -0
  15. package/dist/sh.d.mts +1 -0
  16. package/dist/sh.mjs +439 -0
  17. package/dist/vite.d.mts +8 -0
  18. package/dist/vite.mjs +50 -0
  19. package/dist/zod.d.mts +20 -0
  20. package/dist/zod.mjs +33 -0
  21. package/package.json +54 -47
  22. package/dist/acl.d.ts +0 -4
  23. package/dist/commands/check.command.d.ts +0 -2
  24. package/dist/commands/check.d.ts +0 -7
  25. package/dist/commands/generate.command.d.ts +0 -2
  26. package/dist/commands/generate.d.ts +0 -8
  27. package/dist/generator.d.ts +0 -3
  28. package/dist/generator.js +0 -77
  29. package/dist/generators/checkOpenAPIDoc.d.ts +0 -3
  30. package/dist/generators/const/acl.const.d.ts +0 -13
  31. package/dist/generators/const/buildConfigs.const.d.ts +0 -1
  32. package/dist/generators/const/deps.const.d.ts +0 -38
  33. package/dist/generators/const/endpoints.const.d.ts +0 -11
  34. package/dist/generators/const/js.const.d.ts +0 -1
  35. package/dist/generators/const/openapi.const.d.ts +0 -7
  36. package/dist/generators/const/options.const.d.ts +0 -2
  37. package/dist/generators/const/package.const.d.ts +0 -2
  38. package/dist/generators/const/queries.const.d.ts +0 -8
  39. package/dist/generators/const/validation.const.d.ts +0 -53
  40. package/dist/generators/const/zod.const.d.ts +0 -19
  41. package/dist/generators/core/SchemaResolver.class.d.ts +0 -71
  42. package/dist/generators/core/endpoints/getEndpointAcl.d.ts +0 -8
  43. package/dist/generators/core/endpoints/getEndpointBody.d.ts +0 -13
  44. package/dist/generators/core/endpoints/getEndpointParameter.d.ts +0 -11
  45. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.d.ts +0 -3
  46. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.test.d.ts +0 -1
  47. package/dist/generators/core/getDataFromOpenAPIDoc.d.ts +0 -8
  48. package/dist/generators/core/getMetadataFromOpenAPIDoc.d.ts +0 -4
  49. package/dist/generators/core/getMetadataFromOpenAPIDoc.test.d.ts +0 -1
  50. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.d.ts +0 -2
  51. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.test.d.ts +0 -1
  52. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.d.ts +0 -6
  53. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.test.d.ts +0 -1
  54. package/dist/generators/core/openapi/getSchemaRefObjs.d.ts +0 -4
  55. package/dist/generators/core/openapi/iterateSchema.d.ts +0 -22
  56. package/dist/generators/core/resolveConfig.d.ts +0 -7
  57. package/dist/generators/core/zod/ZodSchema.class.d.ts +0 -26
  58. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.d.ts +0 -2
  59. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.d.ts +0 -2
  60. package/dist/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.d.ts +0 -17
  61. package/dist/generators/core/zod/getZodChain.d.ts +0 -8
  62. package/dist/generators/core/zod/getZodSchema.d.ts +0 -17
  63. package/dist/generators/core/zod/getZodSchema.test.d.ts +0 -1
  64. package/dist/generators/core/zod/getZodSchemaRefs.d.ts +0 -6
  65. package/dist/generators/core/zod/getZodSchemasFromOpenAPIDoc.d.ts +0 -6
  66. package/dist/generators/core/zod/resolveZodSchemaName.d.ts +0 -10
  67. package/dist/generators/core/zod/sortZodSchemasByTopology.d.ts +0 -4
  68. package/dist/generators/generate/generateAcl.d.ts +0 -3
  69. package/dist/generators/generate/generateAclCheck.d.ts +0 -2
  70. package/dist/generators/generate/generateAppRestClient.d.ts +0 -2
  71. package/dist/generators/generate/generateConfigs.d.ts +0 -2
  72. package/dist/generators/generate/generateEndpoints.d.ts +0 -2
  73. package/dist/generators/generate/generateModels.d.ts +0 -2
  74. package/dist/generators/generate/generateQueries.d.ts +0 -2
  75. package/dist/generators/generate/generateQueryModules.d.ts +0 -2
  76. package/dist/generators/generate/generateZodExtended.d.ts +0 -2
  77. package/dist/generators/generateCodeFromOpenAPIDoc.d.ts +0 -4
  78. package/dist/generators/types/builder-config.d.ts +0 -48
  79. package/dist/generators/types/common.d.ts +0 -27
  80. package/dist/generators/types/config.d.ts +0 -2
  81. package/dist/generators/types/endpoint.d.ts +0 -50
  82. package/dist/generators/types/generate.d.ts +0 -39
  83. package/dist/generators/types/metadata.d.ts +0 -51
  84. package/dist/generators/types/openapi.d.ts +0 -22
  85. package/dist/generators/types/options.d.ts +0 -66
  86. package/dist/generators/types/validation.d.ts +0 -5
  87. package/dist/generators/utils/array.utils.d.ts +0 -1
  88. package/dist/generators/utils/endpoint.utils.d.ts +0 -12
  89. package/dist/generators/utils/endpoint.utils.test.d.ts +0 -1
  90. package/dist/generators/utils/file.utils.d.ts +0 -8
  91. package/dist/generators/utils/generate/generate.acl.utils.d.ts +0 -23
  92. package/dist/generators/utils/generate/generate.configs.utils.d.ts +0 -15
  93. package/dist/generators/utils/generate/generate.endpoints.utils.d.ts +0 -39
  94. package/dist/generators/utils/generate/generate.imports.utils.d.ts +0 -39
  95. package/dist/generators/utils/generate/generate.imports.utils.test.d.ts +0 -1
  96. package/dist/generators/utils/generate/generate.openapi.utils.d.ts +0 -2
  97. package/dist/generators/utils/generate/generate.query.utils.d.ts +0 -6
  98. package/dist/generators/utils/generate/generate.utils.d.ts +0 -18
  99. package/dist/generators/utils/generate/generate.zod.utils.d.ts +0 -13
  100. package/dist/generators/utils/generate-files.utils.d.ts +0 -6
  101. package/dist/generators/utils/hbs/hbs-template.utils.d.ts +0 -3
  102. package/dist/generators/utils/hbs/hbs.acl.utils.d.ts +0 -2
  103. package/dist/generators/utils/hbs/hbs.common.utils.d.ts +0 -1
  104. package/dist/generators/utils/hbs/hbs.endpoints.utils.d.ts +0 -2
  105. package/dist/generators/utils/hbs/hbs.imports.utils.d.ts +0 -1
  106. package/dist/generators/utils/hbs/hbs.partials.utils.d.ts +0 -2
  107. package/dist/generators/utils/hbs/hbs.query.utils.d.ts +0 -2
  108. package/dist/generators/utils/hbs/hbs.zod.utils.d.ts +0 -2
  109. package/dist/generators/utils/js.utils.d.ts +0 -2
  110. package/dist/generators/utils/js.utils.test.d.ts +0 -1
  111. package/dist/generators/utils/math.utils.d.ts +0 -1
  112. package/dist/generators/utils/namespace.utils.d.ts +0 -7
  113. package/dist/generators/utils/object.utils.d.ts +0 -13
  114. package/dist/generators/utils/object.utils.test.d.ts +0 -1
  115. package/dist/generators/utils/openapi-schema.utils.d.ts +0 -15
  116. package/dist/generators/utils/openapi.utils.d.ts +0 -23
  117. package/dist/generators/utils/openapi.utils.test.d.ts +0 -1
  118. package/dist/generators/utils/operation.utils.d.ts +0 -22
  119. package/dist/generators/utils/operation.utils.test.d.ts +0 -1
  120. package/dist/generators/utils/query.utils.d.ts +0 -7
  121. package/dist/generators/utils/sort.utils.d.ts +0 -7
  122. package/dist/generators/utils/string.utils.d.ts +0 -14
  123. package/dist/generators/utils/string.utils.test.d.ts +0 -1
  124. package/dist/generators/utils/tag.utils.d.ts +0 -7
  125. package/dist/generators/utils/ts.utils.d.ts +0 -16
  126. package/dist/generators/utils/validation.utils.d.ts +0 -17
  127. package/dist/generators/utils/zod-schema.utils.d.ts +0 -15
  128. package/dist/helpers/cli.helper.d.ts +0 -22
  129. package/dist/helpers/config.helper.d.ts +0 -3
  130. package/dist/helpers/version.helper.d.ts +0 -4
  131. package/dist/helpers/yargs.helper.d.ts +0 -10
  132. package/dist/index.d.ts +0 -14
  133. package/dist/lib/acl/AclGuard.d.ts +0 -8
  134. package/dist/lib/acl/AclGuard.mjs +0 -14
  135. package/dist/lib/acl/Can.d.ts +0 -9
  136. package/dist/lib/acl/Can.mjs +0 -11
  137. package/dist/lib/acl/ability.context.d.ts +0 -15
  138. package/dist/lib/acl/ability.context.mjs +0 -37
  139. package/dist/lib/acl/appAbility.types.d.ts +0 -3
  140. package/dist/lib/assets/locales/en/translation.json.mjs +0 -8
  141. package/dist/lib/assets/locales/sl/translation.json.mjs +0 -8
  142. package/dist/lib/auth/AuthGuard.d.ts +0 -6
  143. package/dist/lib/auth/AuthGuard.mjs +0 -26
  144. package/dist/lib/auth/auth.context.d.ts +0 -22
  145. package/dist/lib/auth/auth.context.mjs +0 -41
  146. package/dist/lib/config/i18n.d.ts +0 -32
  147. package/dist/lib/config/i18n.mjs +0 -31
  148. package/dist/lib/config/queryConfig.context.d.ts +0 -17
  149. package/dist/lib/config/queryConfig.context.mjs +0 -26
  150. package/dist/lib/config/router.context.d.ts +0 -9
  151. package/dist/lib/config/router.context.mjs +0 -20
  152. package/dist/lib/react-query.types.d.ts +0 -10
  153. package/dist/lib/rest/error-handling.d.ts +0 -30
  154. package/dist/lib/rest/error-handling.mjs +0 -132
  155. package/dist/lib/rest/rest-client.d.ts +0 -22
  156. package/dist/lib/rest/rest-client.mjs +0 -62
  157. package/dist/lib/rest/rest-client.types.d.ts +0 -23
  158. package/dist/lib/rest/rest-interceptor.d.ts +0 -8
  159. package/dist/lib/rest/rest-interceptor.mjs +0 -21
  160. package/dist/lib/rest/rest.utils.d.ts +0 -7
  161. package/dist/lib/rest/rest.utils.mjs +0 -51
  162. package/dist/sh.d.ts +0 -2
  163. package/dist/sh.js +0 -634
  164. package/src/assets/useCrossTabQueryInvalidation.ts +0 -40
  165. package/src/assets/useMutationEffects.ts +0 -89
  166. package/src/generators/templates/acl-check.hbs +0 -29
  167. package/src/generators/templates/acl.hbs +0 -19
  168. package/src/generators/templates/app-acl.hbs +0 -17
  169. package/src/generators/templates/app-rest-client.hbs +0 -7
  170. package/src/generators/templates/configs.hbs +0 -80
  171. package/src/generators/templates/endpoints.hbs +0 -44
  172. package/src/generators/templates/models.hbs +0 -23
  173. package/src/generators/templates/partials/acl-check-call.hbs +0 -1
  174. package/src/generators/templates/partials/casl-ability-function.hbs +0 -12
  175. package/src/generators/templates/partials/casl-ability-query.hbs +0 -1
  176. package/src/generators/templates/partials/casl-ability-type.hbs +0 -1
  177. package/src/generators/templates/partials/columns-config.hbs +0 -11
  178. package/src/generators/templates/partials/endpoint-config.hbs +0 -31
  179. package/src/generators/templates/partials/endpoint-param-parse.hbs +0 -1
  180. package/src/generators/templates/partials/endpoint-params.hbs +0 -1
  181. package/src/generators/templates/partials/import.hbs +0 -1
  182. package/src/generators/templates/partials/inputs-config.hbs +0 -10
  183. package/src/generators/templates/partials/model-js-docs.hbs +0 -6
  184. package/src/generators/templates/partials/query-js-docs.hbs +0 -31
  185. package/src/generators/templates/partials/query-keys.hbs +0 -11
  186. package/src/generators/templates/partials/query-use-infinite-query.hbs +0 -21
  187. package/src/generators/templates/partials/query-use-mutation.hbs +0 -54
  188. package/src/generators/templates/partials/query-use-query.hbs +0 -16
  189. package/src/generators/templates/queries.hbs +0 -54
  190. package/src/generators/templates/query-modules.hbs +0 -9
  191. package/src/generators/templates/zod-extended.hbs +0 -49
@@ -0,0 +1,4465 @@
1
+ import fs from "fs";
2
+ import { match } from "ts-pattern";
3
+ import { OpenAPIV3 } from "openapi-types";
4
+ import path from "path";
5
+
6
+ //#region src/generators/const/validation.const.ts
7
+ const HTTP_STATUS_CODES = {
8
+ "100": "Continue",
9
+ "101": "Switching Protocols",
10
+ "102": "Processing",
11
+ "103": "Early Hints",
12
+ "200": "OK",
13
+ "201": "Created",
14
+ "202": "Accepted",
15
+ "203": "Non-Authoritative Information",
16
+ "204": "No Content",
17
+ "205": "Reset Content",
18
+ "206": "Partial Content",
19
+ "300": "Ambiguous",
20
+ "301": "Moved Permanently",
21
+ "302": "Found",
22
+ "303": "See Other",
23
+ "304": "Not Modified",
24
+ "307": "Temporary Redirect",
25
+ "308": "Permanent Redirect",
26
+ "400": "Bad Request",
27
+ "401": "Unauthorized",
28
+ "402": "Payment Required",
29
+ "403": "Forbidden",
30
+ "404": "Not Found",
31
+ "405": "Method Not Allowed",
32
+ "406": "Not Acceptable",
33
+ "407": "Proxy Authentication Required",
34
+ "408": "Request Timeout",
35
+ "409": "Conflict",
36
+ "410": "Gone",
37
+ "411": "Length Required",
38
+ "412": "Precondition Failed",
39
+ "413": "Payload Too Large",
40
+ "414": "URI Too Long",
41
+ "415": "Unsupported Media Type",
42
+ "416": "Requested Range Not Satisfiable",
43
+ "417": "Expectation Failed",
44
+ "418": "I Am a Teapot",
45
+ "421": "Misdirected Request",
46
+ "422": "Unprocessable Entity",
47
+ "424": "Failed Dependency",
48
+ "428": "Precondition Required",
49
+ "429": "Too Many Requests",
50
+ "500": "Internal Server Error",
51
+ "501": "Not Implemented",
52
+ "502": "Bad Gateway",
53
+ "503": "Service Unavailable",
54
+ "504": "Gateway Timeout",
55
+ "505": "HTTP Version Not Supported"
56
+ };
57
+ const VALIDATION_ERROR_TYPE_TITLE = {
58
+ "invalid-schema": "Invalid OpenAPI Schemas",
59
+ "invalid-operation-id": "Invalid Operation IDs",
60
+ "missing-path-parameter": "Missing Path Parameters",
61
+ "not-allowed-inline-enum": "Not Allowed Inline Enums",
62
+ "not-allowed-circular-schema": "Not Allowed Circular Schemas",
63
+ "missing-acl-condition-property": "Missing x-acl Condition Properties",
64
+ "missing-status-code": "Missing HTTP Status Codes",
65
+ "invalid-status-code": "Invalid HTTP Status Codes",
66
+ "multiple-success-status-codes": "Multiple Success HTTP Status Codes"
67
+ };
68
+
69
+ //#endregion
70
+ //#region src/helpers/profile.helper.ts
71
+ function nowMs() {
72
+ return Number(process.hrtime.bigint()) / 1e6;
73
+ }
74
+ var Profiler = class {
75
+ entries = /* @__PURE__ */ new Map();
76
+ constructor(enabled) {
77
+ this.enabled = enabled;
78
+ }
79
+ add(label, elapsedMs) {
80
+ if (!this.enabled) return;
81
+ const prev = this.entries.get(label);
82
+ if (prev) {
83
+ prev.totalMs += elapsedMs;
84
+ prev.count += 1;
85
+ return;
86
+ }
87
+ this.entries.set(label, {
88
+ totalMs: elapsedMs,
89
+ count: 1
90
+ });
91
+ }
92
+ runSync(label, fn) {
93
+ if (!this.enabled) return fn();
94
+ const startMs = nowMs();
95
+ try {
96
+ return fn();
97
+ } finally {
98
+ this.add(label, nowMs() - startMs);
99
+ }
100
+ }
101
+ async runAsync(label, fn) {
102
+ if (!this.enabled) return await fn();
103
+ const startMs = nowMs();
104
+ try {
105
+ return await fn();
106
+ } finally {
107
+ this.add(label, nowMs() - startMs);
108
+ }
109
+ }
110
+ formatLines() {
111
+ if (!this.enabled) return [];
112
+ return Array.from(this.entries.entries()).sort((a, b) => b[1].totalMs - a[1].totalMs).map(([label, entry]) => {
113
+ const avgMs = entry.totalMs / entry.count;
114
+ return `${label}: ${entry.totalMs.toFixed(1)}ms (count: ${entry.count}, avg: ${avgMs.toFixed(2)}ms)`;
115
+ });
116
+ }
117
+ };
118
+
119
+ //#endregion
120
+ //#region src/generators/utils/string.utils.ts
121
+ const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
122
+ const decapitalize = (str) => str.charAt(0).toLowerCase() + str.slice(1);
123
+ const kebabToCamel = (str) => str.replace(/(-\w)/g, (group) => group[1].toUpperCase());
124
+ const snakeToCamel = (str) => str.replace(/(_\w)/g, (group) => group[1].toUpperCase());
125
+ const nonWordCharactersToCamel = (str) => str.replace(/[\W_]+(\w)?/g, (_, char) => char?.toUpperCase() ?? "");
126
+ const suffixIfNeeded = (text, suffix = "") => text.endsWith(suffix) ? text : `${text}${suffix}`;
127
+ const removeSuffix = (text, suffix) => text.replace(new RegExp(`${suffix}$`), "");
128
+ const getLongestMostCommon = (strs) => {
129
+ const counter = strs.reduce((acc, str) => ({
130
+ ...acc,
131
+ [str]: (acc[str] ?? 0) + 1
132
+ }), {});
133
+ return Object.entries(counter).toSorted((a, b) => {
134
+ if (a[1] === b[1]) return b[0].length - a[0].length;
135
+ return b[1] - a[1];
136
+ })[0]?.[0];
137
+ };
138
+ const getMostCommonAdjacentCombinationSplit = (strs) => {
139
+ return getLongestMostCommon(strs.flatMap((str) => getAdjacentStringCombinations(splitByUppercase(capitalize(str)))));
140
+ };
141
+ const splitByUppercase = (str) => {
142
+ return str.split(/(?<![A-Z])(?=[A-Z])/).filter(Boolean);
143
+ };
144
+ const camelToSpaceSeparated = (text) => splitByUppercase(text).join(" ");
145
+ const getAdjacentStringCombinations = (strs, ignoreStrs = [
146
+ "dto",
147
+ "by",
148
+ "for",
149
+ "of",
150
+ "in",
151
+ "to",
152
+ "and",
153
+ "with"
154
+ ]) => {
155
+ const combinations = [];
156
+ for (let i = 0; i < strs.length; i++) {
157
+ if (ignoreStrs.includes(strs[i].toLowerCase())) continue;
158
+ for (let j = i + 1; j <= strs.length; j++) {
159
+ if (ignoreStrs.includes(strs[j - 1]?.toLowerCase())) continue;
160
+ combinations.push(strs.slice(i, j).join(""));
161
+ }
162
+ }
163
+ return combinations;
164
+ };
165
+ const removeWord = (source, wordToRemove) => {
166
+ const singularWordToRemove = wordToRemove.replace(/es$|s$/g, "");
167
+ const pattern = new RegExp(`(${decapitalize(singularWordToRemove)}|${capitalize(singularWordToRemove)})[a-z]*(?=$|[A-Z])`, "g");
168
+ return source.replace(pattern, "");
169
+ };
170
+
171
+ //#endregion
172
+ //#region src/generators/utils/tag.utils.ts
173
+ function formatTag(tag) {
174
+ return nonWordCharactersToCamel(tag);
175
+ }
176
+ function getOperationTag(operation, options) {
177
+ const tag = operation.tags?.[0];
178
+ return formatTag(tag ?? options.defaultTag);
179
+ }
180
+ function getEndpointTag(endpoint, options) {
181
+ return formatTag((options.splitByTags ? endpoint.tags?.[0] : options.defaultTag) ?? options.defaultTag);
182
+ }
183
+ function isTagExcluded(tag, options) {
184
+ return options.excludeTags.some((excludeTag) => excludeTag.toLowerCase() === tag.toLowerCase());
185
+ }
186
+ function shouldInlineEndpointsForTag(tag, options) {
187
+ if (!options.inlineEndpoints) return false;
188
+ return !(options.inlineEndpointsExcludeModules ?? []).some((moduleName) => formatTag(moduleName).toLowerCase() === tag.toLowerCase());
189
+ }
190
+
191
+ //#endregion
192
+ //#region src/generators/const/endpoints.const.ts
193
+ const JSON_APPLICATION_FORMAT = "application/json";
194
+ const DEFAULT_HEADERS = {
195
+ "Content-Type": JSON_APPLICATION_FORMAT,
196
+ Accept: JSON_APPLICATION_FORMAT
197
+ };
198
+ const BODY_PARAMETER_NAME = "data";
199
+ const AXIOS_DEFAULT_IMPORT_NAME = "axios";
200
+ const AXIOS_REQUEST_CONFIG_NAME = "config";
201
+ const AXIOS_REQUEST_CONFIG_TYPE = "AxiosRequestConfig";
202
+ const AXIOS_IMPORT = {
203
+ defaultImport: AXIOS_DEFAULT_IMPORT_NAME,
204
+ bindings: [AXIOS_REQUEST_CONFIG_TYPE],
205
+ from: "axios"
206
+ };
207
+
208
+ //#endregion
209
+ //#region src/generators/const/zod.const.ts
210
+ const SCHEMA_SUFFIX = "Schema";
211
+ const ENUM_SUFFIX = "Enum";
212
+ const BODY_SCHEMA_SUFFIX = "Body";
213
+ const PARAM_SCHEMA_SUFFIX = "Param";
214
+ const RESPONSE_SCHEMA_SUFFIX = "Response";
215
+ const ERROR_RESPONSE_SCHEMA_SUFFIX = "ErrorResponse";
216
+ const VOID_SCHEMA = "z.void()";
217
+ const ANY_SCHEMA = "z.any()";
218
+ const BLOB_SCHEMA = "z.instanceof(Blob)";
219
+ const ENUM_SCHEMA = "z.enum";
220
+ const INT_SCHEMA = "z.int()";
221
+ const NUMBER_SCHEMA = "z.number()";
222
+ const STRING_SCHEMA = "z.string()";
223
+ const EMAIL_SCHEMA = "z.email()";
224
+ const URL_SCHEMA = "z.url()";
225
+ const UUID_SCHEMA = "z.uuid()";
226
+ const DATETIME_SCHEMA = "z.iso.datetime({ offset: true })";
227
+ const ZOD_IMPORT = {
228
+ bindings: ["z"],
229
+ from: "zod"
230
+ };
231
+
232
+ //#endregion
233
+ //#region src/generators/utils/js.utils.ts
234
+ const isValidPropertyName = (str) => /^(?:[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+)$/.test(str);
235
+ const invalidVariableNameCharactersToCamel = (str) => str.replace(/^[^a-zA-Z_$]*/g, "").replace(/[^a-zA-Z0-9_$]+(\w)?/g, (_, char) => char?.toUpperCase() ?? "");
236
+
237
+ //#endregion
238
+ //#region src/generators/utils/openapi-schema.utils.ts
239
+ function isReferenceObject(obj) {
240
+ return obj != null && Object.prototype.hasOwnProperty.call(obj, "$ref");
241
+ }
242
+ function isSchemaObject(schema) {
243
+ return !isReferenceObject(schema);
244
+ }
245
+ function isArraySchemaObject(schema) {
246
+ return schema.type === "array";
247
+ }
248
+ function inferRequiredSchema(schema) {
249
+ if (!schema.allOf) throw new Error("Function inferRequiredSchema is specialized to handle item with required only in an allOf array.");
250
+ const [standaloneRequisites, noRequiredOnlyAllof] = schema.allOf.reduce((acc, cur) => {
251
+ if (isBrokenAllOfItem(cur)) {
252
+ const required = cur.required;
253
+ acc[0].push(...required ?? []);
254
+ } else acc[1].push(cur);
255
+ return acc;
256
+ }, [[], []]);
257
+ const composedRequiredSchema = {
258
+ properties: standaloneRequisites.reduce((acc, cur) => {
259
+ acc[cur] = {};
260
+ return acc;
261
+ }, {}),
262
+ type: "object",
263
+ required: standaloneRequisites
264
+ };
265
+ return {
266
+ noRequiredOnlyAllof,
267
+ composedRequiredSchema,
268
+ patchRequiredSchemaInLoop: (prop, getSchemaByRef) => {
269
+ if (isReferenceObject(prop)) {
270
+ const refType = getSchemaByRef(prop.$ref);
271
+ if (refType) composedRequiredSchema.required.forEach((required) => {
272
+ composedRequiredSchema.properties[required] = refType?.properties?.[required] ?? {};
273
+ });
274
+ } else {
275
+ const properties = prop["properties"] ?? {};
276
+ composedRequiredSchema.required.forEach((required) => {
277
+ if (properties[required]) composedRequiredSchema.properties[required] = properties[required] ?? {};
278
+ });
279
+ }
280
+ }
281
+ };
282
+ }
283
+ const isBrokenAllOfItem = (item) => {
284
+ return !isReferenceObject(item) && !!item.required && !item.type && !item.properties && !item?.allOf && !item?.anyOf && !item.oneOf;
285
+ };
286
+
287
+ //#endregion
288
+ //#region src/generators/const/openapi.const.ts
289
+ const COMPLEXITY_THRESHOLD = 2;
290
+ const ALLOWED_PARAM_MEDIA_TYPES = [
291
+ "application/octet-stream",
292
+ "multipart/form-data",
293
+ "application/x-www-form-urlencoded",
294
+ "*/*"
295
+ ];
296
+ const ALLOWED_PATH_IN = [
297
+ "query",
298
+ "header",
299
+ "path"
300
+ ];
301
+ const ALLOWED_METHODS = [
302
+ OpenAPIV3.HttpMethods.GET,
303
+ OpenAPIV3.HttpMethods.PUT,
304
+ OpenAPIV3.HttpMethods.POST,
305
+ OpenAPIV3.HttpMethods.DELETE,
306
+ OpenAPIV3.HttpMethods.OPTIONS,
307
+ OpenAPIV3.HttpMethods.HEAD,
308
+ OpenAPIV3.HttpMethods.PATCH,
309
+ OpenAPIV3.HttpMethods.TRACE
310
+ ];
311
+ const PRIMITIVE_TYPE_LIST = [
312
+ "string",
313
+ "number",
314
+ "integer",
315
+ "boolean"
316
+ ];
317
+ const COMPOSITE_KEYWORDS = [
318
+ "allOf",
319
+ "anyOf",
320
+ "oneOf"
321
+ ];
322
+
323
+ //#endregion
324
+ //#region src/generators/utils/openapi.utils.ts
325
+ const getSchemaRef = (schemaName) => `#/components/schemas/${schemaName}`;
326
+ const autocorrectRef = (ref) => ref[1] === "/" ? ref : "#/" + ref.slice(1);
327
+ const getSchemaNameByRef = (ref) => autocorrectRef(ref).split("/").at(-1);
328
+ function normalizeString(text) {
329
+ return snakeToCamel(prefixStringStartingWithNumberIfNeeded(text).normalize("NFKD").trim().replace(/\s+/g, "_").replace(/--+/g, "-").replace(/-+/g, "_").replace(/[^\w-]+/g, "_"));
330
+ }
331
+ function wrapWithQuotesIfNeeded(str) {
332
+ if (/^[a-zA-Z]\w*$/.test(str)) return str;
333
+ return `"${str}"`;
334
+ }
335
+ function unwrapQuotesIfNeeded(value) {
336
+ if (typeof value === "string" && value.startsWith("\"") && value.endsWith("\"")) return value.slice(1, -1);
337
+ return value;
338
+ }
339
+ function prefixStringStartingWithNumberIfNeeded(str) {
340
+ const firstAsNumber = Number(str[0]);
341
+ if (typeof firstAsNumber === "number" && !Number.isNaN(firstAsNumber)) return "_" + str;
342
+ return str;
343
+ }
344
+ function pathParamToVariableName(name) {
345
+ return snakeToCamel(name.replaceAll("_", "#").replaceAll("-", "_")).replaceAll("#", "_");
346
+ }
347
+ const isPrimitiveType = (type) => PRIMITIVE_TYPE_LIST.includes(type);
348
+ function escapeControlCharacters(str) {
349
+ return str.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/([\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF])/g, (_m, p1) => {
350
+ const dec = p1.codePointAt();
351
+ const hex = dec.toString(16);
352
+ if (dec <= 255) return `\\x${`00${hex}`.slice(-2)}`;
353
+ return `\\u${`0000${hex}`.slice(-4)}`;
354
+ }).replace(/\//g, "\\/");
355
+ }
356
+ function isParamMediaTypeAllowed(mediaType) {
357
+ return mediaType.includes("application/") && mediaType.includes("json") || ALLOWED_PARAM_MEDIA_TYPES.includes(mediaType) || mediaType.includes("text/");
358
+ }
359
+ function isMainResponseStatus(status) {
360
+ return status >= 200 && status < 300;
361
+ }
362
+ function isErrorStatus(status) {
363
+ return !(status >= 200 && status < 300);
364
+ }
365
+ function isMediaTypeAllowed(mediaType) {
366
+ return mediaType.startsWith("application/");
367
+ }
368
+ const PATH_PARAM_WITH_BRACKETS_REGEX = /({\w+})/g;
369
+ const WORD_PRECEDED_BY_NON_WORD_CHARACTER = /[^\w\-]+/g;
370
+ /** @example turns `/media-objects/{id}` into `MediaObjectsById` */
371
+ function pathToVariableName(path) {
372
+ path = capitalize(kebabToCamel(path.replaceAll("/", "-")).replaceAll("-", ""));
373
+ const pathParams = [...path.matchAll(PATH_PARAM_WITH_BRACKETS_REGEX)];
374
+ if (pathParams.length > 0) {
375
+ const lastPathParam = pathParams.toSorted((a, b) => a.index - b.index)[pathParams.length - 1][0];
376
+ path = `${path.replace(PATH_PARAM_WITH_BRACKETS_REGEX, "")}By${capitalize(lastPathParam.slice(1, -1))}`;
377
+ }
378
+ return path.replace(WORD_PRECEDED_BY_NON_WORD_CHARACTER, "_");
379
+ }
380
+ const MATCHER_REGEX = /{(\b\w+(?:-\w+)*\b)}/g;
381
+ function replaceHyphenatedPath(path) {
382
+ const matches = path.match(MATCHER_REGEX);
383
+ if (matches === null) return path.replaceAll(MATCHER_REGEX, ":$1");
384
+ matches.forEach((match) => {
385
+ const replacement = pathParamToVariableName(match.replaceAll(MATCHER_REGEX, ":$1"));
386
+ path = path.replaceAll(match, replacement);
387
+ });
388
+ return path;
389
+ }
390
+ const isSortingParameterObject = (param) => {
391
+ const enumNames = param["x-enumNames"];
392
+ const hasEnumNames = Array.isArray(enumNames) && enumNames.length > 0;
393
+ const isStringSchema = !!param.schema && isSchemaObject(param.schema) && param.schema.type === "string";
394
+ return hasEnumNames && isStringSchema;
395
+ };
396
+ const isPathExcluded = (path, options) => {
397
+ if (!options.excludePathRegex) return false;
398
+ return new RegExp(options.excludePathRegex).test(path);
399
+ };
400
+
401
+ //#endregion
402
+ //#region src/generators/utils/validation.utils.ts
403
+ function getInvalidSchemaError(message) {
404
+ return {
405
+ type: "invalid-schema",
406
+ message
407
+ };
408
+ }
409
+ function getInvalidOperationIdError(operationId) {
410
+ return {
411
+ type: "invalid-operation-id",
412
+ message: `Operation ${operationId}`
413
+ };
414
+ }
415
+ function getMissingPathParameterError(params, path) {
416
+ return {
417
+ type: "missing-path-parameter",
418
+ message: `Path ${path} is missing [${params.map(({ name }) => name).join(", ")}]`
419
+ };
420
+ }
421
+ function getNotAllowedInlineEnumError(enumProperty) {
422
+ return {
423
+ type: "not-allowed-inline-enum",
424
+ message: `${enumProperty} is missing @IsEnum() and @ApiProperty(enum:, enumName:)`
425
+ };
426
+ }
427
+ function getMissingAclConditionPropertyError(propertyName, operation, endpoint) {
428
+ return {
429
+ type: "missing-acl-condition-property",
430
+ message: `Condition property ${propertyName} is not found in parameters or body in operation ${getOperationDescriptor(operation, endpoint)}`
431
+ };
432
+ }
433
+ function getMissingStatusCodeError(statusCode, operation, endpoint) {
434
+ return {
435
+ type: "missing-status-code",
436
+ message: `Missing HTTP status code ${getStatusCodeDescription(statusCode)} in operation ${getOperationDescriptor(operation, endpoint)}`
437
+ };
438
+ }
439
+ function getInvalidStatusCodeError(statusCode, operation, endpoint) {
440
+ return {
441
+ type: "invalid-status-code",
442
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} expected HTTP status code ${getStatusCodeDescription(statusCode.expected)} but received ${getStatusCodeDescription(statusCode.received)}`
443
+ };
444
+ }
445
+ function getMultipleSuccessStatusCodesError(statusCodes, operation, endpoint) {
446
+ return {
447
+ type: "multiple-success-status-codes",
448
+ message: `Operation ${getOperationDescriptor(operation, endpoint)} has multiple success HTTP status codes: ${statusCodes.map(getStatusCodeDescription).join(", ")}`
449
+ };
450
+ }
451
+ function getOperationDescriptor(operation, endpoint) {
452
+ return operation.operationId ?? `${endpoint.method} ${endpoint.path}`;
453
+ }
454
+ function getStatusCodeDescription(statusCode) {
455
+ return `${statusCode} (${HTTP_STATUS_CODES[statusCode]})`;
456
+ }
457
+ function groupByType(validationErrors) {
458
+ return validationErrors.reduce((acc, err) => ({
459
+ ...acc,
460
+ [err.type]: [...acc[err.type] ?? [], err.message]
461
+ }), {});
462
+ }
463
+
464
+ //#endregion
465
+ //#region src/generators/const/package.const.ts
466
+ const PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli";
467
+ const ACL_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/acl";
468
+ const ZOD_PACKAGE_IMPORT_PATH = "@povio/openapi-codegen-cli/zod";
469
+
470
+ //#endregion
471
+ //#region src/generators/const/deps.const.ts
472
+ const APP_REST_CLIENT_NAME = "AppRestClient";
473
+ const APP_REST_CLIENT_FILE = {
474
+ fileName: "app-rest-client",
475
+ extension: "ts"
476
+ };
477
+ const QUERY_OPTIONS_TYPES = {
478
+ query: "AppQueryOptions",
479
+ infiniteQuery: "AppInfiniteQueryOptions",
480
+ mutation: "AppMutationOptions"
481
+ };
482
+ const TEMPLATE_DATA_FILE_PATH = "src/data";
483
+ const ERROR_HANDLERS = {
484
+ ErrorHandler: "ErrorHandler",
485
+ SharedErrorHandler: "SharedErrorHandler"
486
+ };
487
+ const ERROR_HANDLING_IMPORT = {
488
+ bindings: [ERROR_HANDLERS.ErrorHandler, ERROR_HANDLERS.SharedErrorHandler],
489
+ from: PACKAGE_IMPORT_PATH
490
+ };
491
+ const BUILDERS_UTILS = {
492
+ dynamicInputs: "dynamicInputs",
493
+ dynamicColumns: "dynamicColumns"
494
+ };
495
+ const QUERY_MODULE_ENUM = "QueryModule";
496
+ const QUERY_MODULES_FILE = {
497
+ fileName: "queryModules",
498
+ extension: "ts"
499
+ };
500
+ const MUTATION_EFFECTS = {
501
+ optionsType: "MutationEffectsOptions",
502
+ hookName: "useMutationEffects",
503
+ runFunctionName: "runMutationEffects"
504
+ };
505
+ const ZOD_EXTENDED = {
506
+ namespace: "ZodExtended",
507
+ exports: {
508
+ parse: "parse",
509
+ sortExp: "sortExp"
510
+ }
511
+ };
512
+
513
+ //#endregion
514
+ //#region src/generators/utils/zod-schema.utils.ts
515
+ const getZodSchemaName = (name, schemaSuffix) => suffixIfNeeded(capitalize(normalizeString(name)), schemaSuffix);
516
+ const getEnumZodSchemaName = (name, enumSuffix, schemaSuffix) => suffixIfNeeded(capitalize(normalizeString(name)), `${enumSuffix}${schemaSuffix}`);
517
+ const isNamedZodSchema = (schema) => ["z.", `${ZOD_EXTENDED.namespace}.`].every((searchString) => !schema.startsWith(searchString));
518
+ const isEnumZodSchema = (schema) => schema.startsWith(ENUM_SCHEMA);
519
+ const getZodSchemaOperationName = (operationName, isUniqueOperationName, tag) => isUniqueOperationName ? operationName : `${tag}_${operationName}`;
520
+ const getBodyZodSchemaName = (operationName) => snakeToCamel(`${operationName}_${BODY_SCHEMA_SUFFIX}`);
521
+ const getParamZodSchemaName = (operationName, paramName) => snakeToCamel(`${operationName}_${paramName}${PARAM_SCHEMA_SUFFIX}`);
522
+ const getMainResponseZodSchemaName = (operationName) => snakeToCamel(`${operationName}${RESPONSE_SCHEMA_SUFFIX}`);
523
+ const getErrorResponseZodSchemaName = (operationName, statusCode) => snakeToCamel(`${operationName}_${statusCode}_${ERROR_RESPONSE_SCHEMA_SUFFIX}`);
524
+ function getResponseZodSchemaName({ statusCode, operationName, isUniqueOperationName, tag }) {
525
+ const status = Number(statusCode);
526
+ const zodSchemaOperationName = getZodSchemaOperationName(operationName, isUniqueOperationName, tag);
527
+ if (!isMainResponseStatus(status) && statusCode !== "default" && isErrorStatus(status)) return getErrorResponseZodSchemaName(zodSchemaOperationName, statusCode);
528
+ return getMainResponseZodSchemaName(zodSchemaOperationName);
529
+ }
530
+
531
+ //#endregion
532
+ //#region src/generators/utils/endpoint.utils.ts
533
+ const isGetEndpoint = (endpoint) => endpoint.method === OpenAPIV3.HttpMethods.GET;
534
+ const isPaginatedGetEndpoint = (endpoint, options) => isGetEndpoint(endpoint) && Object.values(options.infiniteQueryParamNames).every((infiniteQueryParam) => endpoint.parameters.some((param) => param.name === infiniteQueryParam && param.type === "Query"));
535
+ const isReadAllEndpoint = (endpoint, options) => endpoint.method === OpenAPIV3.HttpMethods.GET && !isPathSegmentParam(endpoint.pathSegments.at(-1)) && isPaginatedGetEndpoint(endpoint, options);
536
+ const isReadEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.GET && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
537
+ const isCreateEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.POST && hasMatchingPathWithoutTrailingParam(endpoint, readAllEndpoint);
538
+ const isUpdateEndpoint = (endpoint, readAllEndpoint) => [OpenAPIV3.HttpMethods.PUT, OpenAPIV3.HttpMethods.PATCH].includes(endpoint.method) && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
539
+ const isDeleteEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.DELETE && hasMatchingPathWithTrailingParam(endpoint, readAllEndpoint);
540
+ const isBulkDeleteEndpoint = (endpoint, readAllEndpoint) => endpoint.method === OpenAPIV3.HttpMethods.DELETE && hasMatchingPathWithoutTrailingParam(endpoint, readAllEndpoint);
541
+ const getPathSegments = (path) => path.split("/").filter(Boolean);
542
+ const isPathSegmentParam = (pathSegment) => pathSegment?.startsWith(":");
543
+ const hasMatchingPath = (endpoint, readAllEndpoint) => readAllEndpoint.pathSegments.every((segment, index) => isPathSegmentParam(segment) && isPathSegmentParam(endpoint.pathSegments[index]) || segment === endpoint.pathSegments[index]);
544
+ const hasMatchingPathWithoutTrailingParam = (endpoint, readAllEndpoint) => endpoint.pathSegments.length === readAllEndpoint.pathSegments.length && hasMatchingPath(endpoint, readAllEndpoint);
545
+ const hasMatchingPathWithTrailingParam = (endpoint, readAllEndpoint) => endpoint.pathSegments.length - 1 === readAllEndpoint.pathSegments.length && isPathSegmentParam(endpoint.pathSegments.at(-1)) && hasMatchingPath(endpoint, readAllEndpoint);
546
+
547
+ //#endregion
548
+ //#region src/generators/types/generate.ts
549
+ let GenerateType = /* @__PURE__ */ function(GenerateType) {
550
+ GenerateType["Models"] = "models";
551
+ GenerateType["Endpoints"] = "endpoints";
552
+ GenerateType["Queries"] = "queries";
553
+ GenerateType["Acl"] = "acl";
554
+ GenerateType["Configs"] = "configs";
555
+ return GenerateType;
556
+ }({});
557
+
558
+ //#endregion
559
+ //#region src/generators/utils/namespace.utils.ts
560
+ const getNamespaceName = ({ type, tag, options }) => `${capitalize(tag)}${options.configs[type].namespaceSuffix}`;
561
+
562
+ //#endregion
563
+ //#region src/generators/const/acl.const.ts
564
+ const ACL_APP_ABILITY_FILE = {
565
+ fileName: "acl/app.ability",
566
+ extension: "ts"
567
+ };
568
+ const ACL_APP_ABILITIES = "AppAbilities";
569
+ const ACL_CHECK_HOOK = "useAclCheck";
570
+ const CASL_ABILITY_BINDING = {
571
+ abilityTuple: "AbilityTuple",
572
+ pureAbility: "PureAbility",
573
+ forcedSubject: "ForcedSubject",
574
+ subjectType: "Subject",
575
+ subject: "subject"
576
+ };
577
+ const CASL_ABILITY_IMPORT = {
578
+ bindings: [
579
+ CASL_ABILITY_BINDING.abilityTuple,
580
+ CASL_ABILITY_BINDING.pureAbility,
581
+ CASL_ABILITY_BINDING.forcedSubject,
582
+ CASL_ABILITY_BINDING.subjectType,
583
+ CASL_ABILITY_BINDING.subject
584
+ ],
585
+ from: "@casl/ability"
586
+ };
587
+
588
+ //#endregion
589
+ //#region src/generators/const/options.const.ts
590
+ const DEFAULT_GENERATE_OPTIONS = {
591
+ input: "http://localhost:4000/docs-json/",
592
+ output: "output",
593
+ incremental: true,
594
+ splitByTags: true,
595
+ defaultTag: "Common",
596
+ excludeTags: [],
597
+ excludePathRegex: "",
598
+ excludeRedundantZodSchemas: true,
599
+ tsNamespaces: true,
600
+ tsPath: "@/data",
601
+ importPath: "ts",
602
+ configs: {
603
+ [GenerateType.Models]: {
604
+ outputFileNameSuffix: "models",
605
+ namespaceSuffix: "Models"
606
+ },
607
+ [GenerateType.Endpoints]: {
608
+ outputFileNameSuffix: "api",
609
+ namespaceSuffix: "Api"
610
+ },
611
+ [GenerateType.Queries]: {
612
+ outputFileNameSuffix: "queries",
613
+ namespaceSuffix: "Queries"
614
+ },
615
+ [GenerateType.Acl]: {
616
+ outputFileNameSuffix: "acl",
617
+ namespaceSuffix: "Acl"
618
+ },
619
+ [GenerateType.Configs]: {
620
+ outputFileNameSuffix: "configs",
621
+ namespaceSuffix: "Configs"
622
+ }
623
+ },
624
+ baseUrl: "",
625
+ modelsOnly: false,
626
+ standalone: false,
627
+ schemaSuffix: SCHEMA_SUFFIX,
628
+ enumSuffix: ENUM_SUFFIX,
629
+ modelsInCommon: false,
630
+ withDefaultValues: true,
631
+ extractEnums: true,
632
+ replaceOptionalWithNullish: false,
633
+ restClientImportPath: "",
634
+ errorHandlingImportPath: "",
635
+ removeOperationPrefixEndingWith: "Controller_",
636
+ parseRequestParams: true,
637
+ inlineEndpoints: false,
638
+ inlineEndpointsExcludeModules: [],
639
+ queryTypesImportPath: PACKAGE_IMPORT_PATH,
640
+ axiosRequestConfig: false,
641
+ mutationEffects: true,
642
+ workspaceContext: false,
643
+ prefetchQueries: true,
644
+ infiniteQueries: false,
645
+ infiniteQueryParamNames: { page: "page" },
646
+ infiniteQueryResponseParamNames: {
647
+ page: "page",
648
+ totalItems: "totalItems",
649
+ limit: "limit"
650
+ },
651
+ acl: true,
652
+ checkAcl: true,
653
+ abilityContextGenericAppAbilities: false,
654
+ abilityContextImportPath: "",
655
+ builderConfigs: false,
656
+ filterParamName: "filter",
657
+ dataResponseParamNames: ["data", "items"],
658
+ dynamicInputsImportPath: "@povio/ui",
659
+ dynamicColumnsImportPath: "@povio/ui"
660
+ };
661
+
662
+ //#endregion
663
+ //#region src/generators/utils/array.utils.ts
664
+ const getUniqueArray = (...arrs) => [...new Set(arrs.flat())];
665
+
666
+ //#endregion
667
+ //#region src/generators/utils/generate/generate.acl.utils.ts
668
+ const getAbilityFunctionName = (endpoint) => `canUse${capitalize(snakeToCamel(endpoint.operationName))}`;
669
+ const getImportedAbilityFunctionName = (endpoint, options) => {
670
+ return `${options.tsNamespaces ? `${getNamespaceName({
671
+ type: GenerateType.Acl,
672
+ tag: getEndpointTag(endpoint, options),
673
+ options
674
+ })}.` : ""}${getAbilityFunctionName(endpoint)}`;
675
+ };
676
+ const getAbilityAction = (endpoint) => endpoint.acl?.[0].action;
677
+ const getAbilitySubject = (endpoint) => endpoint.acl?.[0].subject;
678
+ const hasAbilityConditions = (endpoint) => !!getAbilityConditionsTypes(endpoint)?.length;
679
+ const getAbilityConditionsTypes = (endpoint) => endpoint.acl?.[0].conditionsTypes?.sort((a, b) => a.name.localeCompare(b.name));
680
+ const getAbilityDescription = (endpoint) => endpoint.acl?.[0]?.description;
681
+ const getAbilitySubjectTypes = (endpoint) => {
682
+ const abilitySubject = getAbilitySubject(endpoint);
683
+ const types = [`"${abilitySubject ?? ""}"`];
684
+ if (hasAbilityConditions(endpoint)) types.push(`ForcedSubject<"${abilitySubject}"> & { ${getAbilityConditionsTypes(endpoint)?.map((conditionType) => `${conditionType.name}${conditionType.required ? "" : "?"}: ${conditionType.type ?? ""}${conditionType.zodSchemaName ?? ""},`).join(" ")} }`);
685
+ return types;
686
+ };
687
+ function getAclData({ resolver, data, tag }) {
688
+ const endpoints = data.get(tag)?.endpoints.filter(({ acl }) => acl && acl.length > 0);
689
+ if (!endpoints || endpoints.length === 0) return;
690
+ return {
691
+ endpoints,
692
+ hasAdditionalAbilityImports: endpoints.some(({ acl }) => acl?.[0].conditions && Object.keys(acl[0].conditions).length > 0),
693
+ modelsImports: getModelsImports({
694
+ resolver,
695
+ tag,
696
+ zodSchemasAsTypes: getUniqueArray(endpoints.reduce((acc, endpoint) => {
697
+ const zodSchemas = endpoint.acl?.[0].conditionsTypes?.reduce((acc, propertyType) => [...acc, ...propertyType?.zodSchemaName ? [propertyType.zodSchemaName] : []], []);
698
+ return [...acc, ...zodSchemas ?? []];
699
+ }, []))
700
+ })
701
+ };
702
+ }
703
+ const getAppAbilitiesType = ({ resolver, data }) => {
704
+ const appAbilitiesTypeMap = /* @__PURE__ */ new Map();
705
+ const modelsImportsArr = [];
706
+ let hasAdditionalAbilityImports = false;
707
+ data.forEach((_, tag) => {
708
+ const aclData = getAclData({
709
+ resolver,
710
+ data,
711
+ tag
712
+ });
713
+ if (!aclData) return;
714
+ const { modelsImports: tagModelsImports, hasAdditionalAbilityImports: tagHasAdditionalAbilityImports, endpoints } = aclData;
715
+ modelsImportsArr.push(tagModelsImports);
716
+ hasAdditionalAbilityImports = hasAdditionalAbilityImports || tagHasAdditionalAbilityImports;
717
+ endpoints.forEach((endpoint) => {
718
+ const abilityAction = getAbilityAction(endpoint);
719
+ if (abilityAction) appAbilitiesTypeMap.set(abilityAction, new Set([...appAbilitiesTypeMap.get(abilityAction) ?? [], ...getAbilitySubjectTypes(endpoint)]));
720
+ });
721
+ });
722
+ const modelsImports = mergeImports(resolver.options, ...modelsImportsArr);
723
+ return {
724
+ appAbilitiesType: appAbilitiesTypeMap.size > 0 ? Object.fromEntries(Array.from(appAbilitiesTypeMap.entries()).map(([key, valueSet]) => [key, Array.from(valueSet)])) : void 0,
725
+ modelsImports,
726
+ hasAdditionalAbilityImports
727
+ };
728
+ };
729
+
730
+ //#endregion
731
+ //#region src/generators/utils/generate/generate.query.utils.ts
732
+ const getQueryName = (endpoint, mutation) => {
733
+ const addMutationSuffix = isQuery(endpoint) && isMutation(endpoint) && mutation;
734
+ return `use${capitalize(snakeToCamel(endpoint.operationName))}${addMutationSuffix ? "Mutation" : ""}`;
735
+ };
736
+ const getInfiniteQueryName = (endpoint) => `use${capitalize(snakeToCamel(endpoint.operationName))}Infinite`;
737
+ const getQueryOptionsName = (endpoint) => `${snakeToCamel(endpoint.operationName)}QueryOptions`;
738
+ const getInfiniteQueryOptionsName = (endpoint) => `${snakeToCamel(endpoint.operationName)}InfiniteQueryOptions`;
739
+ const getPrefetchQueryName = (endpoint) => `prefetch${capitalize(snakeToCamel(endpoint.operationName))}`;
740
+ const getPrefetchInfiniteQueryName = (endpoint) => `prefetch${capitalize(snakeToCamel(endpoint.operationName))}Infinite`;
741
+ const getImportedQueryName = (endpoint, options) => {
742
+ return `${options.tsNamespaces ? `${getNamespaceName({
743
+ type: GenerateType.Queries,
744
+ tag: getEndpointTag(endpoint, options),
745
+ options
746
+ })}.` : ""}${getQueryName(endpoint)}`;
747
+ };
748
+ const getImportedInfiniteQueryName = (endpoint, options) => {
749
+ return `${options.tsNamespaces ? `${getNamespaceName({
750
+ type: GenerateType.Queries,
751
+ tag: getEndpointTag(endpoint, options),
752
+ options
753
+ })}.` : ""}${getInfiniteQueryName(endpoint)}`;
754
+ };
755
+
756
+ //#endregion
757
+ //#region src/generators/core/openapi/iterateSchema.ts
758
+ function iterateSchema(schema, options) {
759
+ if (!schema) return;
760
+ const { data, onSchema } = options;
761
+ if (isReferenceObject(schema) && onSchema({
762
+ type: "reference",
763
+ schema,
764
+ data
765
+ }) === true) return;
766
+ const schemaObj = schema;
767
+ if (COMPOSITE_KEYWORDS.some((prop) => prop in schemaObj && schemaObj[prop])) {
768
+ const schemaObjs = schemaObj.allOf ?? schemaObj.anyOf ?? schemaObj.oneOf ?? [];
769
+ for (const compositeObj of schemaObjs) {
770
+ if (onSchema?.({
771
+ type: "composite",
772
+ parentSchema: schema,
773
+ schema: compositeObj,
774
+ data
775
+ }) === true) continue;
776
+ iterateSchema(compositeObj, {
777
+ data,
778
+ onSchema
779
+ });
780
+ }
781
+ }
782
+ if (schemaObj.properties) for (const [propertyName, propertyObj] of Object.entries(schemaObj.properties)) {
783
+ if (onSchema({
784
+ type: "property",
785
+ parentSchema: schema,
786
+ schema: propertyObj,
787
+ data,
788
+ propertyName
789
+ }) === true) continue;
790
+ iterateSchema(propertyObj, options);
791
+ }
792
+ if (schemaObj.additionalProperties && typeof schemaObj.additionalProperties === "object") {
793
+ if (onSchema({
794
+ type: "additionalProperties",
795
+ parentSchema: schema,
796
+ schema: schemaObj.additionalProperties,
797
+ data
798
+ }) === true) return;
799
+ iterateSchema(schemaObj.additionalProperties, options);
800
+ }
801
+ if (schemaObj.type === "array") {
802
+ const arrayObj = schema.items;
803
+ if (onSchema({
804
+ type: "array",
805
+ parentSchema: schema,
806
+ schema: arrayObj,
807
+ data
808
+ }) === true) return;
809
+ iterateSchema(arrayObj, options);
810
+ }
811
+ }
812
+
813
+ //#endregion
814
+ //#region src/generators/utils/generate/generate.openapi.utils.ts
815
+ const schemaDescriptionsCache = /* @__PURE__ */ new WeakMap();
816
+ function getSchemaDescriptions(schemaObj) {
817
+ const cachedSchemaDescriptions = schemaDescriptionsCache.get(schemaObj);
818
+ if (cachedSchemaDescriptions) return cachedSchemaDescriptions;
819
+ const schemaDescriptions = [
820
+ "minimum",
821
+ "exclusiveMinimum",
822
+ "maximum",
823
+ "exclusiveMaximum",
824
+ "minItems",
825
+ "minLength",
826
+ "minProperties",
827
+ "maxItems",
828
+ "maxLength",
829
+ "maxProperties",
830
+ "default",
831
+ "example"
832
+ ].filter((key) => schemaObj[key] !== void 0).reduce((acc, key) => [...acc, `${capitalize(camelToSpaceSeparated(key))}: \`${schemaObj[key]}\``], []);
833
+ schemaDescriptionsCache.set(schemaObj, schemaDescriptions);
834
+ return schemaDescriptions;
835
+ }
836
+
837
+ //#endregion
838
+ //#region src/generators/utils/generate/generate.zod.utils.ts
839
+ const getZodSchemaInferedTypeName = (zodSchemaName, options) => removeSuffix(zodSchemaName, options.schemaSuffix);
840
+ const getImportedZodSchemaName = (resolver, zodSchemaName, namespaceTag) => {
841
+ if (!isNamedZodSchema(zodSchemaName)) return zodSchemaName;
842
+ const tag = namespaceTag ?? resolver.getTagByZodSchemaName(zodSchemaName);
843
+ return `${resolver.options.tsNamespaces ? `${getNamespaceName({
844
+ type: GenerateType.Models,
845
+ tag,
846
+ options: resolver.options
847
+ })}.` : ""}${zodSchemaName}`;
848
+ };
849
+ const getImportedZodSchemaInferedTypeName = (resolver, zodSchemaName, currentTag, namespaceTag) => {
850
+ if (!isNamedZodSchema(zodSchemaName)) return zodSchemaName === VOID_SCHEMA ? "void" : zodSchemaName;
851
+ const tag = namespaceTag ?? resolver.getTagByZodSchemaName(zodSchemaName);
852
+ return `${resolver.options.tsNamespaces && (Boolean(namespaceTag) || tag !== currentTag) ? `${getNamespaceName({
853
+ type: GenerateType.Models,
854
+ tag,
855
+ options: resolver.options
856
+ })}.` : ""}${getZodSchemaInferedTypeName(zodSchemaName, resolver.options)}`;
857
+ };
858
+ function getZodSchemaType(data) {
859
+ return data.isEnum ? "enum" : data.schemaObj?.type ?? "object";
860
+ }
861
+ function getZodSchemaDescription(data) {
862
+ if (!data.schemaObj) return;
863
+ return [data.schemaObj.description, ...getSchemaDescriptions(data.schemaObj)].filter(Boolean).join(". ");
864
+ }
865
+ function getType(resolver, schemaObj, tag) {
866
+ if (isReferenceObject(schemaObj)) {
867
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schemaObj.$ref);
868
+ return zodSchemaName ? getImportedZodSchemaInferedTypeName(resolver, zodSchemaName, tag) : void 0;
869
+ }
870
+ if (isArraySchemaObject(schemaObj)) {
871
+ if (!isReferenceObject(schemaObj.items)) return `${schemaObj.items?.type ?? "unknown"}[]`;
872
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schemaObj.items.$ref);
873
+ return zodSchemaName ? `${getImportedZodSchemaInferedTypeName(resolver, zodSchemaName, tag)}[]` : void 0;
874
+ }
875
+ if (COMPOSITE_KEYWORDS.some((prop) => prop in schemaObj && schemaObj[prop])) {
876
+ const schemaObjs = schemaObj.allOf ?? schemaObj.anyOf ?? schemaObj.oneOf ?? [];
877
+ if (schemaObjs.length > 0) return getType(resolver, schemaObjs[0], tag);
878
+ }
879
+ return schemaObj.type;
880
+ }
881
+ function getZodSchemaPropertyDescriptions(resolver, data, tag) {
882
+ if (!data.schemaObj) return [];
883
+ const ARRAY_INDEX = "[0]";
884
+ const ADDITIONAL_PROPERTIES_KEY = "[key]";
885
+ const properties = {};
886
+ const onSchema = (schemaData) => {
887
+ if (schemaData.type === "reference") return true;
888
+ if (schemaData.type === "composite") return;
889
+ const segments = [...schemaData.data?.pathSegments ?? []];
890
+ if (schemaData.type === "array") segments.push(ARRAY_INDEX);
891
+ else if (schemaData.type === "property") segments.push(schemaData.propertyName);
892
+ else if (schemaData.type === "additionalProperties") segments.push(ADDITIONAL_PROPERTIES_KEY);
893
+ if (schemaData.schema && segments[segments.length - 1] !== ARRAY_INDEX) {
894
+ const resolvedSchema = resolver.resolveObject(schemaData.schema);
895
+ const schemaDescriptions = [resolvedSchema?.description, ...getSchemaDescriptions(resolvedSchema)].filter(Boolean);
896
+ const propertyKey = segments.join(".");
897
+ if (!(properties[propertyKey] && "type" in schemaData.schema && schemaData.schema.type === "object")) {
898
+ delete properties[propertyKey];
899
+ properties[propertyKey] = {
900
+ type: getType(resolver, schemaData.schema, tag) ?? "unknown",
901
+ description: schemaDescriptions.join(". ")
902
+ };
903
+ }
904
+ }
905
+ iterateSchema(schemaData.schema, {
906
+ data: { pathSegments: [...segments] },
907
+ onSchema
908
+ });
909
+ return true;
910
+ };
911
+ if ("allOf" in data.schemaObj && data.schemaObj.allOf) data.schemaObj.allOf.forEach((schemaObj) => {
912
+ if (isReferenceObject(schemaObj)) iterateSchema(resolver.resolveObject(schemaObj), {
913
+ data: { pathSegments: [] },
914
+ onSchema
915
+ });
916
+ });
917
+ iterateSchema(data.schemaObj, {
918
+ data: { pathSegments: [] },
919
+ onSchema
920
+ });
921
+ return properties;
922
+ }
923
+
924
+ //#endregion
925
+ //#region src/generators/utils/generate/generate.imports.utils.ts
926
+ function getModelsImports({ resolver, tag, zodSchemas = [], zodSchemasAsTypes = [] }) {
927
+ const type = GenerateType.Models;
928
+ const getTag = (zodSchemaName) => resolver.getTagByZodSchemaName(zodSchemaName);
929
+ const zodSchemaImports = getImports({
930
+ type,
931
+ tag,
932
+ entities: zodSchemas,
933
+ getTag,
934
+ getEntityName: (zodSchema) => zodSchema,
935
+ options: resolver.options
936
+ });
937
+ const zodSchemaTypeImports = getImports({
938
+ type,
939
+ tag,
940
+ entities: zodSchemasAsTypes,
941
+ getTag,
942
+ getEntityName: (zodSchema) => getZodSchemaInferedTypeName(zodSchema, resolver.options),
943
+ options: resolver.options
944
+ });
945
+ return mergeImports(resolver.options, zodSchemaImports, zodSchemaTypeImports);
946
+ }
947
+ function getEndpointsImports({ tag, endpoints, options }) {
948
+ return getImports({
949
+ type: GenerateType.Endpoints,
950
+ tag,
951
+ entities: endpoints,
952
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
953
+ getEntityName: getEndpointName,
954
+ options
955
+ });
956
+ }
957
+ function getQueriesImports({ tag, endpoints, options }) {
958
+ return getImports({
959
+ type: GenerateType.Queries,
960
+ tag,
961
+ entities: endpoints,
962
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
963
+ getEntityName: getQueryName,
964
+ options
965
+ });
966
+ }
967
+ function getInfiniteQueriesImports({ tag, endpoints, options }) {
968
+ return getImports({
969
+ type: GenerateType.Queries,
970
+ tag,
971
+ entities: endpoints,
972
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
973
+ getEntityName: getInfiniteQueryName,
974
+ options
975
+ });
976
+ }
977
+ function getAclImports({ tag, endpoints, options }) {
978
+ return getImports({
979
+ type: GenerateType.Acl,
980
+ tag,
981
+ entities: endpoints,
982
+ getTag: (endpoint) => getEndpointTag(endpoint, options),
983
+ getEntityName: getAbilityFunctionName,
984
+ options
985
+ });
986
+ }
987
+ function getImportPath(options, fromRoot = false) {
988
+ let importPath = options.tsPath;
989
+ if (options.importPath === "relative") importPath = fromRoot ? "./" : "../";
990
+ else if (options.importPath === "absolute") importPath = options.output;
991
+ else if (new RegExp(`${TEMPLATE_DATA_FILE_PATH}`, "g").test(options.output)) importPath = options.output.replace(new RegExp(`.*${TEMPLATE_DATA_FILE_PATH}`, "g"), options.tsPath);
992
+ return `${importPath}/`.replace(/\/\//g, "/");
993
+ }
994
+ function getImports({ type = GenerateType.Models, tag: currentTag, entities, getTag, getEntityName, options }) {
995
+ const imports = /* @__PURE__ */ new Map();
996
+ entities.forEach((entity) => {
997
+ const tag = type === GenerateType.Models && options.modelsInCommon && options.splitByTags ? currentTag : getTag(entity);
998
+ if (!imports.has(tag)) {
999
+ const sameTagDir = currentTag === tag;
1000
+ imports.set(tag, {
1001
+ bindings: [options.tsNamespaces ? getNamespaceName({
1002
+ type,
1003
+ tag,
1004
+ options
1005
+ }) : getEntityName(entity)],
1006
+ from: `${sameTagDir ? "./" : getImportPath(options)}${getTagImportPath({
1007
+ type,
1008
+ tag,
1009
+ includeTagDir: !sameTagDir,
1010
+ options
1011
+ })}`
1012
+ });
1013
+ } else if (!options.tsNamespaces) imports.get(tag).bindings.push(getEntityName(entity));
1014
+ });
1015
+ return Array.from(imports.values());
1016
+ }
1017
+ function mergeImports(options, ...importArrs) {
1018
+ const merged = /* @__PURE__ */ new Map();
1019
+ importArrs.forEach((imports) => {
1020
+ imports.forEach((importItem) => {
1021
+ if (!merged.has(importItem.from)) merged.set(importItem.from, importItem);
1022
+ else if (!options.tsNamespaces) merged.get(importItem.from).bindings.push(...importItem.bindings);
1023
+ });
1024
+ });
1025
+ return Array.from(merged.values()).map((importItem) => ({
1026
+ ...importItem,
1027
+ bindings: getUniqueArray(importItem.bindings)
1028
+ }));
1029
+ }
1030
+
1031
+ //#endregion
1032
+ //#region src/generators/utils/generate/generate.utils.ts
1033
+ function getFileNameWithExtension({ fileName, extension }) {
1034
+ return `${fileName}.${extension}`;
1035
+ }
1036
+ function getTagFileNameWithoutExtension({ type, tag, options, includeTagDir = true }) {
1037
+ const outputFileNameSuffix = options.configs[type].outputFileNameSuffix;
1038
+ if (!tag) return outputFileNameSuffix;
1039
+ return `${includeTagDir ? `${decapitalize(tag)}/` : ""}${decapitalize(tag)}.${outputFileNameSuffix}`;
1040
+ }
1041
+ function getTagImportPath(...args) {
1042
+ return getTagFileNameWithoutExtension(...args);
1043
+ }
1044
+ function getTagFileName(...args) {
1045
+ return `${getTagFileNameWithoutExtension(...args)}.ts`;
1046
+ }
1047
+ function getAppRestClientImportPath(options) {
1048
+ if (options.restClientImportPath === DEFAULT_GENERATE_OPTIONS.restClientImportPath) return `${getImportPath(options)}${APP_REST_CLIENT_FILE.fileName}`;
1049
+ return options.restClientImportPath;
1050
+ }
1051
+ function getQueryModulesImportPath(options) {
1052
+ return `${getImportPath(options)}${QUERY_MODULES_FILE.fileName}`;
1053
+ }
1054
+ function getQueryTypesImportPath(options) {
1055
+ return options.queryTypesImportPath;
1056
+ }
1057
+
1058
+ //#endregion
1059
+ //#region src/generators/utils/ts.utils.ts
1060
+ function primitiveTypeToTsType(type) {
1061
+ return match(type).with("string", () => "string").with("number", () => "number").with("integer", () => "number").with("boolean", () => "boolean").exhaustive();
1062
+ }
1063
+ function getTsTypeBase({ zodSchemaName, schema, resolver }) {
1064
+ let type = "void";
1065
+ let tag;
1066
+ if (zodSchemaName && isNamedZodSchema(zodSchemaName)) {
1067
+ type = getImportedZodSchemaInferedTypeName(resolver, zodSchemaName);
1068
+ tag = resolver.getTagByZodSchemaName(zodSchemaName);
1069
+ } else if (schema?.type && isPrimitiveType(schema?.type)) type = primitiveTypeToTsType(schema?.type);
1070
+ const splitType = type.split(".");
1071
+ return {
1072
+ type: splitType[splitType.length - 1],
1073
+ ...splitType.length > 1 ? { namespace: splitType[0] } : {},
1074
+ ...tag ? { importPath: getTagImportPath({
1075
+ type: GenerateType.Models,
1076
+ tag,
1077
+ includeTagDir: true,
1078
+ options: resolver.options
1079
+ }) } : {}
1080
+ };
1081
+ }
1082
+ function getSchemaTsMetaType({ schema, isCircular, parentTypes, resolver }) {
1083
+ if (!schema) return { metaType: "primitive" };
1084
+ for (const compositeKeyword of COMPOSITE_KEYWORDS) {
1085
+ const compositeObjs = schema[compositeKeyword];
1086
+ if (!compositeObjs) continue;
1087
+ if (compositeObjs.length > 1) {
1088
+ const metaTypes = compositeObjs.map((compositeObj) => {
1089
+ return getSchemaTsMetaType({
1090
+ schema: resolver.resolveObject(compositeObj),
1091
+ parentTypes,
1092
+ resolver
1093
+ });
1094
+ });
1095
+ if (metaTypes.every(({ metaType }) => metaType === "object")) return {
1096
+ metaType: "object",
1097
+ objectProperties: metaTypes.reduce((acc, { objectProperties }) => {
1098
+ const objectPropertyNames = new Set(objectProperties.map(({ name }) => name));
1099
+ return [...acc.filter(({ name }) => !objectPropertyNames.has(name)), ...objectProperties];
1100
+ }, [])
1101
+ };
1102
+ else return {
1103
+ metaType: "composite",
1104
+ [compositeKeyword]: metaTypes
1105
+ };
1106
+ } else schema = resolver.resolveObject(compositeObjs[0]);
1107
+ }
1108
+ if (schema.type === "array") return {
1109
+ metaType: "array",
1110
+ arrayType: getArraySchemaTsType({
1111
+ arraySchema: schema,
1112
+ resolver,
1113
+ parentTypes
1114
+ })
1115
+ };
1116
+ else if ((schema.type === "object" || schema.properties) && isCircular) return {
1117
+ metaType: "object",
1118
+ objectProperties: [],
1119
+ isCircular: true
1120
+ };
1121
+ else if (schema.type === "object" || schema.properties) return {
1122
+ metaType: "object",
1123
+ objectProperties: getSchemaTsProperties({
1124
+ schema,
1125
+ parentTypes,
1126
+ resolver
1127
+ })
1128
+ };
1129
+ return { metaType: "primitive" };
1130
+ }
1131
+ function getArraySchemaTsType({ arraySchema, parentTypes, resolver }) {
1132
+ let zodSchemaName;
1133
+ let schema;
1134
+ if (isReferenceObject(arraySchema.items)) {
1135
+ const ref = arraySchema.items.$ref;
1136
+ zodSchemaName = resolver.getZodSchemaNameByRef(ref);
1137
+ schema = resolver.getSchemaByRef(ref);
1138
+ } else schema = arraySchema.items;
1139
+ const tsType = getTsTypeBase({
1140
+ zodSchemaName,
1141
+ schema,
1142
+ resolver
1143
+ });
1144
+ const isCircular = getIsCircular(tsType, parentTypes);
1145
+ const tsMetaType = getSchemaTsMetaType({
1146
+ schema,
1147
+ isCircular,
1148
+ parentTypes: [...parentTypes, tsType],
1149
+ resolver
1150
+ });
1151
+ return {
1152
+ ...tsType,
1153
+ ...tsMetaType
1154
+ };
1155
+ }
1156
+ function getSchemaTsProperties({ schema, parentTypes, resolver }) {
1157
+ return Object.entries(schema?.properties ?? {}).map(([name, property]) => {
1158
+ const isRequired = schema?.required?.includes(name) ?? false;
1159
+ if (isReferenceObject(property)) {
1160
+ const zodSchemaName = resolver.getZodSchemaNameByRef(property.$ref);
1161
+ const schema = resolver.getSchemaByRef(property.$ref);
1162
+ const tsType = getTsTypeBase({
1163
+ zodSchemaName,
1164
+ schema,
1165
+ resolver
1166
+ });
1167
+ const tsMetaType = getSchemaTsMetaType({
1168
+ schema,
1169
+ isCircular: getIsCircular(tsType, parentTypes),
1170
+ parentTypes: [...parentTypes, tsType],
1171
+ resolver
1172
+ });
1173
+ return {
1174
+ name,
1175
+ isRequired,
1176
+ ...tsType,
1177
+ ...tsMetaType
1178
+ };
1179
+ } else if (property.type === "array") return {
1180
+ name,
1181
+ isRequired,
1182
+ type: "array",
1183
+ metaType: "array",
1184
+ arrayType: getArraySchemaTsType({
1185
+ arraySchema: property,
1186
+ parentTypes,
1187
+ resolver
1188
+ })
1189
+ };
1190
+ else if (isPrimitiveType(property.type)) return {
1191
+ name,
1192
+ isRequired,
1193
+ type: primitiveTypeToTsType(property.type),
1194
+ metaType: "primitive"
1195
+ };
1196
+ return {
1197
+ name,
1198
+ isRequired,
1199
+ type: "void",
1200
+ metaType: "primitive"
1201
+ };
1202
+ });
1203
+ }
1204
+ function getIsCircular(tsType, parentTypes) {
1205
+ return parentTypes.findIndex(({ type, namespace }) => type === tsType.type && namespace === tsType.namespace) > -1;
1206
+ }
1207
+
1208
+ //#endregion
1209
+ //#region src/generators/utils/generate/generate.endpoints.utils.ts
1210
+ const getEndpointName = (endpoint) => decapitalize(snakeToCamel(endpoint.operationName));
1211
+ function getImportedEndpointName(endpoint, options) {
1212
+ return `${options.tsNamespaces ? `${getNamespaceName({
1213
+ type: GenerateType.Endpoints,
1214
+ tag: getEndpointTag(endpoint, options),
1215
+ options
1216
+ })}.` : ""}${getEndpointName(endpoint)}`;
1217
+ }
1218
+ const requiresBody = (endpoint) => endpoint.method !== OpenAPIV3.HttpMethods.GET;
1219
+ const getEndpointBody$1 = (endpoint) => endpoint.parameters.find((param) => param.type === "Body");
1220
+ const hasEndpointConfig = (endpoint, resolver) => {
1221
+ const endpointConfig = getEndpointConfig(endpoint);
1222
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1223
+ return Object.keys(endpointConfig).length > 0 || hasAxiosRequestConfig;
1224
+ };
1225
+ const getEndpointPath = (endpoint) => endpoint.path.replace(/:([a-zA-Z0-9_]+)/g, "${$1}");
1226
+ function mapEndpointParamsToFunctionParams(resolver, endpoint, options) {
1227
+ const params = endpoint.parameters.map((param) => {
1228
+ let type = "string";
1229
+ if (isNamedZodSchema(param.zodSchema)) type = getImportedZodSchemaInferedTypeName(resolver, param.zodSchema, void 0, options?.modelNamespaceTag);
1230
+ else if (param.parameterObject?.schema && isSchemaObject(param.parameterObject.schema)) {
1231
+ const openApiSchemaType = (param.parameterObject?.schema)?.type;
1232
+ if (openApiSchemaType && isPrimitiveType(openApiSchemaType)) type = primitiveTypeToTsType(openApiSchemaType);
1233
+ }
1234
+ return {
1235
+ name: invalidVariableNameCharactersToCamel(param.name),
1236
+ type,
1237
+ paramType: param.type,
1238
+ required: param.parameterObject?.required ?? true,
1239
+ parameterObject: param.parameterObject,
1240
+ bodyObject: param.bodyObject
1241
+ };
1242
+ });
1243
+ if (options?.includeFileParam && endpoint.mediaUpload) params.push({
1244
+ name: "file",
1245
+ type: "File",
1246
+ paramType: "Body",
1247
+ required: false,
1248
+ parameterObject: void 0,
1249
+ bodyObject: void 0
1250
+ });
1251
+ return params.toSorted((a, b) => {
1252
+ if (a.required === b.required) {
1253
+ const sortedParamTypes = [
1254
+ "Path",
1255
+ "Body",
1256
+ "Query",
1257
+ "Header"
1258
+ ];
1259
+ return sortedParamTypes.indexOf(a.paramType) - sortedParamTypes.indexOf(b.paramType);
1260
+ }
1261
+ return a.required ? -1 : 1;
1262
+ }).filter((param) => (!options?.excludeBodyParam || param.name !== BODY_PARAMETER_NAME) && (!options?.excludePageParam || param.name !== resolver.options.infiniteQueryParamNames.page) && (!options?.includeOnlyRequiredParams || param.required)).map((param) => ({
1263
+ ...param,
1264
+ name: options?.replacePageParam && param.name === resolver.options.infiniteQueryParamNames.page ? "pageParam" : param.name,
1265
+ required: options?.optionalPathParams && param.paramType === "Path" ? false : param.required && (param.paramType === "Path" || !options?.pathParamsRequiredOnly)
1266
+ }));
1267
+ }
1268
+ function getEndpointConfig(endpoint) {
1269
+ const params = endpoint.parameters.filter((param) => param.type === "Query").map((param) => {
1270
+ const paramPropertyName = isValidPropertyName(param.name) ? param.name : `"${param.name}"`;
1271
+ const paramVariableName = invalidVariableNameCharactersToCamel(param.name);
1272
+ return {
1273
+ ...param,
1274
+ name: paramPropertyName,
1275
+ value: paramVariableName
1276
+ };
1277
+ });
1278
+ const headers = {};
1279
+ if (endpoint.requestFormat !== DEFAULT_HEADERS["Content-Type"]) headers["Content-Type"] = `'${endpoint.requestFormat}'`;
1280
+ if (endpoint.responseFormat && endpoint.responseFormat !== DEFAULT_HEADERS.Accept) headers.Accept = `'${endpoint.responseFormat}'`;
1281
+ endpoint.parameters.filter((param) => param.type === "Header").forEach((param) => {
1282
+ headers[param.name] = invalidVariableNameCharactersToCamel(param.name);
1283
+ });
1284
+ return {
1285
+ ...params.length > 0 ? { params } : {},
1286
+ ...Object.keys(headers).length ? { headers } : {}
1287
+ };
1288
+ }
1289
+
1290
+ //#endregion
1291
+ //#region src/generators/utils/query.utils.ts
1292
+ const isQuery = (endpoint) => isGetEndpoint(endpoint);
1293
+ const isMutation = (endpoint) => !isGetEndpoint(endpoint) || !!endpoint.mediaDownload;
1294
+ const isInfiniteQuery = (endpoint, options) => isPaginatedGetEndpoint(endpoint, options);
1295
+ const getDestructuredVariables = (resolver, endpoint, updateQueryEndpoints) => {
1296
+ const requiredUpdateQueryParams = updateQueryEndpoints.reduce((acc, updateEndpoint) => [...acc, ...mapEndpointParamsToFunctionParams(resolver, updateEndpoint, { includeOnlyRequiredParams: true }).map((param) => param.name)], []);
1297
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, {
1298
+ includeOnlyRequiredParams: true,
1299
+ excludeBodyParam: true
1300
+ }).filter((param) => requiredUpdateQueryParams.includes(param.name)).map((param) => param.name);
1301
+ };
1302
+
1303
+ //#endregion
1304
+ //#region src/generators/core/endpoints/getEndpointAcl.ts
1305
+ function getEndpointAcl({ resolver, endpoint, operation }) {
1306
+ const acl = operation["x-acl"];
1307
+ return acl?.map((item) => {
1308
+ const conditionsTypes = Object.keys(item.conditions ?? {}).reduce((acc, name) => {
1309
+ const propertyType = getEndpointAclConditionPropertyType({
1310
+ resolver,
1311
+ endpoint,
1312
+ acl,
1313
+ name
1314
+ });
1315
+ if (!propertyType) {
1316
+ resolver.validationErrors.push(getMissingAclConditionPropertyError(name, operation, endpoint));
1317
+ return acc;
1318
+ }
1319
+ return [...acc, propertyType];
1320
+ }, []);
1321
+ return {
1322
+ ...item,
1323
+ conditionsTypes
1324
+ };
1325
+ });
1326
+ }
1327
+ function getEndpointAclConditionPropertyType({ resolver, endpoint, acl, name }) {
1328
+ const conditionPropertyPath = acl[0]?.conditions?.[name];
1329
+ if (!conditionPropertyPath) return;
1330
+ const pathSplits = conditionPropertyPath.replace(/^\$[^.]*\./, "").split(".");
1331
+ let schema = void 0;
1332
+ let required = void 0;
1333
+ let info = void 0;
1334
+ let index = 0;
1335
+ const parameter = endpoint.parameters.find(({ name }) => name === pathSplits[index]);
1336
+ if (parameter) {
1337
+ required = parameter.parameterObject?.required;
1338
+ schema = parameter.parameterObject?.schema;
1339
+ info = `${parameter.name} ${decapitalize(parameter.type)} parameter`;
1340
+ index++;
1341
+ } else {
1342
+ const bodyParameter = endpoint.parameters.find(({ bodyObject }) => !!bodyObject);
1343
+ const matchingMediaType = Object.keys(bodyParameter?.bodyObject?.content ?? {}).find(isParamMediaTypeAllowed);
1344
+ if (matchingMediaType) {
1345
+ schema = bodyParameter?.bodyObject?.content?.[matchingMediaType]?.schema;
1346
+ info = `${isQuery(endpoint) ? "query" : "mutation"} data`;
1347
+ }
1348
+ }
1349
+ while (schema && index < pathSplits.length) {
1350
+ const resolvedSchema = resolver.resolveObject(schema);
1351
+ schema = Object.entries(resolvedSchema.properties ?? {}).find(([key]) => key === pathSplits[index])?.[1];
1352
+ required = resolvedSchema.required?.includes(pathSplits[index]) ?? false;
1353
+ index++;
1354
+ }
1355
+ if (!schema) return;
1356
+ return {
1357
+ name,
1358
+ type: isReferenceObject(schema) ? void 0 : schema.type,
1359
+ zodSchemaName: isReferenceObject(schema) ? resolver.getZodSchemaNameByRef(schema.$ref) : void 0,
1360
+ required,
1361
+ info
1362
+ };
1363
+ }
1364
+
1365
+ //#endregion
1366
+ //#region src/generators/core/zod/getZodChain.ts
1367
+ function getZodChain({ schema, meta, options }) {
1368
+ const chains = [];
1369
+ match(schema.type).with("string", () => chains.push(getZodChainableStringValidations(schema))).with("number", "integer", () => chains.push(getZodChainableNumberValidations(schema))).with("array", () => chains.push(getZodChainableArrayValidations(schema))).otherwise(() => void 0);
1370
+ if (typeof schema.description === "string" && schema.description !== "" && options.withDescription) chains.push(`describe(${JSON.stringify(schema.description)})`);
1371
+ const output = chains.concat(getZodChainablePresence({
1372
+ schema,
1373
+ meta,
1374
+ options
1375
+ }), options.withDefaultValues !== false ? getZodChainableDefault(schema) : []).filter(Boolean).join(".");
1376
+ return output ? `.${output}` : "";
1377
+ }
1378
+ function getZodChainablePresence({ schema, meta, options }) {
1379
+ if (schema.nullable && !meta?.isRequired) return "nullish()";
1380
+ if (schema.nullable || options.replaceOptionalWithNullish && meta?.isParentPartial) return "nullable()";
1381
+ if (!meta?.isRequired) return options.replaceOptionalWithNullish ? "nullish()" : "optional()";
1382
+ return "";
1383
+ }
1384
+ function getZodChainableDefault(schema) {
1385
+ if (schema.default !== void 0) return `default(${match(schema.type).with("number", "integer", () => unwrapQuotesIfNeeded(schema.default)).otherwise(() => JSON.stringify(schema.default))})`;
1386
+ return "";
1387
+ }
1388
+ function getZodChainableStringValidations(schema) {
1389
+ const validations = [];
1390
+ if (!schema.enum) {
1391
+ if (schema.minLength !== void 0) validations.push(`min(${schema.minLength})`);
1392
+ if (schema.maxLength !== void 0) validations.push(`max(${schema.maxLength})`);
1393
+ }
1394
+ if (schema.pattern) validations.push(`regex(${formatPatternIfNeeded(schema.pattern)})`);
1395
+ return validations.join(".");
1396
+ }
1397
+ function formatPatternIfNeeded(pattern) {
1398
+ if (pattern.startsWith("/") && pattern.endsWith("/")) pattern = pattern.slice(1, -1);
1399
+ pattern = escapeControlCharacters(pattern);
1400
+ return `/${pattern}/`;
1401
+ }
1402
+ function getZodChainableNumberValidations(schema) {
1403
+ const validations = [];
1404
+ if (schema.enum) return "";
1405
+ if (schema.minimum !== void 0) if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
1406
+ else validations.push(`gte(${schema.minimum})`);
1407
+ else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
1408
+ if (schema.maximum !== void 0) if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
1409
+ else validations.push(`lte(${schema.maximum})`);
1410
+ else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
1411
+ if (schema.multipleOf) validations.push(`multipleOf(${schema.multipleOf})`);
1412
+ return validations.join(".");
1413
+ }
1414
+ function getZodChainableArrayValidations(schema) {
1415
+ const validations = [];
1416
+ if (schema.minItems) validations.push(`min(${schema.minItems})`);
1417
+ if (schema.maxItems) validations.push(`max(${schema.maxItems})`);
1418
+ return validations.join(".");
1419
+ }
1420
+
1421
+ //#endregion
1422
+ //#region src/generators/core/zod/getZodSchemaRefs.ts
1423
+ function getZodSchemaRefs(resolver, zodSchemaName) {
1424
+ const schemaRef = resolver.getRefByZodSchemaName(zodSchemaName);
1425
+ if (schemaRef) {
1426
+ const refs = Array.from(resolver.dependencyGraph.refsDependencyGraph[schemaRef] ?? []).map((ref) => resolver.getZodSchemaNameByRef(ref));
1427
+ const enumRefs = resolver.getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef);
1428
+ return [...refs, ...enumRefs];
1429
+ }
1430
+ const zodSchema = resolver.getCompositeZodSchemaByZodSchemaName(zodSchemaName);
1431
+ if (zodSchema) return Array.from(getSchemaRefs(zodSchema)).map((schemaRef) => resolver.getZodSchemaNameByRef(schemaRef));
1432
+ return [];
1433
+ }
1434
+ function getSchemaRefs(zodSchema, { skipObjectSchema = false } = {}) {
1435
+ return zodSchema.children.reduce((acc, child) => {
1436
+ const ref = child.ref ?? child.enumRef;
1437
+ if (ref) acc.add(ref);
1438
+ if (child.children.length > 0 && (!skipObjectSchema || !isSchemaObject(child.schema) || child.schema.type !== "object")) getSchemaRefs(child).forEach((ref) => acc.add(ref));
1439
+ return acc;
1440
+ }, /* @__PURE__ */ new Set());
1441
+ }
1442
+
1443
+ //#endregion
1444
+ //#region src/generators/utils/math.utils.ts
1445
+ const sum = (arr) => arr.reduce((acc, item) => acc + item, 0);
1446
+
1447
+ //#endregion
1448
+ //#region src/generators/core/openapi/getOpenAPISchemaComplexity.ts
1449
+ function getOpenAPISchemaComplexity(current, schema) {
1450
+ if (!schema) return current;
1451
+ if (isReferenceObject(schema)) return current + 2;
1452
+ if (Array.isArray(schema.type)) {
1453
+ if (schema.type.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, {
1454
+ ...schema,
1455
+ type: schema.type[0]
1456
+ });
1457
+ return current + complexityByComposite("oneOf") + sum(schema.type.map((prop) => getOpenAPISchemaComplexity(0, {
1458
+ ...schema,
1459
+ type: prop
1460
+ })));
1461
+ }
1462
+ if (schema.oneOf) {
1463
+ if (schema.oneOf.length === 1) return complexityByComposite("oneOf") + getOpenAPISchemaComplexity(current, schema.oneOf[0]);
1464
+ return current + complexityByComposite("oneOf") + sum(schema.oneOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1465
+ }
1466
+ if (schema.anyOf) {
1467
+ if (schema.anyOf.length === 1) return complexityByComposite("anyOf") + getOpenAPISchemaComplexity(current, schema.anyOf[0]);
1468
+ return current + complexityByComposite("anyOf") + sum(schema.anyOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1469
+ }
1470
+ if (schema.allOf) {
1471
+ if (schema.allOf.length === 1) return complexityByComposite("allOf") + getOpenAPISchemaComplexity(current, schema.allOf[0]);
1472
+ return current + complexityByComposite("allOf") + sum(schema.allOf.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1473
+ }
1474
+ if (!schema.type) return current;
1475
+ if (isPrimitiveType(schema.type)) {
1476
+ if (schema.enum) return current + complexityByType(schema) + complexityByComposite("enum") + sum(schema.enum.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1477
+ return current + complexityByType(schema);
1478
+ }
1479
+ if (schema.type === "array") {
1480
+ if (schema.items) return complexityByComposite("array") + getOpenAPISchemaComplexity(current, schema.items);
1481
+ return complexityByComposite("array") + getOpenAPISchemaComplexity(current);
1482
+ }
1483
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
1484
+ if (schema.properties) {
1485
+ const props = Object.values(schema.properties);
1486
+ current += complexityByComposite("object") + sum(props.map((prop) => getOpenAPISchemaComplexity(0, prop)));
1487
+ } else current += complexityByComposite("empty-object");
1488
+ if (schema.additionalProperties) if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
1489
+ else current += getOpenAPISchemaComplexity(1);
1490
+ }
1491
+ return current;
1492
+ }
1493
+ function complexityByType(schema) {
1494
+ return match(schema.type).with("string", "number", "integer", "boolean", () => 1).otherwise(() => 0);
1495
+ }
1496
+ function complexityByComposite(type) {
1497
+ return match(type).with("oneOf", () => 2).with("anyOf", () => 3).with("allOf", () => 2).with("enum", "array", "empty-object", () => 1).with("object", () => 2).otherwise(() => 0);
1498
+ }
1499
+
1500
+ //#endregion
1501
+ //#region src/generators/core/zod/ZodSchema.class.ts
1502
+ var ZodSchema = class {
1503
+ code;
1504
+ ref;
1505
+ enumRef;
1506
+ children = [];
1507
+ meta;
1508
+ constructor(schema, resolver, meta = { referencedBy: [] }, enumRef) {
1509
+ this.schema = schema;
1510
+ this.resolver = resolver;
1511
+ if (isReferenceObject(schema)) this.ref = schema.$ref;
1512
+ if (enumRef) this.enumRef = enumRef;
1513
+ this.meta = {
1514
+ ...meta,
1515
+ referencedBy: [...meta?.referencedBy ?? []]
1516
+ };
1517
+ if (this.ref) this.meta.referencedBy.push(this);
1518
+ }
1519
+ getCodeString(tag, options) {
1520
+ if (!this.ref && this.code) return this.code;
1521
+ if (!this.ref) throw new Error("Zod schema is missing both ref and code");
1522
+ const zodSchemaName = this.resolver?.getZodSchemaNameByRef(this.ref);
1523
+ if (!zodSchemaName) return this.ref;
1524
+ const zodSchemaTag = this.resolver?.getTagByZodSchemaName(zodSchemaName);
1525
+ if (options?.tsNamespaces && zodSchemaTag && zodSchemaTag !== tag) return `${getNamespaceName({
1526
+ type: GenerateType.Models,
1527
+ tag: zodSchemaTag,
1528
+ options
1529
+ })}.${zodSchemaName}`;
1530
+ return zodSchemaName;
1531
+ }
1532
+ get complexity() {
1533
+ return getOpenAPISchemaComplexity(0, this.schema);
1534
+ }
1535
+ assign(code) {
1536
+ this.code = code;
1537
+ return this;
1538
+ }
1539
+ inherit(parent) {
1540
+ if (parent) parent.children.push(this);
1541
+ return this;
1542
+ }
1543
+ };
1544
+ function getParentRef(meta) {
1545
+ if (!meta) return;
1546
+ if (meta.parent?.ref) return meta.parent.ref;
1547
+ return getParentRef(meta.parent?.meta);
1548
+ }
1549
+
1550
+ //#endregion
1551
+ //#region src/generators/core/zod/getZodSchema.ts
1552
+ /**
1553
+ * @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject
1554
+ * @see https://github.com/colinhacks/zod
1555
+ */
1556
+ function getZodSchema({ schema, resolver, meta: inheritedMeta, tag }) {
1557
+ const zodSchema = new ZodSchema(schema, resolver, inheritedMeta);
1558
+ const meta = {
1559
+ parent: zodSchema.inherit(inheritedMeta?.parent),
1560
+ referencedBy: [...zodSchema.meta.referencedBy]
1561
+ };
1562
+ const params = {
1563
+ resolver,
1564
+ meta,
1565
+ tag
1566
+ };
1567
+ if (isReferenceObject(schema)) return getReferenceZodSchema({
1568
+ schema,
1569
+ zodSchema,
1570
+ resolver,
1571
+ meta,
1572
+ tag
1573
+ });
1574
+ const arrayZodSchema = getArrayZodSchema({
1575
+ schema,
1576
+ zodSchema,
1577
+ resolver,
1578
+ meta,
1579
+ tag
1580
+ });
1581
+ if (arrayZodSchema) return arrayZodSchema;
1582
+ const oneOfZodSchema = getOneOfZodSchema({
1583
+ schema,
1584
+ zodSchema,
1585
+ resolver,
1586
+ meta,
1587
+ tag
1588
+ });
1589
+ if (oneOfZodSchema) return oneOfZodSchema;
1590
+ const anyOfZodSchema = getAnyOfZodSchema({
1591
+ schema,
1592
+ zodSchema,
1593
+ resolver,
1594
+ meta,
1595
+ tag
1596
+ });
1597
+ if (anyOfZodSchema) return anyOfZodSchema;
1598
+ const allOfZodSchema = getAllOfZodSchema({
1599
+ schema,
1600
+ zodSchema,
1601
+ resolver,
1602
+ meta,
1603
+ tag
1604
+ });
1605
+ if (allOfZodSchema) return allOfZodSchema;
1606
+ const primitiveZodSchema = getPrimitiveZodSchema({
1607
+ schema,
1608
+ zodSchema,
1609
+ resolver,
1610
+ meta,
1611
+ tag
1612
+ });
1613
+ if (primitiveZodSchema) return primitiveZodSchema;
1614
+ const readonly = resolver.options.allReadonly ? ".readonly()" : "";
1615
+ if (isArraySchemaObject(schema)) {
1616
+ if (schema.items) return zodSchema.assign(`z.array(${getZodSchema({
1617
+ ...params,
1618
+ schema: schema.items
1619
+ }).getCodeString(tag, resolver.options)}${getZodChain({
1620
+ schema: schema.items,
1621
+ meta: {
1622
+ ...meta,
1623
+ isRequired: true
1624
+ },
1625
+ options: resolver.options
1626
+ })})${readonly}`);
1627
+ return zodSchema.assign(`z.array(${ANY_SCHEMA})${readonly}`);
1628
+ }
1629
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
1630
+ if (schemaType === "object" || schema.properties || schema.additionalProperties) {
1631
+ const hasRequiredArray = schema.required && schema.required.length > 0;
1632
+ const isPartial = resolver.options.withImplicitRequiredProps ? false : schema.properties && !schema.required?.length;
1633
+ let properties = "{}";
1634
+ if (schema.properties) properties = `{ ${Object.entries(schema.properties).map(([prop, propSchema]) => {
1635
+ const propMetadata = {
1636
+ ...meta,
1637
+ isRequired: isPartial ? true : hasRequiredArray ? schema.required?.includes(prop) : resolver.options.withImplicitRequiredProps,
1638
+ name: prop,
1639
+ isParentPartial: isPartial
1640
+ };
1641
+ let propActualSchema = propSchema;
1642
+ if (isReferenceObject(propSchema) && resolver) {
1643
+ propActualSchema = resolver.getSchemaByRef(propSchema.$ref);
1644
+ if (!propActualSchema) throw new Error(`Schema ${propSchema.$ref} not found`);
1645
+ }
1646
+ const zodSchema = getZodSchema({
1647
+ ...params,
1648
+ schema: propSchema,
1649
+ meta: propMetadata
1650
+ });
1651
+ const propZodSchema = zodSchema.getCodeString(tag, resolver.options) + getZodChain({
1652
+ schema: propActualSchema,
1653
+ meta: propMetadata,
1654
+ options: resolver.options
1655
+ });
1656
+ let isCircular = false;
1657
+ const parentRef = getParentRef(inheritedMeta);
1658
+ if (parentRef) isCircular = [...isReferenceObject(propSchema) ? [propSchema.$ref] : [], ...getSchemaRefs(zodSchema, { skipObjectSchema: true })].some((ref) => resolver.dependencyGraph.deepDependencyGraph[ref]?.has(parentRef));
1659
+ return [
1660
+ prop,
1661
+ propZodSchema,
1662
+ isCircular
1663
+ ];
1664
+ }).map(([prop, propSchema, isCircular]) => isCircular ? `get ${wrapWithQuotesIfNeeded(prop)}() { return ${propSchema} }` : `${wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
1665
+ let additionalPropsSchema = "";
1666
+ if (schema.additionalProperties) additionalPropsSchema = `.catchall(${typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0 ? getZodSchema({
1667
+ ...params,
1668
+ schema: schema.additionalProperties
1669
+ }).getCodeString(tag, resolver.options) + getZodChain({
1670
+ schema: schema.additionalProperties,
1671
+ meta: {
1672
+ ...meta,
1673
+ isRequired: true
1674
+ },
1675
+ options: resolver.options
1676
+ }) : ANY_SCHEMA})`;
1677
+ const zodObject = `z.object(${properties})${isPartial ? ".partial()" : ""}${additionalPropsSchema}${readonly}`;
1678
+ return zodSchema.assign(zodObject);
1679
+ }
1680
+ if (schemaType === "any") return zodSchema.assign(ANY_SCHEMA);
1681
+ if (schemaType === "null") return zodSchema.assign("z.null()");
1682
+ if (!schemaType) return zodSchema.assign("z.unknown()");
1683
+ throw new Error(`Unsupported schema type: ${schemaType}`);
1684
+ }
1685
+ function getReferenceZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1686
+ if (!isReferenceObject(schema)) return;
1687
+ const refsPath = zodSchema.meta.referencedBy.slice(0, -1).map((prev) => prev.ref ? resolver.getZodSchemaNameByRef(prev.ref) ?? prev.ref : void 0).filter(Boolean);
1688
+ const zodSchemaName = resolver.getZodSchemaNameByRef(schema.$ref);
1689
+ if (refsPath.length > 1 && refsPath.includes(zodSchemaName)) return zodSchema.assign(resolver.getCodeByZodSchemaName(zodSchema.ref));
1690
+ let result = resolver.getCodeByZodSchemaName(schema.$ref);
1691
+ if (!result) {
1692
+ const actualSchema = resolver.getSchemaByRef(schema.$ref);
1693
+ if (!actualSchema) throw new Error(`Schema ${schema.$ref} not found`);
1694
+ result = getZodSchema({
1695
+ schema: actualSchema,
1696
+ resolver,
1697
+ meta,
1698
+ tag
1699
+ }).getCodeString(tag, resolver.options);
1700
+ }
1701
+ if (resolver.getCodeByZodSchemaName(zodSchemaName)) return zodSchema;
1702
+ resolver.setZodSchema(zodSchemaName, result, tag);
1703
+ return zodSchema;
1704
+ }
1705
+ function getOneOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1706
+ if (!isSchemaObject(schema) || !schema.oneOf) return;
1707
+ if (schema.oneOf.length === 1) {
1708
+ const type = getZodSchema({
1709
+ schema: schema.oneOf[0],
1710
+ resolver,
1711
+ meta,
1712
+ tag
1713
+ });
1714
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1715
+ }
1716
+ const hasMultipleAllOf = schema.oneOf?.some((obj) => isSchemaObject(obj) && (obj?.allOf || []).length > 1);
1717
+ if (schema.discriminator && !hasMultipleAllOf) {
1718
+ const propertyName = schema.discriminator.propertyName;
1719
+ return zodSchema.assign(`
1720
+ z.discriminatedUnion("${propertyName}", [${schema.oneOf.map((schema) => getZodSchema({
1721
+ schema,
1722
+ resolver,
1723
+ meta,
1724
+ tag
1725
+ }).getCodeString(tag, resolver.options)).join(", ")}])
1726
+ `);
1727
+ }
1728
+ return zodSchema.assign(`z.union([${schema.oneOf.map((schema) => getZodSchema({
1729
+ schema,
1730
+ resolver,
1731
+ meta,
1732
+ tag
1733
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
1734
+ }
1735
+ function getArrayZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1736
+ if (!isSchemaObject(schema) || !Array.isArray(schema.type)) return;
1737
+ if (schema.type.length === 1) return getZodSchema({
1738
+ schema: {
1739
+ ...schema,
1740
+ type: schema.type[0]
1741
+ },
1742
+ resolver,
1743
+ meta,
1744
+ tag
1745
+ });
1746
+ return zodSchema.assign(`z.union([${schema.type.map((prop) => getZodSchema({
1747
+ schema: {
1748
+ ...schema,
1749
+ type: prop
1750
+ },
1751
+ resolver,
1752
+ meta,
1753
+ tag
1754
+ }).getCodeString(tag, resolver.options)).join(", ")}])`);
1755
+ }
1756
+ function getAnyOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1757
+ if (!isSchemaObject(schema) || !schema.anyOf) return;
1758
+ if (schema.anyOf.length === 1) {
1759
+ const type = getZodSchema({
1760
+ schema: schema.anyOf[0],
1761
+ resolver,
1762
+ meta,
1763
+ tag
1764
+ });
1765
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1766
+ }
1767
+ const types = schema.anyOf.map((schema) => getZodSchema({
1768
+ schema,
1769
+ resolver,
1770
+ meta,
1771
+ tag
1772
+ })).map((type) => type.getCodeString(tag, resolver.options)).join(", ");
1773
+ return zodSchema.assign(`z.union([${types}])`);
1774
+ }
1775
+ function getAllOfZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1776
+ if (!isSchemaObject(schema) || !schema.allOf) return;
1777
+ if (schema.allOf.length === 1) {
1778
+ const type = getZodSchema({
1779
+ schema: schema.allOf[0],
1780
+ resolver,
1781
+ meta,
1782
+ tag
1783
+ });
1784
+ return zodSchema.assign(type.getCodeString(tag, resolver.options));
1785
+ }
1786
+ const { patchRequiredSchemaInLoop, noRequiredOnlyAllof, composedRequiredSchema } = inferRequiredSchema(schema);
1787
+ const types = noRequiredOnlyAllof.map((schema) => {
1788
+ const type = getZodSchema({
1789
+ schema,
1790
+ resolver,
1791
+ meta,
1792
+ tag
1793
+ });
1794
+ if (resolver) patchRequiredSchemaInLoop(schema, resolver.getSchemaByRef.bind(resolver));
1795
+ return type;
1796
+ });
1797
+ if (composedRequiredSchema.required.length) types.push(getZodSchema({
1798
+ schema: composedRequiredSchema,
1799
+ resolver,
1800
+ meta,
1801
+ tag
1802
+ }));
1803
+ const first = types.at(0);
1804
+ const rest = types.slice(1).map((type) => `...${type.getCodeString(tag, resolver.options)}.shape`).join(", ");
1805
+ return zodSchema.assign(`z.object({ ...${first.getCodeString(tag, resolver.options)}.shape, ${rest} })`);
1806
+ }
1807
+ function getPrimitiveZodSchema({ schema, zodSchema, resolver, meta, tag }) {
1808
+ if (!isSchemaObject(schema)) return;
1809
+ const schemaType = schema.type ? schema.type.toLowerCase() : void 0;
1810
+ if (schemaType && isPrimitiveType(schemaType)) {
1811
+ if (schema.enum) {
1812
+ if (schemaType === "string") return getEnumZodSchema({
1813
+ schema,
1814
+ zodSchema,
1815
+ resolver,
1816
+ meta,
1817
+ tag
1818
+ });
1819
+ if (schema.enum.some((e) => typeof e === "string")) return zodSchema.assign("z.never()");
1820
+ if (schema.enum.length === 1) {
1821
+ const value = schema.enum[0];
1822
+ return zodSchema.assign(`z.literal(${value === null ? "null" : value})`);
1823
+ }
1824
+ return zodSchema.assign(`z.union([${schema.enum.map((value) => `z.literal(${value === null ? "null" : value})`).join(", ")}])`);
1825
+ }
1826
+ return zodSchema.assign(match(schemaType).with("integer", () => match(schema.type).with("integer", () => INT_SCHEMA).otherwise(() => NUMBER_SCHEMA)).with("string", () => match(schema.format).with("binary", () => BLOB_SCHEMA).with("email", () => EMAIL_SCHEMA).with("hostname", "uri", () => URL_SCHEMA).with("uuid", () => UUID_SCHEMA).with("date-time", () => DATETIME_SCHEMA).otherwise(() => STRING_SCHEMA)).otherwise((type) => `z.${type}()`));
1827
+ }
1828
+ }
1829
+ function getEnumZodSchema({ resolver, schema, zodSchema, meta, tag }) {
1830
+ if (!isSchemaObject(schema)) return;
1831
+ const code = getEnumZodSchemaCode(schema);
1832
+ if (!resolver.options.extractEnums) return zodSchema.assign(code);
1833
+ const enumZodSchema = resolver.getEnumZodSchemaDataByCode(code);
1834
+ if (enumZodSchema) {
1835
+ if (zodSchema.meta.parent?.ref === resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName)) return zodSchema.assign(enumZodSchema.code);
1836
+ return new ZodSchema({ $ref: resolver.getRefByZodSchemaName(enumZodSchema.zodSchemaName) }, resolver, meta).inherit(zodSchema).assign(code);
1837
+ }
1838
+ const extractedEnumZodSchema = resolver.getExtractedEnumZodSchemaDataByCode(code);
1839
+ if (!extractedEnumZodSchema) return zodSchema.assign(code);
1840
+ if (!extractedEnumZodSchema.zodSchemaName || !extractedEnumZodSchema.tag) throw new Error(`Enum zod schema name or tag not resolved for code: ${code}`);
1841
+ const namespacePrefix = resolver.options.tsNamespaces && extractedEnumZodSchema.tag !== tag ? `${getNamespaceName({
1842
+ type: GenerateType.Models,
1843
+ tag: extractedEnumZodSchema.tag,
1844
+ options: resolver.options
1845
+ })}.` : "";
1846
+ return zodSchema.assign(`${namespacePrefix}${extractedEnumZodSchema.zodSchemaName}`);
1847
+ }
1848
+ function getEnumZodSchemaCode(schema) {
1849
+ return `${ENUM_SCHEMA}([${schema.enum?.map((value) => value === null ? "null" : `"${value}"`).join(", ")}])`;
1850
+ }
1851
+ function getEnumZodSchemaCodeFromEnumNames(enumNames) {
1852
+ return `${ENUM_SCHEMA}([${enumNames.map((value) => `"${value}"`).join(", ")}])`;
1853
+ }
1854
+
1855
+ //#endregion
1856
+ //#region src/generators/core/zod/resolveZodSchemaName.ts
1857
+ const resolverResolveZodSchemaNameCache = /* @__PURE__ */ new WeakMap();
1858
+ function resolveZodSchemaName({ schema, zodSchema, fallbackName, resolver, tag }) {
1859
+ const result = zodSchema.getCodeString();
1860
+ const cacheKey = `${zodSchema.ref ?? ""}|${fallbackName ?? ""}|${tag}|${zodSchema.complexity}|${result}`;
1861
+ let cacheForResolver = resolverResolveZodSchemaNameCache.get(resolver);
1862
+ if (!cacheForResolver) {
1863
+ cacheForResolver = /* @__PURE__ */ new Map();
1864
+ resolverResolveZodSchemaNameCache.set(resolver, cacheForResolver);
1865
+ }
1866
+ const cachedName = cacheForResolver.get(cacheKey);
1867
+ if (cachedName) return cachedName;
1868
+ if ((!isNamedZodSchema(result) || zodSchema.ref === void 0) && fallbackName) {
1869
+ if (zodSchema.complexity < COMPLEXITY_THRESHOLD) return result;
1870
+ const zodSchemaName = getZodSchemaName(fallbackName, resolver.options.schemaSuffix);
1871
+ while (resolver.getCodeByZodSchemaName(zodSchemaName)) if (resolver.getZodSchemaNamesByCompositeCode(result)?.includes(zodSchemaName)) return zodSchemaName;
1872
+ else if (resolver.getCodeByZodSchemaName(zodSchemaName) === zodSchemaName) return zodSchemaName;
1873
+ else throw new Error(`Can't uniquely resolve zod schema name: ${zodSchemaName}`);
1874
+ resolver.setZodSchema(zodSchemaName, result, tag);
1875
+ resolver.addZodSchemaForCompositeCode(result, zodSchema, zodSchemaName, schema);
1876
+ cacheForResolver.set(cacheKey, zodSchemaName);
1877
+ return zodSchemaName;
1878
+ }
1879
+ let resolvedSchema = resolver.getCodeByZodSchemaName(result);
1880
+ if (!resolvedSchema && zodSchema.ref) resolvedSchema = resolver.getCodeByZodSchemaName(resolver.getZodSchemaNameByRef(zodSchema.ref));
1881
+ if (zodSchema.ref && resolvedSchema) {
1882
+ if (getOpenAPISchemaComplexity(0, resolver.getSchemaByRef(zodSchema.ref)) < COMPLEXITY_THRESHOLD) {
1883
+ const resolvedName = resolver.getCodeByZodSchemaName(result);
1884
+ cacheForResolver.set(cacheKey, resolvedName);
1885
+ return resolvedName;
1886
+ }
1887
+ cacheForResolver.set(cacheKey, result);
1888
+ return result;
1889
+ }
1890
+ if (zodSchema.ref) {
1891
+ const resolvedRefName = resolver.getZodSchemaNameByRef(zodSchema.ref);
1892
+ cacheForResolver.set(cacheKey, resolvedRefName);
1893
+ return resolvedRefName;
1894
+ }
1895
+ throw new Error(`Invalid ref: ${zodSchema.ref}`);
1896
+ }
1897
+
1898
+ //#endregion
1899
+ //#region src/generators/core/endpoints/resolveEndpointZodSchema.ts
1900
+ const resolverEndpointZodSchemaCache = /* @__PURE__ */ new WeakMap();
1901
+ function getResolverSchemaCache(resolver) {
1902
+ let schemaCache = resolverEndpointZodSchemaCache.get(resolver);
1903
+ if (!schemaCache) {
1904
+ schemaCache = {
1905
+ byObject: /* @__PURE__ */ new WeakMap(),
1906
+ byRef: /* @__PURE__ */ new Map()
1907
+ };
1908
+ resolverEndpointZodSchemaCache.set(resolver, schemaCache);
1909
+ }
1910
+ return schemaCache;
1911
+ }
1912
+ function getOrCreateSchemaEntries(schemaCache, schema) {
1913
+ if (isReferenceObject(schema)) {
1914
+ let entries = schemaCache.byRef.get(schema.$ref);
1915
+ if (!entries) {
1916
+ entries = /* @__PURE__ */ new Map();
1917
+ schemaCache.byRef.set(schema.$ref, entries);
1918
+ }
1919
+ return entries;
1920
+ }
1921
+ let entries = schemaCache.byObject.get(schema);
1922
+ if (!entries) {
1923
+ entries = /* @__PURE__ */ new Map();
1924
+ schemaCache.byObject.set(schema, entries);
1925
+ }
1926
+ return entries;
1927
+ }
1928
+ function resolveEndpointZodSchema({ resolver, schema, meta, tag, fallbackName, composeBeforeResolve }) {
1929
+ const entries = getOrCreateSchemaEntries(getResolverSchemaCache(resolver), schema);
1930
+ const isRefSchema = isReferenceObject(schema);
1931
+ const normalizedFallbackName = isRefSchema ? "" : fallbackName ?? "";
1932
+ const normalizedTag = isRefSchema ? "" : tag;
1933
+ const metaKey = `required:${Boolean(meta.isRequired)}|name:${meta.name ?? ""}|parentPartial:${Boolean(meta.isParentPartial)}|fallback:${normalizedFallbackName}|tag:${normalizedTag}|compose:${composeBeforeResolve ? 1 : 0}`;
1934
+ const cached = entries.get(metaKey);
1935
+ if (cached) return cached;
1936
+ const zodSchema = getZodSchema({
1937
+ schema,
1938
+ resolver,
1939
+ meta,
1940
+ tag
1941
+ });
1942
+ const schemaObject = resolver.resolveObject(schema);
1943
+ const zodChain = getZodChain({
1944
+ schema: schemaObject,
1945
+ meta: zodSchema.meta,
1946
+ options: resolver.options
1947
+ });
1948
+ const resolved = composeBeforeResolve ? resolveZodSchemaName({
1949
+ schema: schemaObject,
1950
+ zodSchema: zodSchema.assign(zodSchema.getCodeString(tag) + zodChain),
1951
+ fallbackName,
1952
+ resolver,
1953
+ tag
1954
+ }) : `${resolveZodSchemaName({
1955
+ schema: schemaObject,
1956
+ zodSchema,
1957
+ fallbackName,
1958
+ resolver,
1959
+ tag
1960
+ })}${zodChain}`;
1961
+ entries.set(metaKey, resolved);
1962
+ return resolved;
1963
+ }
1964
+
1965
+ //#endregion
1966
+ //#region src/generators/core/endpoints/getEndpointBody.ts
1967
+ function getEndpointBody({ resolver, operation, operationName, isUniqueOperationName, tag }) {
1968
+ const requestBodyObj = resolver.resolveObject(operation.requestBody);
1969
+ if (!requestBodyObj) return;
1970
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
1971
+ if (!matchingMediaType) return;
1972
+ const schema = requestBodyObj.content?.[matchingMediaType]?.schema;
1973
+ if (!schema) return;
1974
+ const zodSchema = resolveEndpointZodSchema({
1975
+ resolver,
1976
+ schema,
1977
+ meta: { isRequired: requestBodyObj.required ?? true },
1978
+ tag,
1979
+ fallbackName: getBodyZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag)),
1980
+ composeBeforeResolve: false
1981
+ });
1982
+ return {
1983
+ endpointParameter: {
1984
+ name: BODY_PARAMETER_NAME,
1985
+ type: "Body",
1986
+ description: requestBodyObj.description,
1987
+ zodSchema,
1988
+ bodyObject: requestBodyObj
1989
+ },
1990
+ requestFormat: matchingMediaType
1991
+ };
1992
+ }
1993
+
1994
+ //#endregion
1995
+ //#region src/generators/core/endpoints/getEndpointParameter.ts
1996
+ function getEndpointParameter({ resolver, param, operationName, isUniqueOperationName, tag }) {
1997
+ const paramObj = resolver.resolveObject(param);
1998
+ if (!ALLOWED_PATH_IN.includes(paramObj.in)) return;
1999
+ let schema = {};
2000
+ if (paramObj.content) {
2001
+ const mediaTypes = Object.keys(paramObj.content ?? {});
2002
+ const matchingMediaType = mediaTypes.find(isParamMediaTypeAllowed);
2003
+ if (!matchingMediaType) throw new Error(`Unsupported media type for param ${paramObj.name}: ${mediaTypes.join(", ")}`);
2004
+ const mediaTypeObject = paramObj.content?.[matchingMediaType];
2005
+ if (!mediaTypeObject) throw new Error(`No content with media type for param ${paramObj.name}: ${matchingMediaType}`);
2006
+ schema = mediaTypeObject?.schema ?? mediaTypeObject;
2007
+ } else if (paramObj.schema) schema = paramObj.schema;
2008
+ if (resolver.options.withDescription && schema) schema.description = (paramObj.description ?? "").trim();
2009
+ const fallbackName = getParamZodSchemaName(getZodSchemaOperationName(operationName, isUniqueOperationName, tag), paramObj.name);
2010
+ let parameterSortingEnumSchemaName = void 0;
2011
+ if (isSortingParameterObject(paramObj)) {
2012
+ const enumZodSchemaName = getEnumZodSchemaName(fallbackName, resolver.options.enumSuffix, resolver.options.schemaSuffix);
2013
+ const code = getEnumZodSchemaCodeFromEnumNames(paramObj["x-enumNames"]);
2014
+ resolver.setZodSchema(enumZodSchemaName, code, tag);
2015
+ parameterSortingEnumSchemaName = enumZodSchemaName;
2016
+ }
2017
+ const zodSchemaName = resolveEndpointZodSchema({
2018
+ resolver,
2019
+ schema,
2020
+ meta: { isRequired: paramObj.in === "path" ? true : paramObj.required ?? false },
2021
+ tag,
2022
+ fallbackName,
2023
+ composeBeforeResolve: true
2024
+ });
2025
+ return {
2026
+ name: match(paramObj.in).with("path", () => pathParamToVariableName(paramObj.name)).otherwise(() => paramObj.name),
2027
+ type: match(paramObj.in).with("header", () => "Header").with("query", () => "Query").with("path", () => "Path").run(),
2028
+ zodSchema: zodSchemaName,
2029
+ parameterObject: paramObj,
2030
+ parameterSortingEnumSchemaName
2031
+ };
2032
+ }
2033
+
2034
+ //#endregion
2035
+ //#region src/generators/core/endpoints/getEndpointsFromOpenAPIDoc.ts
2036
+ function getEndpointsFromOpenAPIDoc(resolver, profiler) {
2037
+ const endpoints = [];
2038
+ const p = profiler ?? new Profiler(false);
2039
+ for (const context of resolver.getOperationContexts()) endpoints.push(buildEndpointFromOperationContext(resolver, context, p));
2040
+ return endpoints;
2041
+ }
2042
+ function buildEndpointFromOperationContext(resolver, context, profiler) {
2043
+ const p = profiler ?? new Profiler(false);
2044
+ const { path, method, operation, operationName, isUniqueOperationName, tag, parameters, responses } = context;
2045
+ const invalidOperationId = operation.operationId && operation.operationId !== invalidVariableNameCharactersToCamel(operation.operationId);
2046
+ if (operation.operationId && invalidOperationId) resolver.validationErrors.push(getInvalidOperationIdError(operation.operationId));
2047
+ const endpoint = {
2048
+ method,
2049
+ path: replaceHyphenatedPath(path),
2050
+ operationName,
2051
+ description: operation.description,
2052
+ summary: operation.summary,
2053
+ tags: operation.tags?.map(formatTag),
2054
+ requestFormat: JSON_APPLICATION_FORMAT,
2055
+ parameters: [],
2056
+ response: "",
2057
+ errors: [],
2058
+ responseStatusCodes: [],
2059
+ mediaUpload: !!operation["x-media-upload"],
2060
+ mediaDownload: !!operation["x-media-download"]
2061
+ };
2062
+ p.runSync("endpoints.requestBody", () => {
2063
+ if (operation.requestBody) {
2064
+ const body = getEndpointBody({
2065
+ resolver,
2066
+ operation,
2067
+ operationName,
2068
+ isUniqueOperationName,
2069
+ tag
2070
+ });
2071
+ if (body) {
2072
+ endpoint.parameters.push(body.endpointParameter);
2073
+ endpoint.requestFormat = body.requestFormat;
2074
+ }
2075
+ }
2076
+ });
2077
+ p.runSync("endpoints.params", () => {
2078
+ for (const param of parameters) {
2079
+ const endpointParameter = getEndpointParameter({
2080
+ resolver,
2081
+ param,
2082
+ operationName,
2083
+ isUniqueOperationName,
2084
+ tag
2085
+ });
2086
+ if (endpointParameter) endpoint.parameters.push(endpointParameter);
2087
+ }
2088
+ });
2089
+ p.runSync("endpoints.pathParams", () => {
2090
+ const missingPathParameters = getMissingPathParameters(endpoint);
2091
+ missingPathParameters.forEach((pathParam) => {
2092
+ endpoint.parameters.push(pathParam);
2093
+ });
2094
+ if (missingPathParameters.length > 0) resolver.validationErrors.push(getMissingPathParameterError(missingPathParameters, path));
2095
+ });
2096
+ p.runSync("endpoints.responses", () => {
2097
+ for (const responseData of responses) {
2098
+ const { statusCode, responseObj, matchingMediaType, schema } = responseData;
2099
+ endpoint.responseStatusCodes.push(statusCode);
2100
+ let responseZodSchema;
2101
+ if (matchingMediaType) endpoint.responseFormat = matchingMediaType;
2102
+ else {
2103
+ responseZodSchema = VOID_SCHEMA;
2104
+ if (statusCode === "200") resolver.validationErrors.push(getInvalidStatusCodeError({
2105
+ received: "200",
2106
+ expected: "204"
2107
+ }, operation, endpoint));
2108
+ }
2109
+ if (schema) responseZodSchema = resolveEndpointZodSchema({
2110
+ resolver,
2111
+ schema,
2112
+ meta: { isRequired: true },
2113
+ tag,
2114
+ fallbackName: isReferenceObject(schema) ? void 0 : getResponseZodSchemaName({
2115
+ statusCode,
2116
+ operationName,
2117
+ isUniqueOperationName,
2118
+ tag
2119
+ }),
2120
+ composeBeforeResolve: false
2121
+ });
2122
+ if (responseZodSchema) {
2123
+ const status = Number(statusCode);
2124
+ if (isMainResponseStatus(status) && !endpoint.response) {
2125
+ endpoint.response = responseZodSchema;
2126
+ endpoint.responseObject = responseObj;
2127
+ endpoint.responseDescription = responseObj?.description;
2128
+ } else if (statusCode !== "default" && isErrorStatus(status)) endpoint.errors.push({
2129
+ zodSchema: responseZodSchema,
2130
+ status,
2131
+ description: responseObj?.description
2132
+ });
2133
+ }
2134
+ }
2135
+ });
2136
+ if (!endpoint.response) endpoint.response = VOID_SCHEMA;
2137
+ p.runSync("endpoints.statusValidation", () => {
2138
+ const mainStatusCodes = Object.keys(operation.responses).map(Number).filter(isMainResponseStatus);
2139
+ if (mainStatusCodes.length > 1) resolver.validationErrors.push(getMultipleSuccessStatusCodesError(mainStatusCodes.map(String), operation, endpoint));
2140
+ });
2141
+ p.runSync("endpoints.acl", () => {
2142
+ endpoint.acl = getEndpointAcl({
2143
+ resolver,
2144
+ endpoint,
2145
+ operation
2146
+ });
2147
+ });
2148
+ if (operation.security?.[0].Authorization && !endpoint.responseStatusCodes.includes("401")) resolver.validationErrors.push(getMissingStatusCodeError("401", operation, endpoint));
2149
+ if (endpoint.acl?.[0] && !endpoint.responseStatusCodes.includes("403")) resolver.validationErrors.push(getMissingStatusCodeError("403", operation, endpoint));
2150
+ return endpoint;
2151
+ }
2152
+ function getMissingPathParameters(endpoint) {
2153
+ return [...endpoint.path.matchAll(/:([a-zA-Z0-9_]+)/g)].map((param) => param[1]).filter((pathParam) => endpoint.parameters.findIndex(({ name }) => name === pathParam) === -1).map((name) => getPathParameterFromName(name));
2154
+ }
2155
+ function getPathParameterFromName(name) {
2156
+ return {
2157
+ name,
2158
+ type: "Path",
2159
+ zodSchema: STRING_SCHEMA,
2160
+ parameterObject: {
2161
+ name,
2162
+ required: true,
2163
+ in: "path",
2164
+ schema: { type: "string" }
2165
+ }
2166
+ };
2167
+ }
2168
+
2169
+ //#endregion
2170
+ //#region src/generators/utils/object.utils.ts
2171
+ /** Pick given properties in object */
2172
+ function pick(obj, paths) {
2173
+ const result = {};
2174
+ Object.keys(obj).forEach((key) => {
2175
+ if (!paths.includes(key)) return;
2176
+ result[key] = obj[key];
2177
+ });
2178
+ return result;
2179
+ }
2180
+ /**
2181
+ * Deep merge two or more objects/arrays recursively.
2182
+ * Arrays are concatenated, objects are merged recursively.
2183
+ * Later arguments take precedence over earlier ones.
2184
+ * Returns a new object/array without mutating the originals.
2185
+ */
2186
+ function deepMerge(source, ...sources) {
2187
+ if (sources.length === 0) return source;
2188
+ let result = source;
2189
+ for (const source of sources) result = mergeTwoValues(result, source);
2190
+ return result;
2191
+ }
2192
+ /**
2193
+ * Merge two values recursively
2194
+ */
2195
+ function mergeTwoValues(target, source) {
2196
+ if (source === null || source === void 0) return target;
2197
+ if (target === null || target === void 0) return deepClone(source);
2198
+ if (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];
2199
+ if (isPlainObject(target) && isPlainObject(source)) {
2200
+ const result = {};
2201
+ for (const [key, targetValue] of Object.entries(target)) result[key] = deepClone(targetValue);
2202
+ for (const [key, sourceValue] of Object.entries(source)) {
2203
+ const targetValue = result[key];
2204
+ if (sourceValue === void 0) continue;
2205
+ else if (sourceValue === null) result[key] = sourceValue;
2206
+ else if (isPlainObject(targetValue) && isPlainObject(sourceValue)) result[key] = mergeTwoValues(targetValue, sourceValue);
2207
+ else if (Array.isArray(targetValue) && Array.isArray(sourceValue)) result[key] = [...targetValue, ...sourceValue];
2208
+ else result[key] = deepClone(sourceValue);
2209
+ }
2210
+ return result;
2211
+ }
2212
+ return deepClone(source);
2213
+ }
2214
+ /**
2215
+ * Deep clone an object or array to avoid reference sharing.
2216
+ * Helper function for deepMerge.
2217
+ */
2218
+ function deepClone(obj) {
2219
+ if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
2220
+ if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
2221
+ if (isPlainObject(obj)) {
2222
+ const result = {};
2223
+ for (const [key, value] of Object.entries(obj)) result[key] = deepClone(value);
2224
+ return result;
2225
+ }
2226
+ return obj;
2227
+ }
2228
+ /**
2229
+ * Check if a value is a plain object (not an array, Date, etc.)
2230
+ */
2231
+ function isPlainObject(obj) {
2232
+ return obj !== null && typeof obj === "object" && !Array.isArray(obj) && Object.prototype.toString.call(obj) === "[object Object]";
2233
+ }
2234
+
2235
+ //#endregion
2236
+ //#region src/generators/const/js.const.ts
2237
+ const RESERVED_WORDS = [
2238
+ "break",
2239
+ "case",
2240
+ "catch",
2241
+ "class",
2242
+ "const",
2243
+ "continue",
2244
+ "debugger",
2245
+ "default",
2246
+ "delete",
2247
+ "do",
2248
+ "else",
2249
+ "export",
2250
+ "extends",
2251
+ "false",
2252
+ "finally",
2253
+ "for",
2254
+ "function",
2255
+ "if",
2256
+ "import",
2257
+ "in",
2258
+ "instanceof",
2259
+ "new",
2260
+ "null",
2261
+ "return",
2262
+ "super",
2263
+ "switch",
2264
+ "this",
2265
+ "throw",
2266
+ "true",
2267
+ "try",
2268
+ "typeof",
2269
+ "var",
2270
+ "void",
2271
+ "while",
2272
+ "with"
2273
+ ];
2274
+
2275
+ //#endregion
2276
+ //#region src/generators/utils/operation.utils.ts
2277
+ function isOperationExcluded(operation, options) {
2278
+ const isDeprecated = operation.deprecated && !options.withDeprecatedEndpoints;
2279
+ const isExcluded = isTagExcluded(getOperationTag(operation, options), options);
2280
+ return isDeprecated || isExcluded;
2281
+ }
2282
+ function getOperationName({ path, method, operation, options, tag, keepOperationTag, keepOperationPrefix }) {
2283
+ const pathOperationName = `${method}${pathToVariableName(path)}`;
2284
+ let operationName = operation.operationId ? invalidVariableNameCharactersToCamel(operation.operationId) : pathOperationName;
2285
+ if (options.removeOperationPrefixEndingWith && keepOperationPrefix) operationName = operationName.split(options.removeOperationPrefixEndingWith).map((split, index) => index === 0 ? split : capitalize(split)).join("");
2286
+ else if (options.removeOperationPrefixEndingWith && !keepOperationPrefix) {
2287
+ const regex = new RegExp(`^.*${options.removeOperationPrefixEndingWith}`);
2288
+ operationName = operationName.replace(regex, "");
2289
+ }
2290
+ if (options.tsNamespaces && !keepOperationTag) {
2291
+ const operationNameWithoutTag = removeWord(operationName, tag);
2292
+ if (operationNameWithoutTag === "") operationName = method.toLowerCase();
2293
+ else if (!RESERVED_WORDS.includes(operationNameWithoutTag)) operationName = operationNameWithoutTag;
2294
+ }
2295
+ return RESERVED_WORDS.includes(operationName) ? pathOperationName : operationName;
2296
+ }
2297
+ function getUniqueOperationName({ operationsByTag, ...params }) {
2298
+ const { operation, options } = params;
2299
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
2300
+ const operationName = (keepOperationTag) => {
2301
+ const name = getOperationName({
2302
+ ...params,
2303
+ tag,
2304
+ keepOperationTag
2305
+ });
2306
+ if (operationsByTag[tag].filter((operation) => getOperationName({
2307
+ ...params,
2308
+ operation,
2309
+ tag,
2310
+ keepOperationTag
2311
+ }) === name).length === 1) return name;
2312
+ };
2313
+ return operationName() ?? operationName(true) ?? getOperationName({
2314
+ ...params,
2315
+ tag,
2316
+ keepOperationTag: true,
2317
+ keepOperationPrefix: true
2318
+ });
2319
+ }
2320
+ function getUniqueOperationNamesWithoutSplitByTags(openApiDoc, operationsByTag, options) {
2321
+ const operationNames = [];
2322
+ for (const path in openApiDoc.paths) {
2323
+ if (isPathExcluded(path, options)) continue;
2324
+ const pathItemObj = openApiDoc.paths[path];
2325
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2326
+ for (const method in pathItem) {
2327
+ const operation = pathItem[method];
2328
+ if (!operation || isOperationExcluded(operation, options)) continue;
2329
+ const operationName = getUniqueOperationName({
2330
+ path,
2331
+ method,
2332
+ operation,
2333
+ operationsByTag,
2334
+ options
2335
+ });
2336
+ operationNames.push(operationName);
2337
+ }
2338
+ }
2339
+ return operationNames;
2340
+ }
2341
+ function getOperationsByTag(openApiDoc, options) {
2342
+ const operationsByTag = {};
2343
+ for (const path in openApiDoc.paths) {
2344
+ if (isPathExcluded(path, options)) continue;
2345
+ const pathItemObj = openApiDoc.paths[path];
2346
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2347
+ for (const method in pathItem) {
2348
+ const operation = pathItem[method];
2349
+ if (!operation || isOperationExcluded(operation, options)) continue;
2350
+ const tag = options.splitByTags ? getOperationTag(operation, options) : options.defaultTag;
2351
+ if (!operationsByTag[tag]) operationsByTag[tag] = [];
2352
+ operationsByTag[tag].push(operation);
2353
+ }
2354
+ }
2355
+ return operationsByTag;
2356
+ }
2357
+
2358
+ //#endregion
2359
+ //#region src/generators/core/openapi/getOpenAPISchemaDependencyGraph.ts
2360
+ function getOpenAPISchemaDependencyGraph(schemaRef, getSchemaByRef) {
2361
+ const refsDependencyGraph = getRefsDependencyGraph(schemaRef, getSchemaByRef);
2362
+ return {
2363
+ refsDependencyGraph,
2364
+ deepDependencyGraph: getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph)
2365
+ };
2366
+ }
2367
+ function getRefsDependencyGraph(schemaRef, getSchemaByRef) {
2368
+ const visitedRefs = {};
2369
+ const refsDependencyGraph = {};
2370
+ schemaRef.forEach((ref) => getSchemaRefsDependencyGraph({
2371
+ schema: getSchemaByRef(ref),
2372
+ fromRef: ref,
2373
+ getSchemaByRef,
2374
+ visitedRefs,
2375
+ refsDependencyGraph
2376
+ }));
2377
+ return refsDependencyGraph;
2378
+ }
2379
+ function getDeepRefsDependencyGraph(schemaRef, refsDependencyGraph) {
2380
+ const visitedDeepRefs = {};
2381
+ const deepDependencyGraph = {};
2382
+ const visit = (dep, ref) => {
2383
+ deepDependencyGraph[ref].add(dep);
2384
+ if (refsDependencyGraph[dep] && ref !== dep) refsDependencyGraph[dep].forEach((transitive) => {
2385
+ const refName = `${ref}__${transitive}`;
2386
+ if (visitedDeepRefs[refName]) return;
2387
+ visitedDeepRefs[refName] = true;
2388
+ visit(transitive, ref);
2389
+ });
2390
+ };
2391
+ schemaRef.forEach((ref) => {
2392
+ const deps = refsDependencyGraph[ref];
2393
+ if (!deps) return;
2394
+ if (!deepDependencyGraph[ref]) deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
2395
+ deps.forEach((dep) => visit(dep, ref));
2396
+ });
2397
+ return deepDependencyGraph;
2398
+ }
2399
+ function getSchemaRefsDependencyGraph({ schema, fromRef, getSchemaByRef, visitedRefs = {}, refsDependencyGraph = {} }) {
2400
+ const onSchema = (callbackData) => {
2401
+ if (callbackData.type !== "reference" || !callbackData.data) return;
2402
+ const { schema, data } = callbackData;
2403
+ if (!refsDependencyGraph[data.fromRef]) refsDependencyGraph[data.fromRef] = /* @__PURE__ */ new Set();
2404
+ refsDependencyGraph[data.fromRef].add(schema.$ref);
2405
+ if (visitedRefs[schema.$ref]) return true;
2406
+ visitedRefs[data.fromRef] = true;
2407
+ iterateSchema(getSchemaByRef(schema.$ref), {
2408
+ data: { fromRef: schema.$ref },
2409
+ onSchema
2410
+ });
2411
+ };
2412
+ iterateSchema(schema, {
2413
+ data: { fromRef },
2414
+ onSchema
2415
+ });
2416
+ return {
2417
+ visitedRefs,
2418
+ refsDependencyGraph
2419
+ };
2420
+ }
2421
+
2422
+ //#endregion
2423
+ //#region src/generators/core/openapi/getSchemaRefObjs.ts
2424
+ function getSchemaRefObjs(resolver, schema, schemaInfo) {
2425
+ const schemaRefObjs = [];
2426
+ const onSchema = (data) => {
2427
+ if (data.type === "reference") schemaRefObjs.push(data.schema);
2428
+ else if (isReferenceObject(data.parentSchema)) {
2429
+ if (data.type === "property") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and properties`));
2430
+ else if (data.type === "additionalProperties") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and additionalProperties`));
2431
+ else if (data.type === "array") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} is both reference and array schema`));
2432
+ else if (data.type === "composite") resolver.validationErrors.push(getInvalidSchemaError(`${schemaInfo} has both reference and composite keyword`));
2433
+ }
2434
+ };
2435
+ iterateSchema(schema, { onSchema });
2436
+ return schemaRefObjs;
2437
+ }
2438
+ function getDeepSchemaRefObjs(resolver, schemaRefs) {
2439
+ return schemaRefs.map((schemaRef) => autocorrectRef(schemaRef.$ref)).reduce((acc, schemaRef) => {
2440
+ const refs = resolver.dependencyGraph.deepDependencyGraph[schemaRef];
2441
+ return [
2442
+ ...acc,
2443
+ schemaRef,
2444
+ ...Array.from(refs ?? [])
2445
+ ];
2446
+ }, []);
2447
+ }
2448
+
2449
+ //#endregion
2450
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.ts
2451
+ function resolveExtractedEnumZodSchemaNames(resolver) {
2452
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2453
+ const mostCommonLastSegment = getMostCommonAdjacentCombinationSplit(enumData.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - 1]).filter(Boolean));
2454
+ if (!mostCommonLastSegment) throw new Error(`No common last segment found for enum: ${enumData.code}`);
2455
+ enumData.zodSchemaName = getEnumZodSchemaName(mostCommonLastSegment, resolver.options.enumSuffix, resolver.options.schemaSuffix);
2456
+ });
2457
+ let nameResolutionIterationsCounter = 0;
2458
+ while (nameResolutionIterationsCounter < 5) {
2459
+ if (allExtractedEnumZodSchemaNamesAreUnique(resolver)) break;
2460
+ additionalResolveExtractedEnumZodSchemaName(resolver, nameResolutionIterationsCounter + 2);
2461
+ nameResolutionIterationsCounter++;
2462
+ }
2463
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) resolver.extractedEnumZodSchemaData.filter((enumData) => !isUnique(resolver, enumData)).forEach((enumData) => {
2464
+ enumData.zodSchemaName = getEnumZodSchemaName(enumData.meta.zodSchemaNameSegments[0].map((name) => sanitizeName(capitalize(name))).join(""), resolver.options.enumSuffix, resolver.options.schemaSuffix);
2465
+ });
2466
+ if (!allExtractedEnumZodSchemaNamesAreUnique(resolver)) throw new Error("Failed to resolve unique names for enum zod schemas");
2467
+ }
2468
+ function allExtractedEnumZodSchemaNamesAreUnique(resolver) {
2469
+ return resolver.extractedEnumZodSchemaData.every((enumData) => isUnique(resolver, enumData));
2470
+ }
2471
+ function additionalResolveExtractedEnumZodSchemaName(resolver, index) {
2472
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2473
+ const enumsDataWithSameName = resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName);
2474
+ if (enumsDataWithSameName.length === 1) return;
2475
+ suffixWithPreviousSegmentName(enumsDataWithSameName, index);
2476
+ });
2477
+ }
2478
+ function suffixWithPreviousSegmentName(enumsData, index = 2) {
2479
+ enumsData.forEach((data) => {
2480
+ const precedingLastFragments = data.meta.zodSchemaNameSegments.map((arr) => arr[arr.length - index]).filter(Boolean);
2481
+ if (precedingLastFragments.length === 1) data.zodSchemaName = [sanitizeName(capitalize(precedingLastFragments[0])), data.zodSchemaName].filter(Boolean).join("");
2482
+ else {
2483
+ const secondLastFragmentSplit = getMostCommonAdjacentCombinationSplit(precedingLastFragments);
2484
+ data.zodSchemaName = [secondLastFragmentSplit ? sanitizeName(capitalize(secondLastFragmentSplit)) : "", data.zodSchemaName].filter(Boolean).join("");
2485
+ }
2486
+ });
2487
+ }
2488
+ function isUnique(resolver, enumData) {
2489
+ return resolver.extractedEnumZodSchemaData.filter(({ zodSchemaName }) => enumData.zodSchemaName === zodSchemaName).length === 1;
2490
+ }
2491
+ function sanitizeName(name) {
2492
+ return name.replace(/(Dto|DTO|Response|Request)/g, "");
2493
+ }
2494
+
2495
+ //#endregion
2496
+ //#region src/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.ts
2497
+ function resolveExtractedEnumZodSchemaTags(resolver) {
2498
+ resolver.extractedEnumZodSchemaData.forEach((enumData) => {
2499
+ const tags = getUniqueArray(enumData.meta.tags);
2500
+ enumData.tag = tags.length === 1 ? tags[0] : resolver.options.defaultTag;
2501
+ });
2502
+ }
2503
+
2504
+ //#endregion
2505
+ //#region src/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.ts
2506
+ function updateExtractedEnumZodSchemaData({ schema, nameSegments = [], includeSelf, ...params }) {
2507
+ if (includeSelf) handleExtractedEnumZodSchemaDataUpdate({
2508
+ schema,
2509
+ nameSegments,
2510
+ ...params
2511
+ });
2512
+ const onSchema = (data) => {
2513
+ if (data.type === "reference") return true;
2514
+ const segments = [...data.data?.nameSegments ?? []];
2515
+ if (data.type === "property") segments.push(data.propertyName);
2516
+ handleExtractedEnumZodSchemaDataUpdate({
2517
+ schema: data.schema,
2518
+ nameSegments: [...segments],
2519
+ ...params
2520
+ });
2521
+ };
2522
+ iterateSchema(schema, {
2523
+ data: { nameSegments },
2524
+ onSchema
2525
+ });
2526
+ }
2527
+ function handleExtractedEnumZodSchemaDataUpdate({ resolver, schema, schemaRef, schemaInfo, tags, nameSegments = [] }) {
2528
+ if (!schema || isReferenceObject(schema) || !schema.enum) return;
2529
+ const code = getEnumZodSchemaCode(schema);
2530
+ const enumZodSchema = resolver.extractedEnumZodSchemaData.find((data) => data.code === code);
2531
+ if (enumZodSchema) {
2532
+ enumZodSchema.meta.zodSchemaNameSegments.push(nameSegments);
2533
+ enumZodSchema.meta.tags.push(...tags);
2534
+ enumZodSchema.meta.schemaRefs.push(...schemaRef ? [schemaRef] : []);
2535
+ enumZodSchema.meta.schemas.push(...schema ? [schema] : []);
2536
+ } else resolver.extractedEnumZodSchemaData.push({
2537
+ code,
2538
+ meta: {
2539
+ zodSchemaNameSegments: [nameSegments],
2540
+ tags: [...tags],
2541
+ schemaRefs: schemaRef ? [schemaRef] : [],
2542
+ schemas: schema ? [schema] : []
2543
+ }
2544
+ });
2545
+ resolver.validationErrors.push(getNotAllowedInlineEnumError(schemaRef ? `${getSchemaNameByRef(schemaRef)}.${nameSegments[nameSegments.length - 1]}` : schemaInfo ?? nameSegments.join(".")));
2546
+ }
2547
+
2548
+ //#endregion
2549
+ //#region src/generators/core/zod/getZodSchemasFromOpenAPIDoc.ts
2550
+ function getZodSchemasFromOpenAPIDoc(resolver, profiler) {
2551
+ const p = profiler ?? new Profiler(false);
2552
+ const zodSchemas = {};
2553
+ const enumZodSchemas = {};
2554
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => p.runSync("zod.extract.schemaEntry", () => {
2555
+ const schemaData = resolver.getSchemaDataByName(name);
2556
+ if (resolver.options.excludeRedundantZodSchemas && (!schemaData || schemaData.deepRefOperations.length === 0 && schemaData.tags.length === 0)) return;
2557
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
2558
+ if (zodSchemas[zodSchemaName]) return;
2559
+ const tag = resolver.getTagByZodSchemaName(zodSchemaName);
2560
+ const schemaObject = resolver.resolveObject(schema);
2561
+ if (schemaObject.enum) enumZodSchemas[zodSchemaName] = getEnumZodSchemaCode(schemaObject);
2562
+ else zodSchemas[zodSchemaName] = p.runSync("zod.extract.schemaToCode", () => getZodSchema({
2563
+ schema,
2564
+ resolver,
2565
+ tag
2566
+ }).getCodeString(tag));
2567
+ }));
2568
+ return {
2569
+ zodSchemas,
2570
+ enumZodSchemas
2571
+ };
2572
+ }
2573
+ function getEnumZodSchemasFromOpenAPIDoc(resolver) {
2574
+ const enumZodSchemas = [];
2575
+ Object.entries(resolver.openApiDoc.components?.schemas ?? {}).forEach(([name, schema]) => {
2576
+ const zodSchemaName = getZodSchemaName(name, resolver.options.schemaSuffix);
2577
+ const schemaObject = resolver.resolveObject(schema);
2578
+ if (!enumZodSchemas.find((enumZodSchema) => enumZodSchema.zodSchemaName === zodSchemaName) && schemaObject.enum) enumZodSchemas.push({
2579
+ zodSchemaName,
2580
+ code: getEnumZodSchemaCode(schemaObject)
2581
+ });
2582
+ });
2583
+ return enumZodSchemas;
2584
+ }
2585
+
2586
+ //#endregion
2587
+ //#region src/generators/core/SchemaResolver.class.ts
2588
+ var SchemaResolver = class {
2589
+ schemaData = [];
2590
+ zodSchemaData = [];
2591
+ compositeZodSchemaData = [];
2592
+ schemaRefs;
2593
+ schemaByRef = /* @__PURE__ */ new Map();
2594
+ schemaDataByRef = /* @__PURE__ */ new Map();
2595
+ schemaDataByName = /* @__PURE__ */ new Map();
2596
+ refByZodSchemaName = /* @__PURE__ */ new Map();
2597
+ zodSchemaDataByName = /* @__PURE__ */ new Map();
2598
+ compositeByCode = /* @__PURE__ */ new Map();
2599
+ compositeSchemaByZodSchemaName = /* @__PURE__ */ new Map();
2600
+ dependencyGraph;
2601
+ enumZodSchemas = [];
2602
+ extractedEnumZodSchemaData = [];
2603
+ operationsByTag = {};
2604
+ operationNames = [];
2605
+ operationNameCounts = /* @__PURE__ */ new Map();
2606
+ operationContexts = [];
2607
+ validationErrors = [];
2608
+ get docSchemas() {
2609
+ return this.openApiDoc.components?.schemas ?? {};
2610
+ }
2611
+ constructor(openApiDoc, options, profiler) {
2612
+ this.openApiDoc = openApiDoc;
2613
+ this.options = options;
2614
+ this.profiler = profiler;
2615
+ this.schemaRefs = Object.keys(this.docSchemas).map(getSchemaRef);
2616
+ this.dependencyGraph = getOpenAPISchemaDependencyGraph(this.schemaRefs, this.getSchemaByRef.bind(this));
2617
+ this.enumZodSchemas = getEnumZodSchemasFromOpenAPIDoc(this);
2618
+ this.operationsByTag = getOperationsByTag(openApiDoc, options);
2619
+ this.operationNames = getUniqueOperationNamesWithoutSplitByTags(openApiDoc, this.operationsByTag, options);
2620
+ for (const name of this.operationNames) this.operationNameCounts.set(name, (this.operationNameCounts.get(name) ?? 0) + 1);
2621
+ this.initialize();
2622
+ }
2623
+ getSchemaByRef(ref) {
2624
+ const correctRef = autocorrectRef(ref);
2625
+ const cachedSchema = this.schemaByRef.get(correctRef);
2626
+ if (cachedSchema) return cachedSchema;
2627
+ const schema = this.docSchemas[getSchemaNameByRef(correctRef)];
2628
+ this.schemaByRef.set(correctRef, schema);
2629
+ return schema;
2630
+ }
2631
+ getSchemaDataByName(name) {
2632
+ return this.schemaDataByName.get(name);
2633
+ }
2634
+ getZodSchemaNameByRef(ref) {
2635
+ const zodSchemaName = this.getSchemaDataByRef(autocorrectRef(ref))?.zodSchemaName ?? this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === ref)?.zodSchemaName;
2636
+ if (!zodSchemaName) throw new Error(`Zod schema not found for ref: ${ref}`);
2637
+ return zodSchemaName;
2638
+ }
2639
+ getRefByZodSchemaName(zodSchemaName) {
2640
+ return this.refByZodSchemaName.get(zodSchemaName);
2641
+ }
2642
+ getTagByZodSchemaName(zodSchemaName) {
2643
+ if (!this.options.splitByTags) return this.options.defaultTag;
2644
+ const extractedEnumZodSchema = this.extractedEnumZodSchemaData.find((data) => data.zodSchemaName === zodSchemaName);
2645
+ if (extractedEnumZodSchema) return formatTag(extractedEnumZodSchema.tag ?? this.options.defaultTag);
2646
+ const schemaRef = this.getRefByZodSchemaName(zodSchemaName);
2647
+ const tags = getUniqueArray(schemaRef ? this.getSchemaDataByRef(schemaRef)?.tags ?? [] : [], this.zodSchemaDataByName.get(zodSchemaName)?.tags ?? []);
2648
+ return formatTag((tags.length === 1 ? tags[0] : this.options.defaultTag) ?? this.options.defaultTag);
2649
+ }
2650
+ getCodeByZodSchemaName(name) {
2651
+ return this.zodSchemaDataByName.get(name)?.code;
2652
+ }
2653
+ getZodSchemaNamesByCompositeCode(code) {
2654
+ return this.compositeByCode.get(code)?.zodSchemas.map((schema) => schema.zodSchemaName);
2655
+ }
2656
+ setZodSchema(name, code, tag) {
2657
+ const zodSchema = this.zodSchemaDataByName.get(name);
2658
+ if (zodSchema) {
2659
+ zodSchema.code = code;
2660
+ zodSchema.tags = (zodSchema.tags ?? []).concat(tag);
2661
+ } else {
2662
+ const newZodSchemaData = {
2663
+ zodSchemaName: name,
2664
+ code,
2665
+ tags: [tag]
2666
+ };
2667
+ this.zodSchemaData.push(newZodSchemaData);
2668
+ this.zodSchemaDataByName.set(name, newZodSchemaData);
2669
+ }
2670
+ }
2671
+ addZodSchemaForCompositeCode(code, zodSchema, zodSchemaName, schema) {
2672
+ const compositeZodSchema = {
2673
+ zodSchemaName,
2674
+ zodSchema,
2675
+ schema
2676
+ };
2677
+ const compositeData = this.compositeByCode.get(code);
2678
+ if (compositeData) compositeData.zodSchemas.push(compositeZodSchema);
2679
+ else {
2680
+ const newCompositeData = {
2681
+ code,
2682
+ zodSchemas: [compositeZodSchema]
2683
+ };
2684
+ this.compositeZodSchemaData.push(newCompositeData);
2685
+ this.compositeByCode.set(code, newCompositeData);
2686
+ }
2687
+ this.compositeSchemaByZodSchemaName.set(zodSchemaName, {
2688
+ zodSchema,
2689
+ schema
2690
+ });
2691
+ }
2692
+ getCompositeZodSchemaByZodSchemaName(zodSchemaName) {
2693
+ return this.compositeSchemaByZodSchemaName.get(zodSchemaName)?.zodSchema;
2694
+ }
2695
+ getSchemaByCompositeZodSchemaName(compositeZodSchemaName) {
2696
+ return this.compositeSchemaByZodSchemaName.get(compositeZodSchemaName)?.schema;
2697
+ }
2698
+ getEnumZodSchemaDataByCode(code) {
2699
+ return this.enumZodSchemas.find((data) => data.code === code);
2700
+ }
2701
+ getExtractedEnumZodSchemaDataByCode(code) {
2702
+ return this.extractedEnumZodSchemaData.find((data) => data.code === code);
2703
+ }
2704
+ getExtractedEnumZodSchemaNamesReferencedBySchemaRef(schemaRef) {
2705
+ return this.extractedEnumZodSchemaData.reduce((acc, { zodSchemaName, meta }) => {
2706
+ if (zodSchemaName && meta.schemaRefs.includes(schemaRef)) return [...acc, zodSchemaName];
2707
+ return acc;
2708
+ }, []);
2709
+ }
2710
+ getZodSchemas() {
2711
+ const zodSchemas = {};
2712
+ for (const { zodSchemaName, code } of this.zodSchemaData) zodSchemas[zodSchemaName] = code;
2713
+ return zodSchemas;
2714
+ }
2715
+ getExtractedEnumZodSchemas() {
2716
+ const zodSchemas = {};
2717
+ for (const { zodSchemaName, code } of this.extractedEnumZodSchemaData) if (zodSchemaName) zodSchemas[zodSchemaName] = code;
2718
+ return zodSchemas;
2719
+ }
2720
+ resolveObject(obj) {
2721
+ return isReferenceObject(obj) ? this.getSchemaByRef(obj.$ref) : obj;
2722
+ }
2723
+ isSchemaCircular(ref) {
2724
+ return this.dependencyGraph.deepDependencyGraph[ref]?.has(ref);
2725
+ }
2726
+ getCircularSchemaChain(ref, currentRef = ref, chain = [], visited = []) {
2727
+ if (visited.includes(currentRef)) return [];
2728
+ visited.push(currentRef);
2729
+ if (this.dependencyGraph.refsDependencyGraph[currentRef]?.has(ref)) return [
2730
+ ...chain,
2731
+ currentRef,
2732
+ ref
2733
+ ];
2734
+ return Array.from(this.dependencyGraph.refsDependencyGraph[currentRef]?.values() ?? []).flatMap((childRef) => {
2735
+ const childChain = this.getCircularSchemaChain(ref, childRef, chain, visited);
2736
+ return childChain.length > 0 ? [currentRef, ...childChain] : childChain;
2737
+ });
2738
+ }
2739
+ getBaseUrl() {
2740
+ const serverUrl = this.openApiDoc.servers?.[0]?.url;
2741
+ if (this.options.baseUrl === "" && serverUrl) return serverUrl;
2742
+ return this.options.baseUrl;
2743
+ }
2744
+ isOperationNameUnique(operationName) {
2745
+ return (this.operationNameCounts.get(operationName) ?? 0) <= 1;
2746
+ }
2747
+ getOperationContexts() {
2748
+ return this.operationContexts;
2749
+ }
2750
+ getZodSchemaObj(zodSchemaName) {
2751
+ const ref = this.getRefByZodSchemaName(zodSchemaName);
2752
+ if (ref) return this.getSchemaByRef(ref);
2753
+ const schema = this.getSchemaByCompositeZodSchemaName(zodSchemaName);
2754
+ if (schema) return schema;
2755
+ const enumZodSchemaData = this.getExtractedEnumZodSchemaDataByName(zodSchemaName);
2756
+ if (enumZodSchemaData) {
2757
+ const schemaObject = {};
2758
+ for (const schema of enumZodSchemaData.meta.schemas) Object.assign(schemaObject, this.resolveObject(schema));
2759
+ return schemaObject;
2760
+ }
2761
+ }
2762
+ getSchemaDataByRef(ref) {
2763
+ return this.schemaDataByRef.get(ref);
2764
+ }
2765
+ getExtractedEnumZodSchemaDataByName(enumZodSchemaName) {
2766
+ return this.extractedEnumZodSchemaData.find(({ zodSchemaName }) => zodSchemaName === enumZodSchemaName);
2767
+ }
2768
+ initialize() {
2769
+ const p = this.profiler ?? new Profiler(false);
2770
+ p.runSync("resolver.init.seedSchemas", () => {
2771
+ this.schemaRefs.forEach((ref) => {
2772
+ const correctRef = autocorrectRef(ref);
2773
+ const name = getSchemaNameByRef(correctRef);
2774
+ const zodSchemaName = getZodSchemaName(name, this.options.schemaSuffix);
2775
+ const data = {
2776
+ ref: correctRef,
2777
+ name,
2778
+ zodSchemaName,
2779
+ tags: [],
2780
+ deepRefOperations: []
2781
+ };
2782
+ this.schemaData.push(data);
2783
+ this.schemaDataByRef.set(correctRef, data);
2784
+ this.schemaDataByName.set(name, data);
2785
+ this.refByZodSchemaName.set(zodSchemaName, correctRef);
2786
+ });
2787
+ });
2788
+ p.runSync("resolver.init.operationsLoop", () => {
2789
+ for (const path in this.openApiDoc.paths) {
2790
+ if (isPathExcluded(path, this.options)) continue;
2791
+ const pathItemObj = this.openApiDoc.paths[path];
2792
+ const pathParameters = this.getParameters(pathItemObj.parameters ?? []);
2793
+ const pathItem = pick(pathItemObj, ALLOWED_METHODS);
2794
+ for (const method in pathItem) {
2795
+ const operation = pathItem[method];
2796
+ if (!operation || isOperationExcluded(operation, this.options)) continue;
2797
+ const tag = getOperationTag(operation, this.options);
2798
+ const operationName = getUniqueOperationName({
2799
+ path,
2800
+ method,
2801
+ operation,
2802
+ operationsByTag: this.operationsByTag,
2803
+ options: this.options
2804
+ });
2805
+ const isUniqueOperationName = this.isOperationNameUnique(operationName);
2806
+ const parameters = p.runSync("resolver.init.parameters.mergeResolve", () => Object.entries({
2807
+ ...pathParameters,
2808
+ ...this.getParameters(operation.parameters ?? [])
2809
+ }).map(([, param]) => this.resolveObject(param)));
2810
+ const responses = p.runSync("resolver.init.responses.prepare", () => Object.entries(operation.responses).map(([statusCode, response]) => {
2811
+ const responseObj = this.resolveObject(response);
2812
+ const matchingMediaType = Object.keys(responseObj?.content ?? {}).find(isMediaTypeAllowed);
2813
+ return {
2814
+ statusCode,
2815
+ responseObj,
2816
+ matchingMediaType,
2817
+ schema: matchingMediaType ? responseObj.content?.[matchingMediaType]?.schema : void 0
2818
+ };
2819
+ }));
2820
+ const zodSchemaOperationName = snakeToCamel(getZodSchemaOperationName(operationName, isUniqueOperationName, tag));
2821
+ const schemaRefObjs = [];
2822
+ p.runSync("resolver.init.parameters.refs", () => {
2823
+ parameters.forEach((parameter) => {
2824
+ const parameterObject = this.resolveObject(parameter);
2825
+ const parameterSchema = parameterObject.schema;
2826
+ const schemaInfo = `Operation ${operation.operationId ?? path} parameter ${parameterObject.name}`;
2827
+ schemaRefObjs.push(...getSchemaRefObjs(this, parameterSchema, schemaInfo));
2828
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2829
+ resolver: this,
2830
+ schema: parameterSchema,
2831
+ schemaInfo,
2832
+ tags: [tag],
2833
+ nameSegments: [zodSchemaOperationName, parameterObject.name],
2834
+ includeSelf: true
2835
+ });
2836
+ });
2837
+ });
2838
+ p.runSync("resolver.init.requestBody.refs", () => {
2839
+ if (operation.requestBody) {
2840
+ const requestBodyObj = this.resolveObject(operation.requestBody);
2841
+ const matchingMediaType = Object.keys(requestBodyObj.content ?? {}).find(isParamMediaTypeAllowed);
2842
+ if (matchingMediaType) {
2843
+ const matchingMediaSchema = requestBodyObj.content?.[matchingMediaType]?.schema;
2844
+ const schemaInfo = `Operation ${operation.operationId} request body`;
2845
+ schemaRefObjs.push(...getSchemaRefObjs(this, matchingMediaSchema, schemaInfo));
2846
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2847
+ resolver: this,
2848
+ schema: matchingMediaSchema,
2849
+ schemaInfo,
2850
+ tags: [tag],
2851
+ nameSegments: [getBodyZodSchemaName(zodSchemaOperationName)]
2852
+ });
2853
+ }
2854
+ }
2855
+ });
2856
+ p.runSync("resolver.init.responses.refs", () => {
2857
+ for (const responseData of responses) {
2858
+ if (!responseData.matchingMediaType) continue;
2859
+ const schemaInfo = `Operation ${operation.operationId} response body`;
2860
+ schemaRefObjs.push(...getSchemaRefObjs(this, responseData.schema, schemaInfo));
2861
+ if (this.options.extractEnums) updateExtractedEnumZodSchemaData({
2862
+ resolver: this,
2863
+ schema: responseData.schema,
2864
+ schemaInfo,
2865
+ tags: [tag],
2866
+ nameSegments: [getResponseZodSchemaName({
2867
+ statusCode: responseData.statusCode,
2868
+ operationName,
2869
+ isUniqueOperationName,
2870
+ tag
2871
+ })]
2872
+ });
2873
+ }
2874
+ });
2875
+ const deepRefs = p.runSync("resolver.init.deepRefs", () => getDeepSchemaRefObjs(this, schemaRefObjs));
2876
+ const operationContext = {
2877
+ path,
2878
+ method,
2879
+ operation,
2880
+ tag,
2881
+ operationName,
2882
+ isUniqueOperationName,
2883
+ parameters,
2884
+ deepRefs,
2885
+ responses
2886
+ };
2887
+ this.operationContexts.push(operationContext);
2888
+ deepRefs.forEach((schemaRef) => {
2889
+ const schemaData = this.getSchemaDataByRef(schemaRef);
2890
+ if (schemaData) {
2891
+ schemaData.tags.push(tag);
2892
+ schemaData.deepRefOperations.push(operation);
2893
+ }
2894
+ });
2895
+ }
2896
+ }
2897
+ });
2898
+ if (this.options.extractEnums) p.runSync("resolver.init.enums.finalize", () => {
2899
+ this.schemaRefs.forEach((ref) => {
2900
+ const schemaRef = autocorrectRef(ref);
2901
+ updateExtractedEnumZodSchemaData({
2902
+ resolver: this,
2903
+ schema: this.getSchemaByRef(schemaRef),
2904
+ schemaRef,
2905
+ tags: this.getSchemaDataByRef(schemaRef)?.tags ?? [],
2906
+ nameSegments: [getSchemaNameByRef(schemaRef)]
2907
+ });
2908
+ });
2909
+ resolveExtractedEnumZodSchemaTags(this);
2910
+ this.handleDuplicateEnumZodSchemas();
2911
+ resolveExtractedEnumZodSchemaNames(this);
2912
+ });
2913
+ }
2914
+ handleDuplicateEnumZodSchemas() {
2915
+ const codes = new Set(this.enumZodSchemas.map(({ code }) => code));
2916
+ const duplicates = this.enumZodSchemas.filter(({ code }) => codes.has(code));
2917
+ this.schemaData.forEach((schemaData) => {
2918
+ const duplicateCode = duplicates.find(({ zodSchemaName }) => zodSchemaName === schemaData.zodSchemaName)?.code;
2919
+ if (!duplicateCode) return;
2920
+ const duplicate = this.extractedEnumZodSchemaData.find(({ code }) => code === duplicateCode);
2921
+ if (!duplicate || this.getEnumZodSchemaDataByCode(duplicate.code)?.zodSchemaName !== schemaData.zodSchemaName) return;
2922
+ schemaData.tags.push(...duplicate.meta.tags ?? []);
2923
+ duplicate.meta.schemaRefs.forEach((ref) => {
2924
+ if (!this.dependencyGraph.refsDependencyGraph[ref]) this.dependencyGraph.refsDependencyGraph[ref] = /* @__PURE__ */ new Set();
2925
+ this.dependencyGraph.refsDependencyGraph[ref].add(schemaData.ref);
2926
+ if (!this.dependencyGraph.deepDependencyGraph[ref]) this.dependencyGraph.deepDependencyGraph[ref] = /* @__PURE__ */ new Set();
2927
+ this.dependencyGraph.deepDependencyGraph[ref].add(schemaData.ref);
2928
+ });
2929
+ });
2930
+ this.extractedEnumZodSchemaData.splice(0, this.extractedEnumZodSchemaData.length, ...this.extractedEnumZodSchemaData.filter(({ code }) => !codes.has(code)));
2931
+ }
2932
+ getParameters(parameters) {
2933
+ return Object.fromEntries((parameters ?? []).map((param) => [isReferenceObject(param) ? param.$ref : param.name, param]));
2934
+ }
2935
+ };
2936
+
2937
+ //#endregion
2938
+ //#region src/generators/utils/sort.utils.ts
2939
+ /** @see https://gist.github.com/RubyTuesdayDONO/5006455 */
2940
+ function topologicalSort(graph) {
2941
+ const sorted = [];
2942
+ const visited = {};
2943
+ function visit(name, ancestors) {
2944
+ if (!Array.isArray(ancestors)) ancestors = [];
2945
+ ancestors.push(name);
2946
+ visited[name] = true;
2947
+ if (graph[name]) graph[name].forEach((dep) => {
2948
+ if (ancestors.includes(dep)) return;
2949
+ if (visited[dep]) return;
2950
+ visit(dep, ancestors.slice(0));
2951
+ });
2952
+ if (!sorted.includes(name)) sorted.push(name);
2953
+ }
2954
+ Object.keys(graph).forEach((name) => visit(name, []));
2955
+ return sorted;
2956
+ }
2957
+ /** Sort object keys using a reference order array, sort keys not in reference order in lasts positions */
2958
+ function sortObjKeysFromArray(obj, orderedKeys) {
2959
+ const entries = Object.entries(obj);
2960
+ const sortedEntries = entries.filter(([key]) => orderedKeys.includes(key)).toSorted(([a], [b]) => orderedKeys.indexOf(a) - orderedKeys.indexOf(b)).concat(entries.filter(([key]) => !orderedKeys.includes(key)));
2961
+ return Object.fromEntries(sortedEntries);
2962
+ }
2963
+
2964
+ //#endregion
2965
+ //#region src/generators/core/zod/sortZodSchemasByTopology.ts
2966
+ function sortZodSchemasByTopology(resolver, zodSchemas) {
2967
+ return sortObjKeysFromArray(zodSchemas, topologicalSort(resolver.dependencyGraph.deepDependencyGraph).map((ref) => resolver.getZodSchemaNameByRef(ref)));
2968
+ }
2969
+
2970
+ //#endregion
2971
+ //#region src/generators/core/getDataFromOpenAPIDoc.ts
2972
+ function getDataFromOpenAPIDoc(openApiDoc, options, profiler) {
2973
+ const p = profiler ?? new Profiler(false);
2974
+ const resolver = p.runSync("data.resolver.init", () => new SchemaResolver(openApiDoc, options, p));
2975
+ const endpoints = p.runSync("data.endpoints.extract", () => getEndpointsFromOpenAPIDoc(resolver, p));
2976
+ const zodSchemasFromDocSchemas = p.runSync("data.zod.extract", () => getZodSchemasFromOpenAPIDoc(resolver, p));
2977
+ let zodSchemas = {
2978
+ ...zodSchemasFromDocSchemas.zodSchemas,
2979
+ ...resolver.getZodSchemas(),
2980
+ ...zodSchemasFromDocSchemas.enumZodSchemas
2981
+ };
2982
+ zodSchemas = p.runSync("data.zod.sortTopology", () => sortZodSchemasByTopology(resolver, zodSchemas));
2983
+ zodSchemas = {
2984
+ ...resolver.getExtractedEnumZodSchemas(),
2985
+ ...zodSchemas
2986
+ };
2987
+ return {
2988
+ resolver,
2989
+ data: p.runSync("data.splitByTags", () => splitDataByTags({
2990
+ resolver,
2991
+ endpoints,
2992
+ zodSchemas,
2993
+ options
2994
+ }))
2995
+ };
2996
+ }
2997
+ function splitDataByTags({ resolver, endpoints, zodSchemas, options }) {
2998
+ const data = /* @__PURE__ */ new Map();
2999
+ if (!options.splitByTags) {
3000
+ data.set(options.defaultTag, {
3001
+ endpoints,
3002
+ zodSchemas
3003
+ });
3004
+ return data;
3005
+ }
3006
+ endpoints.forEach((endpoint) => {
3007
+ getTagElement(getEndpointTag(endpoint, options), data).endpoints.push(endpoint);
3008
+ });
3009
+ Object.entries(zodSchemas).forEach(([zodSchemaName, zodSchemaCode]) => {
3010
+ const tag = options.modelsInCommon ? options.defaultTag : resolver.getTagByZodSchemaName(zodSchemaName);
3011
+ if (tag) getTagElement(tag, data).zodSchemas[zodSchemaName] = zodSchemaCode;
3012
+ });
3013
+ return data;
3014
+ }
3015
+ function getTagElement(tag, data) {
3016
+ if (!data.has(tag)) data.set(tag, {
3017
+ endpoints: [],
3018
+ zodSchemas: {}
3019
+ });
3020
+ return data.get(tag);
3021
+ }
3022
+
3023
+ //#endregion
3024
+ //#region src/generators/utils/file.utils.ts
3025
+ function getOutputFileName({ output, fileName }) {
3026
+ return `${output}/${fileName}`;
3027
+ }
3028
+ function writeFileWithDirSync(file, data) {
3029
+ const dir = path.dirname(file);
3030
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
3031
+ if (fs.existsSync(file)) {
3032
+ if (fs.readFileSync(file, "utf-8") === data) return;
3033
+ }
3034
+ fs.writeFileSync(file, data, "utf-8");
3035
+ }
3036
+ function writeFileSync$1({ fileName, content }) {
3037
+ writeFileWithDirSync(fileName, content);
3038
+ }
3039
+ function writeGenerateFileData(filesData) {
3040
+ filesData.forEach(writeFileSync$1);
3041
+ }
3042
+
3043
+ //#endregion
3044
+ //#region src/generators/generate/generateAcl.ts
3045
+ function generateAcl({ resolver, data, tag }) {
3046
+ const aclData = getAclData({
3047
+ resolver,
3048
+ data,
3049
+ tag
3050
+ });
3051
+ if (!aclData) return;
3052
+ const { hasAdditionalAbilityImports, modelsImports, endpoints } = aclData;
3053
+ const caslAbilityTupleImport = {
3054
+ bindings: [CASL_ABILITY_BINDING.abilityTuple, ...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject, CASL_ABILITY_BINDING.subject] : []],
3055
+ from: CASL_ABILITY_IMPORT.from
3056
+ };
3057
+ const lines = [];
3058
+ lines.push(renderImport$4(caslAbilityTupleImport));
3059
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3060
+ lines.push("");
3061
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3062
+ type: GenerateType.Acl,
3063
+ tag,
3064
+ options: resolver.options
3065
+ })} {`);
3066
+ for (const endpoint of endpoints) {
3067
+ lines.push(renderAbilityFunction(endpoint));
3068
+ lines.push("");
3069
+ }
3070
+ if (resolver.options.tsNamespaces) lines.push("}");
3071
+ return lines.join("\n").trimEnd() + "\n";
3072
+ }
3073
+ function generateAppAcl({ resolver, data }) {
3074
+ const { appAbilitiesType, hasAdditionalAbilityImports, modelsImports } = getAppAbilitiesType({
3075
+ resolver,
3076
+ data
3077
+ });
3078
+ const caslAbilityTupleImport = {
3079
+ bindings: [
3080
+ CASL_ABILITY_BINDING.pureAbility,
3081
+ CASL_ABILITY_BINDING.abilityTuple,
3082
+ ...!appAbilitiesType ? [CASL_ABILITY_BINDING.subjectType] : [],
3083
+ ...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject] : []
3084
+ ],
3085
+ from: CASL_ABILITY_IMPORT.from
3086
+ };
3087
+ const lines = [];
3088
+ lines.push(renderImport$4(caslAbilityTupleImport));
3089
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
3090
+ lines.push("");
3091
+ if (appAbilitiesType) {
3092
+ lines.push(`export type ${ACL_APP_ABILITIES} = `);
3093
+ for (const [action, subjects] of Object.entries(appAbilitiesType)) lines.push(`| ${CASL_ABILITY_BINDING.abilityTuple}<"${action}", ${subjects.join(" | ")}>`);
3094
+ } else lines.push(`export type ${ACL_APP_ABILITIES} = ${CASL_ABILITY_BINDING.abilityTuple}<string, ${CASL_ABILITY_BINDING.subjectType}>;`);
3095
+ lines.push("");
3096
+ lines.push(`export type AppAbility = PureAbility<${ACL_APP_ABILITIES}>;`);
3097
+ return lines.join("\n");
3098
+ }
3099
+ function renderImport$4(importData) {
3100
+ return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3101
+ }
3102
+ function renderAbilityFunction(endpoint) {
3103
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
3104
+ const hasConditions = hasAbilityConditions(endpoint);
3105
+ const lines = [];
3106
+ const abilityQuery = endpoint.method === "get" ? endpoint.mediaDownload ? `\`${getQueryName(endpoint)}\` query or \`${getQueryName(endpoint, true)}\` mutation` : `\`${getQueryName(endpoint)}\` query` : `\`${getQueryName(endpoint)}\` mutation`;
3107
+ lines.push("/**");
3108
+ lines.push(` * Use for ${abilityQuery} ability. ${hasConditions ? "For global ability, omit the object parameter." : ""}${getAbilityDescription(endpoint) ? "" : ""}`);
3109
+ if (getAbilityDescription(endpoint)) lines.push(` * @description ${getAbilityDescription(endpoint)}`);
3110
+ if (hasConditions) for (const propertyType of abilityConditionsTypes) lines.push(` * @param { ${(propertyType.type ?? "") + (propertyType.zodSchemaName ?? "")} } object.${propertyType.name} ${propertyType.name} from ${propertyType.info}`);
3111
+ lines.push(` * @returns { AbilityTuple } An ability tuple indicating the user's ability to use ${abilityQuery}`);
3112
+ lines.push(" */");
3113
+ lines.push(`export const ${getAbilityFunctionName(endpoint)} = (`);
3114
+ if (hasConditions) lines.push(` object?: { ${abilityConditionsTypes.map((propertyType) => `${propertyType.name}${propertyType.required ? "" : "?"}: ${(propertyType.type ?? "") + (propertyType.zodSchemaName ?? "")}, `).join("")} } `);
3115
+ lines.push(") => [");
3116
+ lines.push(` "${getAbilityAction(endpoint)}",`);
3117
+ lines.push(` ${hasConditions ? `object ? subject("${getAbilitySubject(endpoint)}", object) : "${getAbilitySubject(endpoint)}"` : `"${getAbilitySubject(endpoint)}"`}`);
3118
+ lines.push(`] as ${CASL_ABILITY_BINDING.abilityTuple}<"${getAbilityAction(endpoint)}", ${getAbilitySubjectTypes(endpoint).join(" | ")}>;`);
3119
+ return lines.join("\n");
3120
+ }
3121
+
3122
+ //#endregion
3123
+ //#region src/generators/const/buildConfigs.const.ts
3124
+ const BUILD_CONFIG_SUFFIX = "config";
3125
+
3126
+ //#endregion
3127
+ //#region src/generators/utils/generate/generate.configs.utils.ts
3128
+ function getBuilderConfigs({ data, tag, resolver }) {
3129
+ const endpoints = data.get(tag)?.endpoints;
3130
+ if (!endpoints || endpoints.length === 0) return {
3131
+ configs: [],
3132
+ hasZodImport: false,
3133
+ modelsImports: [],
3134
+ queriesImports: [],
3135
+ aclImports: []
3136
+ };
3137
+ const extendedEndpoints = endpoints.map((endpoint) => ({
3138
+ ...endpoint,
3139
+ pathSegments: getPathSegments(endpoint.path)
3140
+ }));
3141
+ const namedReadAllEndpoints = resolveBuilderConfigNames(extendedEndpoints.filter((endpoint) => isReadAllEndpoint(endpoint, resolver.options)));
3142
+ let hasZodImport = false;
3143
+ const importedZodSchemas = [];
3144
+ const importedEndpoints = [];
3145
+ const importedInfiniteEndpoints = [];
3146
+ const configs = Object.entries(namedReadAllEndpoints).map(([name, readAllEndpoint]) => {
3147
+ const columnsConfig = getColumnsConfig(resolver, readAllEndpoint);
3148
+ if (!columnsConfig) return;
3149
+ importedEndpoints.push(readAllEndpoint);
3150
+ importedInfiniteEndpoints.push(readAllEndpoint);
3151
+ if (columnsConfig.zodSchema) if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
3152
+ else hasZodImport = true;
3153
+ if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
3154
+ const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
3155
+ if (filter) importedZodSchemas.push(filter.zodSchema);
3156
+ const config = {
3157
+ name,
3158
+ title: capitalize(camelToSpaceSeparated(name.replace(/config$/i, ""))),
3159
+ readAll: {
3160
+ acl: getAclConfig(readAllEndpoint, resolver.options),
3161
+ paginated: getImportedQueryName(readAllEndpoint, resolver.options),
3162
+ infinite: resolver.options.infiniteQueries ? getImportedInfiniteQueryName(readAllEndpoint, resolver.options) : void 0,
3163
+ filters: getInputsConfig(resolver, filter),
3164
+ columns: columnsConfig.columns
3165
+ }
3166
+ };
3167
+ const readEndpoint = extendedEndpoints.find((endpoint) => isReadEndpoint(endpoint, readAllEndpoint));
3168
+ if (readEndpoint) {
3169
+ importedEndpoints.push(readEndpoint);
3170
+ let responseSchema = readEndpoint.response;
3171
+ if (isNamedZodSchema(responseSchema)) {
3172
+ importedZodSchemas.push(responseSchema);
3173
+ responseSchema = getImportedZodSchemaName(resolver, responseSchema);
3174
+ } else hasZodImport = true;
3175
+ config.read = {
3176
+ acl: getAclConfig(readEndpoint, resolver.options),
3177
+ schema: responseSchema,
3178
+ query: getImportedQueryName(readEndpoint, resolver.options)
3179
+ };
3180
+ }
3181
+ const createEndpoint = extendedEndpoints.find((endpoint) => isCreateEndpoint(endpoint, readAllEndpoint));
3182
+ if (createEndpoint) {
3183
+ importedEndpoints.push(createEndpoint);
3184
+ const body = getEndpointBody$1(createEndpoint);
3185
+ if (body) importedZodSchemas.push(body.zodSchema);
3186
+ config.create = {
3187
+ acl: getAclConfig(createEndpoint, resolver.options),
3188
+ mutation: getImportedQueryName(createEndpoint, resolver.options),
3189
+ inputDefs: getInputsConfig(resolver, body)
3190
+ };
3191
+ }
3192
+ const updateEndpoint = extendedEndpoints.find((endpoint) => isUpdateEndpoint(endpoint, readAllEndpoint));
3193
+ if (updateEndpoint) {
3194
+ importedEndpoints.push(updateEndpoint);
3195
+ const body = getEndpointBody$1(updateEndpoint);
3196
+ if (body) importedZodSchemas.push(body.zodSchema);
3197
+ config.update = {
3198
+ acl: getAclConfig(updateEndpoint, resolver.options),
3199
+ mutation: getImportedQueryName(updateEndpoint, resolver.options),
3200
+ inputDefs: getInputsConfig(resolver, body)
3201
+ };
3202
+ }
3203
+ const deleteEndpoint = extendedEndpoints.find((endpoint) => isDeleteEndpoint(endpoint, readAllEndpoint));
3204
+ if (deleteEndpoint) {
3205
+ importedEndpoints.push(deleteEndpoint);
3206
+ config.delete = {
3207
+ acl: getAclConfig(deleteEndpoint, resolver.options),
3208
+ mutation: getImportedQueryName(deleteEndpoint, resolver.options)
3209
+ };
3210
+ }
3211
+ const bulkDeleteEndpoint = extendedEndpoints.find((endpoint) => isBulkDeleteEndpoint(endpoint, readAllEndpoint));
3212
+ if (bulkDeleteEndpoint) {
3213
+ importedEndpoints.push(bulkDeleteEndpoint);
3214
+ const body = getEndpointBody$1(bulkDeleteEndpoint);
3215
+ if (body) importedZodSchemas.push(body.zodSchema);
3216
+ config.bulkDelete = {
3217
+ acl: getAclConfig(bulkDeleteEndpoint, resolver.options),
3218
+ mutation: getImportedQueryName(bulkDeleteEndpoint, resolver.options),
3219
+ inputDefs: getInputsConfig(resolver, body)
3220
+ };
3221
+ }
3222
+ return config;
3223
+ });
3224
+ const modelsImports = getModelsImports({
3225
+ resolver,
3226
+ tag,
3227
+ zodSchemas: importedZodSchemas
3228
+ });
3229
+ const queriesImports = getQueriesImports({
3230
+ tag,
3231
+ endpoints: importedEndpoints,
3232
+ options: resolver.options
3233
+ });
3234
+ const infiniteQueriesImports = resolver.options.infiniteQueries ? getInfiniteQueriesImports({
3235
+ tag,
3236
+ endpoints: importedInfiniteEndpoints,
3237
+ options: resolver.options
3238
+ }) : [];
3239
+ const aclImports = getAclImports({
3240
+ tag,
3241
+ endpoints: importedEndpoints.filter((endpoint) => endpoint.acl),
3242
+ options: resolver.options
3243
+ });
3244
+ return {
3245
+ configs: configs.filter(Boolean),
3246
+ hasZodImport,
3247
+ modelsImports,
3248
+ queriesImports: mergeImports(resolver.options, queriesImports, infiniteQueriesImports),
3249
+ aclImports
3250
+ };
3251
+ }
3252
+ function resolveBuilderConfigNames(endpoints) {
3253
+ const sortedEndpoints = endpoints.map((endpoint) => ({
3254
+ ...endpoint,
3255
+ namePathSegments: endpoint.pathSegments.filter((segment) => !isPathSegmentParam(segment))
3256
+ })).toSorted((a, b) => a.namePathSegments.length - b.namePathSegments.length);
3257
+ const namedEndpoints = {};
3258
+ for (const endpoint of sortedEndpoints) {
3259
+ const namePathSegments = endpoint.namePathSegments;
3260
+ let name = namePathSegments.length > 0 ? `${kebabToCamel(namePathSegments.pop())}${capitalize(BUILD_CONFIG_SUFFIX)}` : BUILD_CONFIG_SUFFIX;
3261
+ while (namedEndpoints[name]) {
3262
+ if (namePathSegments.length === 0) throw new Error(`Can't uniquely resolve builder config name: ${name}`);
3263
+ name = `${kebabToCamel(namePathSegments.pop())}${capitalize(name)}`;
3264
+ }
3265
+ namedEndpoints[name] = endpoint;
3266
+ }
3267
+ return namedEndpoints;
3268
+ }
3269
+ function getAclConfig(endpoint, options) {
3270
+ return options.acl && endpoint.acl ? getImportedAbilityFunctionName(endpoint, options) : void 0;
3271
+ }
3272
+ function getInputsConfig(resolver, endpointParameter) {
3273
+ if (!endpointParameter) return;
3274
+ let schema;
3275
+ if (endpointParameter.type === "Body") schema = endpointParameter.bodyObject?.content?.[JSON_APPLICATION_FORMAT]?.schema;
3276
+ else schema = endpointParameter.parameterObject?.schema;
3277
+ if (!schema) return;
3278
+ const schemaObj = resolver.resolveObject(schema);
3279
+ const inputs = Object.keys(schemaObj?.properties ?? {}).reduce((acc, key) => ({
3280
+ ...acc,
3281
+ [key]: true
3282
+ }), {});
3283
+ return {
3284
+ schema: getImportedZodSchemaName(resolver, endpointParameter.zodSchema),
3285
+ options: { inputs }
3286
+ };
3287
+ }
3288
+ function getColumnsConfig(resolver, endpoint) {
3289
+ const endpointResponse = endpoint.responseObject;
3290
+ if (!endpointResponse) return;
3291
+ const schema = endpointResponse.content?.[JSON_APPLICATION_FORMAT]?.schema;
3292
+ if (!schema) return;
3293
+ const properties = getSchemaProperties(resolver, schema);
3294
+ const arrayPropertyKeys = Object.keys(properties).filter((key) => resolver.resolveObject(properties[key]).type === "array");
3295
+ arrayPropertyKeys.sort((a, b) => {
3296
+ const aIndex = resolver.options.dataResponseParamNames.indexOf(a);
3297
+ const bIndex = resolver.options.dataResponseParamNames.indexOf(b);
3298
+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
3299
+ if (aIndex !== -1) return -1;
3300
+ if (bIndex !== -1) return 1;
3301
+ return a.localeCompare(b);
3302
+ });
3303
+ const propertyKey = arrayPropertyKeys[0];
3304
+ if (!propertyKey) return;
3305
+ const dataSchemaObj = resolver.resolveObject(properties[propertyKey]);
3306
+ if (!dataSchemaObj || dataSchemaObj.type !== "array") return;
3307
+ const itemSchema = dataSchemaObj.items;
3308
+ const itemSchemaObj = resolver.resolveObject(itemSchema);
3309
+ if (!itemSchemaObj) return;
3310
+ const zodSchema = isReferenceObject(itemSchema) ? resolver.getZodSchemaNameByRef(itemSchema.$ref) : ANY_SCHEMA;
3311
+ const columns = Object.keys(itemSchemaObj?.properties ?? {}).reduce((acc, key) => ({
3312
+ ...acc,
3313
+ [key]: true
3314
+ }), {});
3315
+ const sortableEnumSchemaName = endpoint.parameters.find((param) => param.parameterObject && isSortingParameterObject(param.parameterObject))?.parameterSortingEnumSchemaName;
3316
+ return {
3317
+ columns: {
3318
+ schema: getImportedZodSchemaName(resolver, zodSchema),
3319
+ options: {
3320
+ columns,
3321
+ sortable: sortableEnumSchemaName ? getImportedZodSchemaName(resolver, sortableEnumSchemaName) : void 0
3322
+ }
3323
+ },
3324
+ zodSchema,
3325
+ sortableEnumSchemaName
3326
+ };
3327
+ }
3328
+ function getSchemaProperties(resolver, schema) {
3329
+ const schemaObj = resolver.resolveObject(schema);
3330
+ if (schemaObj.properties) return schemaObj.properties;
3331
+ else if ("allOf" in schemaObj && schemaObj.allOf) return schemaObj.allOf.reduce((acc, cur) => ({
3332
+ ...acc,
3333
+ ...getSchemaProperties(resolver, cur)
3334
+ }), {});
3335
+ return {};
3336
+ }
3337
+
3338
+ //#endregion
3339
+ //#region src/generators/generate/generateConfigs.ts
3340
+ function generateConfigs(generateTypeParams) {
3341
+ const { configs, hasZodImport, modelsImports, queriesImports, aclImports } = getBuilderConfigs(generateTypeParams);
3342
+ if (configs.length === 0) return;
3343
+ const { resolver, tag } = generateTypeParams;
3344
+ const hasDynamicInputsImport = configs.some((config) => config.readAll.filters || config.create?.inputDefs || config.update?.inputDefs);
3345
+ const dynamicInputsImport = {
3346
+ bindings: [BUILDERS_UTILS.dynamicInputs],
3347
+ from: resolver.options.dynamicInputsImportPath
3348
+ };
3349
+ const hasDynamicColumnsImport = configs.some((config) => config.readAll.columns);
3350
+ const dynamicColumnsImport = {
3351
+ bindings: [BUILDERS_UTILS.dynamicColumns],
3352
+ from: resolver.options.dynamicColumnsImportPath
3353
+ };
3354
+ const lines = [];
3355
+ if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
3356
+ if (hasDynamicInputsImport) lines.push(renderImport$3(dynamicInputsImport));
3357
+ if (hasDynamicColumnsImport) lines.push(renderImport$3(dynamicColumnsImport));
3358
+ for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
3359
+ for (const queriesImport of queriesImports) lines.push(renderImport$3(queriesImport));
3360
+ for (const aclImport of aclImports) lines.push(renderImport$3(aclImport));
3361
+ lines.push("");
3362
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3363
+ type: GenerateType.Configs,
3364
+ tag,
3365
+ options: resolver.options
3366
+ })} {`);
3367
+ for (const config of configs) {
3368
+ lines.push(renderBuilderConfig(config));
3369
+ lines.push("");
3370
+ }
3371
+ if (resolver.options.tsNamespaces) lines.push("}");
3372
+ return lines.join("\n").trimEnd() + "\n";
3373
+ }
3374
+ function renderImport$3(importData) {
3375
+ return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3376
+ }
3377
+ function renderInputsConfig(inputsConfig) {
3378
+ const lines = [];
3379
+ lines.push("{");
3380
+ lines.push(` schema: ${inputsConfig.schema},`);
3381
+ lines.push(" options: {");
3382
+ lines.push(" inputs: {");
3383
+ for (const key of Object.keys(inputsConfig.options.inputs)) lines.push(` ${key}: true,`);
3384
+ lines.push(" },");
3385
+ lines.push(" },");
3386
+ lines.push("}");
3387
+ return lines.join("\n");
3388
+ }
3389
+ function renderColumnsConfig(columnsConfig) {
3390
+ const lines = [];
3391
+ lines.push("{");
3392
+ lines.push(` schema: ${columnsConfig.schema},`);
3393
+ lines.push(" options: {");
3394
+ lines.push(" columns: {");
3395
+ for (const key of Object.keys(columnsConfig.options.columns)) lines.push(` ${key}: true,`);
3396
+ lines.push(" },");
3397
+ if (columnsConfig.options.sortable) lines.push(` sortable: ${columnsConfig.options.sortable},`);
3398
+ lines.push(" },");
3399
+ lines.push("}");
3400
+ return lines.join("\n");
3401
+ }
3402
+ function renderBuilderConfig(config) {
3403
+ const lines = [];
3404
+ lines.push(`export const ${config.name} = {`);
3405
+ lines.push(" meta: {");
3406
+ lines.push(` title: "${config.title}",`);
3407
+ lines.push(" },");
3408
+ lines.push(" readAll: {");
3409
+ if (config.readAll.acl) lines.push(` acl: ${config.readAll.acl},`);
3410
+ lines.push(` schema: ${config.readAll.columns.schema},`);
3411
+ lines.push(` paginated: ${config.readAll.paginated},`);
3412
+ if (config.readAll.infinite) lines.push(` infinite: ${config.readAll.infinite},`);
3413
+ if (config.readAll.filters) {
3414
+ lines.push(" filters: {");
3415
+ lines.push(` schema: ${config.readAll.filters.schema},`);
3416
+ lines.push(` filterDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.readAll.filters)})`);
3417
+ lines.push(" },");
3418
+ }
3419
+ lines.push(` columns: ${BUILDERS_UTILS.dynamicColumns}(${renderColumnsConfig(config.readAll.columns)}),`);
3420
+ lines.push(" },");
3421
+ if (config.read) {
3422
+ lines.push(" read: {");
3423
+ if (config.read.acl) lines.push(` acl: ${config.read.acl},`);
3424
+ lines.push(` schema: ${config.read.schema},`);
3425
+ lines.push(` query: ${config.read.query},`);
3426
+ lines.push(" },");
3427
+ }
3428
+ if (config.create) {
3429
+ lines.push(" create: {");
3430
+ if (config.create.acl) lines.push(` acl: ${config.create.acl},`);
3431
+ if (config.create.inputDefs) lines.push(` schema: ${config.create.inputDefs.schema},`);
3432
+ lines.push(` mutation: ${config.create.mutation},`);
3433
+ if (config.create.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.create.inputDefs)})`);
3434
+ lines.push(" },");
3435
+ }
3436
+ if (config.update) {
3437
+ lines.push(" update: {");
3438
+ if (config.update.acl) lines.push(` acl: ${config.update.acl},`);
3439
+ if (config.update.inputDefs) lines.push(` schema: ${config.update.inputDefs.schema},`);
3440
+ lines.push(` mutation: ${config.update.mutation},`);
3441
+ if (config.update.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.update.inputDefs)})`);
3442
+ lines.push(" },");
3443
+ }
3444
+ if (config.delete) {
3445
+ lines.push(" delete: {");
3446
+ if (config.delete.acl) lines.push(` acl: ${config.delete.acl},`);
3447
+ lines.push(` mutation: ${config.delete.mutation},`);
3448
+ lines.push(" },");
3449
+ }
3450
+ lines.push("};");
3451
+ return lines.join("\n");
3452
+ }
3453
+
3454
+ //#endregion
3455
+ //#region src/generators/generate/generateEndpoints.ts
3456
+ function generateEndpoints({ resolver, data, tag }) {
3457
+ if (shouldInlineEndpointsForTag(tag, resolver.options)) return;
3458
+ const endpoints = data.get(tag)?.endpoints;
3459
+ if (!endpoints || endpoints.length === 0) return;
3460
+ const appRestClientImport = {
3461
+ bindings: [APP_REST_CLIENT_NAME],
3462
+ from: getAppRestClientImportPath(resolver.options)
3463
+ };
3464
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3465
+ const hasAxiosImport = hasAxiosRequestConfig;
3466
+ const axiosImport = {
3467
+ bindings: hasAxiosRequestConfig ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
3468
+ from: AXIOS_IMPORT.from
3469
+ };
3470
+ const generateParse = resolver.options.parseRequestParams;
3471
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
3472
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
3473
+ const zodSchemas = getUniqueArray([...endpoints.map((endpoint) => endpoint.response), ...generateParse ? endpointParamsParseSchemas : []]);
3474
+ const hasZodImport = zodSchemas.some((schema) => !isNamedZodSchema(schema));
3475
+ const hasZodExtendedImport = resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
3476
+ const zodExtendedImport = {
3477
+ bindings: [ZOD_EXTENDED.namespace],
3478
+ from: ZOD_PACKAGE_IMPORT_PATH
3479
+ };
3480
+ const modelsImports = getModelsImports({
3481
+ resolver,
3482
+ tag,
3483
+ zodSchemas: zodSchemas.filter(isNamedZodSchema),
3484
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
3485
+ });
3486
+ const lines = [];
3487
+ lines.push(renderImport$2(appRestClientImport));
3488
+ if (hasAxiosImport) lines.push(renderImport$2(axiosImport));
3489
+ if (hasZodImport) lines.push(renderImport$2(ZOD_IMPORT));
3490
+ if (hasZodExtendedImport) lines.push(renderImport$2(zodExtendedImport));
3491
+ for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
3492
+ lines.push("");
3493
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3494
+ type: GenerateType.Endpoints,
3495
+ tag,
3496
+ options: resolver.options
3497
+ })} {`);
3498
+ for (const endpoint of endpoints) {
3499
+ const endpointParamOptions = { modelNamespaceTag: tag };
3500
+ const endpointParams = renderEndpointParams$1(resolver, endpoint, endpointParamOptions);
3501
+ renderEndpointArgs$1(resolver, endpoint, endpointParamOptions);
3502
+ const endpointBody = getEndpointBody$1(endpoint);
3503
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
3504
+ const endpointConfig = renderEndpointConfig(resolver, endpoint, tag);
3505
+ lines.push(`export const ${getEndpointName(endpoint)} = (${endpointParams}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
3506
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
3507
+ lines.push(` { resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} },`);
3508
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
3509
+ if (endpointBody) lines.push(` ${generateParse ? renderEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
3510
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
3511
+ lines.push(` ${endpointConfig}`);
3512
+ lines.push(" )");
3513
+ lines.push("};");
3514
+ }
3515
+ if (resolver.options.tsNamespaces) lines.push("}");
3516
+ return lines.join("\n").trimEnd() + "\n";
3517
+ }
3518
+ function renderImport$2(importData) {
3519
+ return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3520
+ }
3521
+ function renderEndpointParams$1(resolver, endpoint, options) {
3522
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}, `).join("");
3523
+ }
3524
+ function renderEndpointArgs$1(resolver, endpoint, options) {
3525
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => param.name).join(", ");
3526
+ }
3527
+ function renderEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
3528
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
3529
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${addOptional ? ".optional()" : ""}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
3530
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
3531
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
3532
+ }
3533
+ function renderEndpointConfig(resolver, endpoint, modelNamespaceTag) {
3534
+ const endpointConfig = getEndpointConfig(endpoint);
3535
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3536
+ if (Object.keys(endpointConfig).length === 0) return hasAxiosRequestConfig ? AXIOS_REQUEST_CONFIG_NAME : "";
3537
+ const lines = [];
3538
+ lines.push("{");
3539
+ if (hasAxiosRequestConfig) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
3540
+ if (endpointConfig.params) {
3541
+ lines.push(" params: {");
3542
+ for (const param of endpointConfig.params) {
3543
+ const value = resolver.options.parseRequestParams ? renderEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
3544
+ lines.push(` ${param.name}: ${value},`);
3545
+ }
3546
+ lines.push(" },");
3547
+ }
3548
+ if (endpointConfig.headers) {
3549
+ lines.push(" headers: {");
3550
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
3551
+ lines.push(" },");
3552
+ }
3553
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
3554
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
3555
+ lines.push("}");
3556
+ return lines.join("\n ");
3557
+ }
3558
+
3559
+ //#endregion
3560
+ //#region src/generators/generate/generateModels.ts
3561
+ function generateModels({ resolver, data, tag }) {
3562
+ if (resolver.options.modelsInCommon && resolver.options.splitByTags && tag !== resolver.options.defaultTag) return renderModelsProxy({
3563
+ resolver,
3564
+ data,
3565
+ tag
3566
+ });
3567
+ const zodSchemas = data.get(tag)?.zodSchemas;
3568
+ if (!zodSchemas || Object.keys(zodSchemas).length === 0) return;
3569
+ const refZodSchemas = [];
3570
+ for (const zodSchema of Object.keys(zodSchemas)) {
3571
+ const refs = getZodSchemaRefs(resolver, zodSchema);
3572
+ for (const ref of refs) if (!zodSchemas[ref]) refZodSchemas.push(ref);
3573
+ }
3574
+ const modelsImports = getModelsImports({
3575
+ resolver,
3576
+ tag,
3577
+ zodSchemas: refZodSchemas
3578
+ });
3579
+ const zodSchemasData = {};
3580
+ for (const [key, code] of Object.entries(zodSchemas)) {
3581
+ const schemaRef = resolver.getRefByZodSchemaName(key);
3582
+ zodSchemasData[key] = {
3583
+ code,
3584
+ isCiruclar: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
3585
+ isEnum: isEnumZodSchema(code),
3586
+ schemaObj: resolver.getZodSchemaObj(key)
3587
+ };
3588
+ }
3589
+ const lines = [];
3590
+ lines.push(renderImport$1(ZOD_IMPORT));
3591
+ for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
3592
+ lines.push("");
3593
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
3594
+ type: GenerateType.Models,
3595
+ tag,
3596
+ options: resolver.options
3597
+ })} {`);
3598
+ for (const [name, zodSchema] of Object.entries(zodSchemasData)) {
3599
+ lines.push(renderModelJsDocs({
3600
+ name,
3601
+ zodSchema,
3602
+ tag,
3603
+ resolver
3604
+ }));
3605
+ lines.push(`export const ${name} = ${zodSchema.code};`);
3606
+ lines.push(`export type ${getZodSchemaInferedTypeName(name, resolver.options)} = z.infer<typeof ${name}>;`);
3607
+ if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
3608
+ lines.push("");
3609
+ }
3610
+ if (resolver.options.tsNamespaces) lines.push("}");
3611
+ return lines.join("\n").trimEnd() + "\n";
3612
+ }
3613
+ function renderModelsProxy({ resolver, data, tag }) {
3614
+ const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
3615
+ const schemaNames = getUsedSchemaNames({
3616
+ resolver,
3617
+ endpoints: data.get(tag)?.endpoints ?? []
3618
+ }).filter((schemaName) => Boolean(commonZodSchemas[schemaName]));
3619
+ if (schemaNames.length === 0) return;
3620
+ const modelsNamespace = getNamespaceName({
3621
+ type: GenerateType.Models,
3622
+ tag,
3623
+ options: resolver.options
3624
+ });
3625
+ const commonNamespace = getNamespaceName({
3626
+ type: GenerateType.Models,
3627
+ tag: resolver.options.defaultTag,
3628
+ options: resolver.options
3629
+ });
3630
+ const commonModelsPath = `${getImportPath(resolver.options)}${getTagImportPath({
3631
+ type: GenerateType.Models,
3632
+ tag: resolver.options.defaultTag,
3633
+ includeTagDir: true,
3634
+ options: resolver.options
3635
+ })}`;
3636
+ const inferredTypeNames = schemaNames.map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
3637
+ const enumInferredTypeNames = schemaNames.filter((schemaName) => isEnumZodSchema(commonZodSchemas[schemaName] ?? "")).map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
3638
+ if (resolver.options.tsNamespaces) {
3639
+ const lines = [];
3640
+ lines.push(`import { ${commonNamespace} } from "${commonModelsPath}";`);
3641
+ lines.push("");
3642
+ lines.push(`export namespace ${modelsNamespace} {`);
3643
+ for (const schemaName of schemaNames) lines.push(` export const ${schemaName} = ${commonNamespace}.${schemaName};`);
3644
+ for (const typeName of inferredTypeNames) lines.push(` export type ${typeName} = ${commonNamespace}.${typeName};`);
3645
+ for (const enumName of enumInferredTypeNames) lines.push(` export const ${enumName} = ${commonNamespace}.${enumName};`);
3646
+ lines.push("}");
3647
+ lines.push("");
3648
+ return lines.join("\n");
3649
+ }
3650
+ const valueExports = getUniqueArray([...schemaNames, ...enumInferredTypeNames]);
3651
+ const lines = [];
3652
+ if (valueExports.length > 0) lines.push(`export { ${valueExports.join(", ")} } from "${commonModelsPath}";`);
3653
+ if (inferredTypeNames.length > 0) lines.push(`export type { ${inferredTypeNames.join(", ")} } from "${commonModelsPath}";`);
3654
+ return lines.join("\n") + "\n";
3655
+ }
3656
+ function getUsedSchemaNames({ resolver, endpoints }) {
3657
+ const usedSchemaNames = /* @__PURE__ */ new Set();
3658
+ const queue = [];
3659
+ const enqueue = (schemaName) => {
3660
+ if (!schemaName || !isNamedZodSchema(schemaName) || usedSchemaNames.has(schemaName)) return;
3661
+ usedSchemaNames.add(schemaName);
3662
+ queue.push(schemaName);
3663
+ };
3664
+ for (const endpoint of endpoints) {
3665
+ enqueue(endpoint.response);
3666
+ for (const error of endpoint.errors) enqueue(error.zodSchema);
3667
+ for (const param of endpoint.parameters) {
3668
+ enqueue(param.zodSchema);
3669
+ enqueue(param.parameterSortingEnumSchemaName);
3670
+ }
3671
+ }
3672
+ while (queue.length > 0) {
3673
+ const schemaName = queue.shift();
3674
+ if (!schemaName) continue;
3675
+ const refs = getZodSchemaRefs(resolver, schemaName);
3676
+ for (const ref of refs) enqueue(ref);
3677
+ }
3678
+ return Array.from(usedSchemaNames);
3679
+ }
3680
+ function renderImport$1(importData) {
3681
+ return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3682
+ }
3683
+ function renderModelJsDocs({ name, zodSchema, tag, resolver }) {
3684
+ const lines = [
3685
+ `/** `,
3686
+ ` * ${name} `,
3687
+ ` * @type { ${getZodSchemaType(zodSchema)} }`
3688
+ ];
3689
+ const description = getZodSchemaDescription(zodSchema);
3690
+ if (description) lines.push(` * @description ${description.replace(/\n/g, "\n *")}`);
3691
+ const propertyDescriptions = getZodSchemaPropertyDescriptions(resolver, zodSchema, tag);
3692
+ if (propertyDescriptions) for (const [property, info] of Object.entries(propertyDescriptions)) lines.push(` * @property { ${info.type} } ${property} ${info.description.replace(/\n/g, "\n *")} `);
3693
+ lines.push(" */");
3694
+ return lines.join("\n");
3695
+ }
3696
+
3697
+ //#endregion
3698
+ //#region src/generators/const/queries.const.ts
3699
+ const QUERY_HOOKS = {
3700
+ query: "useQuery",
3701
+ infiniteQuery: "useInfiniteQuery",
3702
+ mutation: "useMutation"
3703
+ };
3704
+ const QUERY_IMPORT = {
3705
+ bindings: [
3706
+ QUERY_HOOKS.query,
3707
+ QUERY_HOOKS.infiniteQuery,
3708
+ QUERY_HOOKS.mutation
3709
+ ],
3710
+ from: "@tanstack/react-query"
3711
+ };
3712
+ const QUERIES_MODULE_NAME = "moduleName";
3713
+
3714
+ //#endregion
3715
+ //#region src/generators/generate/generateQueries.ts
3716
+ const endpointParamMappingCache = /* @__PURE__ */ new WeakMap();
3717
+ function generateQueries(params) {
3718
+ const { resolver, data, tag } = params;
3719
+ const inlineEndpoints = shouldInlineEndpointsForTag(tag, resolver.options);
3720
+ const endpoints = data.get(tag)?.endpoints;
3721
+ if (!endpoints || endpoints.length === 0) return;
3722
+ const endpointGroups = groupEndpoints(endpoints, resolver);
3723
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
3724
+ const hasAxiosDefaultImport = endpoints.some(({ mediaUpload }) => mediaUpload);
3725
+ const hasAxiosImport = hasAxiosRequestConfig || hasAxiosDefaultImport;
3726
+ const axiosImport = {
3727
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
3728
+ bindings: hasAxiosRequestConfig ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
3729
+ from: AXIOS_IMPORT.from
3730
+ };
3731
+ const { queryEndpoints, infiniteQueryEndpoints, mutationEndpoints, aclEndpoints } = endpointGroups;
3732
+ const queryImport = {
3733
+ bindings: [
3734
+ ...resolver.options.prefetchQueries && queryEndpoints.length > 0 ? ["QueryClient"] : [],
3735
+ ...queryEndpoints.length > 0 ? [QUERY_HOOKS.query] : [],
3736
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_HOOKS.infiniteQuery] : [],
3737
+ ...mutationEndpoints.length > 0 ? [QUERY_HOOKS.mutation] : []
3738
+ ],
3739
+ from: QUERY_IMPORT.from
3740
+ };
3741
+ const hasMutationEffects = resolver.options.mutationEffects;
3742
+ const queryModulesImport = {
3743
+ bindings: [QUERY_MODULE_ENUM],
3744
+ from: getQueryModulesImportPath(resolver.options)
3745
+ };
3746
+ const hasMutationEffectsImport = hasMutationEffects && mutationEndpoints.length > 0;
3747
+ const mutationEffectsImport = {
3748
+ bindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.optionsType, MUTATION_EFFECTS.hookName] : []],
3749
+ from: PACKAGE_IMPORT_PATH
3750
+ };
3751
+ const hasAclCheck = resolver.options.checkAcl && aclEndpoints.length > 0;
3752
+ const aclCheckImport = {
3753
+ bindings: [ACL_CHECK_HOOK],
3754
+ from: ACL_PACKAGE_IMPORT_PATH
3755
+ };
3756
+ const queryTypesImport = {
3757
+ bindings: [
3758
+ "OpenApiQueryConfig",
3759
+ ...queryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.query] : [],
3760
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.infiniteQuery] : [],
3761
+ ...mutationEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.mutation] : []
3762
+ ],
3763
+ from: getQueryTypesImportPath(resolver.options)
3764
+ };
3765
+ const hasWorkspaceContext = resolver.options.workspaceContext && endpoints.some((endpoint) => getWorkspaceParamNames(resolver, endpoint).length > 0);
3766
+ const workspaceContextImport = {
3767
+ bindings: ["OpenApiWorkspaceContext"],
3768
+ from: PACKAGE_IMPORT_PATH
3769
+ };
3770
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
3771
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
3772
+ const endpointRuntimeSchemas = getUniqueArray([...endpoints.map((endpoint) => endpoint.response), ...resolver.options.parseRequestParams ? endpointParamsParseSchemas : []]);
3773
+ const hasZodImport = inlineEndpoints && endpointRuntimeSchemas.some((schema) => !isNamedZodSchema(schema));
3774
+ const hasZodExtendedImport = inlineEndpoints && resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
3775
+ const appRestClientImport = {
3776
+ bindings: [APP_REST_CLIENT_NAME],
3777
+ from: getAppRestClientImportPath(resolver.options)
3778
+ };
3779
+ const zodExtendedImport = {
3780
+ bindings: [ZOD_EXTENDED.namespace],
3781
+ from: ZOD_PACKAGE_IMPORT_PATH
3782
+ };
3783
+ const modelsImports = getModelsImports({
3784
+ resolver,
3785
+ tag,
3786
+ zodSchemas: inlineEndpoints ? endpointRuntimeSchemas.filter(isNamedZodSchema) : [],
3787
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
3788
+ });
3789
+ const endpointsImports = inlineEndpoints ? [] : getEndpointsImports({
3790
+ tag,
3791
+ endpoints,
3792
+ options: resolver.options
3793
+ });
3794
+ const aclImports = getAclImports({
3795
+ tag,
3796
+ endpoints: aclEndpoints,
3797
+ options: resolver.options
3798
+ });
3799
+ const namespace = getNamespaceName({
3800
+ type: GenerateType.Queries,
3801
+ tag,
3802
+ options: resolver.options
3803
+ });
3804
+ const lines = [];
3805
+ if (hasAxiosImport) lines.push(renderImport(axiosImport));
3806
+ if (inlineEndpoints) {
3807
+ lines.push(renderImport(appRestClientImport));
3808
+ if (hasZodImport) lines.push(renderImport(ZOD_IMPORT));
3809
+ if (hasZodExtendedImport) lines.push(renderImport(zodExtendedImport));
3810
+ }
3811
+ lines.push(renderImport(queryImport));
3812
+ if (hasMutationEffects) lines.push(renderImport(queryModulesImport));
3813
+ if (hasMutationEffectsImport) lines.push(renderImport(mutationEffectsImport));
3814
+ if (hasAclCheck) {
3815
+ lines.push(renderImport(aclCheckImport));
3816
+ for (const aclImport of aclImports) lines.push(renderImport(aclImport));
3817
+ }
3818
+ lines.push(renderImport(queryTypesImport));
3819
+ if (hasWorkspaceContext) lines.push(renderImport(workspaceContextImport));
3820
+ for (const modelsImport of modelsImports) lines.push(renderImport(modelsImport));
3821
+ for (const endpointsImport of endpointsImports) lines.push(renderImport(endpointsImport));
3822
+ lines.push("");
3823
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${namespace} {`);
3824
+ if (inlineEndpoints) {
3825
+ lines.push(...renderInlineEndpoints({
3826
+ resolver,
3827
+ endpoints,
3828
+ tag
3829
+ }));
3830
+ lines.push("");
3831
+ }
3832
+ lines.push(`export const ${QUERIES_MODULE_NAME} = ${hasMutationEffects ? `${QUERY_MODULE_ENUM}.${tag}` : `"${namespace}"`};`);
3833
+ lines.push("");
3834
+ lines.push(renderQueryKeys({
3835
+ resolver,
3836
+ queryEndpoints,
3837
+ tag
3838
+ }));
3839
+ lines.push("");
3840
+ for (const endpoint of endpoints) {
3841
+ const endpointInfo = endpointGroups.infoByEndpoint.get(endpoint);
3842
+ if (endpointInfo?.query) {
3843
+ lines.push(renderQueryOptions({
3844
+ resolver,
3845
+ endpoint,
3846
+ inlineEndpoints
3847
+ }));
3848
+ lines.push("");
3849
+ lines.push(renderQuery({
3850
+ resolver,
3851
+ endpoint,
3852
+ inlineEndpoints
3853
+ }));
3854
+ lines.push("");
3855
+ if (resolver.options.prefetchQueries) {
3856
+ lines.push(renderPrefetchQuery({
3857
+ resolver,
3858
+ endpoint
3859
+ }));
3860
+ lines.push("");
3861
+ }
3862
+ }
3863
+ if (endpointInfo?.mutation) {
3864
+ lines.push(renderMutation({
3865
+ resolver,
3866
+ endpoint,
3867
+ inlineEndpoints,
3868
+ precomputed: endpointGroups.mutationDataByEndpoint.get(endpoint)
3869
+ }));
3870
+ lines.push("");
3871
+ }
3872
+ if (endpointInfo?.infiniteQuery) {
3873
+ lines.push(renderInfiniteQueryOptions({
3874
+ resolver,
3875
+ endpoint,
3876
+ inlineEndpoints
3877
+ }));
3878
+ lines.push("");
3879
+ lines.push(renderInfiniteQuery({
3880
+ resolver,
3881
+ endpoint,
3882
+ inlineEndpoints
3883
+ }));
3884
+ lines.push("");
3885
+ if (resolver.options.prefetchQueries) {
3886
+ lines.push(renderPrefetchInfiniteQuery({
3887
+ resolver,
3888
+ endpoint
3889
+ }));
3890
+ lines.push("");
3891
+ }
3892
+ }
3893
+ }
3894
+ if (resolver.options.tsNamespaces) lines.push("}");
3895
+ return lines.join("\n").trimEnd() + "\n";
3896
+ }
3897
+ function getEndpointParamMapping(resolver, endpoint, options) {
3898
+ let resolverCache = endpointParamMappingCache.get(resolver);
3899
+ if (!resolverCache) {
3900
+ resolverCache = /* @__PURE__ */ new WeakMap();
3901
+ endpointParamMappingCache.set(resolver, resolverCache);
3902
+ }
3903
+ let endpointCache = resolverCache.get(endpoint);
3904
+ if (!endpointCache) {
3905
+ endpointCache = /* @__PURE__ */ new Map();
3906
+ resolverCache.set(endpoint, endpointCache);
3907
+ }
3908
+ const key = JSON.stringify(Object.entries(options ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([optionName, optionValue]) => [optionName, Boolean(optionValue)]));
3909
+ const cached = endpointCache.get(key);
3910
+ if (cached) return cached;
3911
+ const computed = mapEndpointParamsToFunctionParams(resolver, endpoint, options);
3912
+ endpointCache.set(key, computed);
3913
+ return computed;
3914
+ }
3915
+ function renderImport(importData) {
3916
+ return `import ${[...importData.defaultImport ? [importData.defaultImport] : [], ...importData.bindings ? [`{ ${importData.bindings.join(", ")} }`] : []].join(", ")} from "${importData.from}";`;
3917
+ }
3918
+ function renderEndpointParams(resolver, endpoint, options) {
3919
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}`).join(", ");
3920
+ }
3921
+ function renderEndpointArgs(resolver, endpoint, options, replacements) {
3922
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => replacements?.[param.name] ?? param.name).join(", ");
3923
+ }
3924
+ function renderEndpointParamDescription(endpointParam) {
3925
+ const strs = [`${endpointParam.paramType} parameter`];
3926
+ const description = endpointParam.parameterObject?.description || endpointParam.bodyObject?.description;
3927
+ if (description) strs.push(description);
3928
+ let schema = void 0;
3929
+ let mediaTypeObject = void 0;
3930
+ if (endpointParam.parameterObject?.schema && isSchemaObject(endpointParam.parameterObject.schema)) schema = endpointParam.parameterObject?.schema;
3931
+ if (endpointParam.bodyObject?.content) {
3932
+ const matchingMediaType = Object.keys(endpointParam.bodyObject.content ?? {}).find(isParamMediaTypeAllowed);
3933
+ if (matchingMediaType) {
3934
+ mediaTypeObject = endpointParam.bodyObject.content[matchingMediaType];
3935
+ if (mediaTypeObject.schema && isSchemaObject(mediaTypeObject.schema)) schema = mediaTypeObject.schema;
3936
+ }
3937
+ }
3938
+ if (schema) strs.push(...getSchemaDescriptions(schema));
3939
+ if (mediaTypeObject?.example) strs.push(`Example: \`${mediaTypeObject.example}\``);
3940
+ return strs.join(". ");
3941
+ }
3942
+ function getWorkspaceParamNames(resolver, endpoint) {
3943
+ const endpointParams = getEndpointParamMapping(resolver, endpoint, {});
3944
+ const endpointParamNames = new Set(endpointParams.map((param) => param.name));
3945
+ const workspaceParamNames = endpointParams.filter((param) => param.paramType === "Path").map((param) => param.name);
3946
+ const aclParamNames = (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => invalidVariableNameCharactersToCamel(condition.name)).filter((name) => endpointParamNames.has(name));
3947
+ return getUniqueArray([...workspaceParamNames, ...aclParamNames]);
3948
+ }
3949
+ function getWorkspaceParamReplacements(resolver, endpoint) {
3950
+ return Object.fromEntries(getWorkspaceParamNames(resolver, endpoint).map((name) => [name, `${name}FromWorkspace`]));
3951
+ }
3952
+ function renderWorkspaceParamResolutions({ replacements, indent }) {
3953
+ const workspaceParamNames = Object.keys(replacements);
3954
+ if (workspaceParamNames.length === 0) return [];
3955
+ const lines = [`${indent}const workspaceContext = OpenApiWorkspaceContext.useContext();`];
3956
+ for (const paramName of workspaceParamNames) lines.push(`${indent}const ${replacements[paramName]} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
3957
+ return lines;
3958
+ }
3959
+ function renderAclCheckCall(resolver, endpoint, replacements, indent = "") {
3960
+ const checkParams = getAbilityConditionsTypes(endpoint)?.map((condition) => invalidVariableNameCharactersToCamel(condition.name));
3961
+ const paramNames = new Set(endpoint.parameters.map((param) => invalidVariableNameCharactersToCamel(param.name)));
3962
+ const hasAllCheckParams = checkParams?.every((param) => paramNames.has(param));
3963
+ const args = hasAbilityConditions(endpoint) && hasAllCheckParams ? `{ ${(checkParams ?? []).map((param) => {
3964
+ const resolvedParam = replacements?.[param] ?? param;
3965
+ return resolvedParam === param ? param : `${param}: ${resolvedParam}`;
3966
+ }).join(", ")} } ` : "";
3967
+ return `${indent}checkAcl(${getImportedAbilityFunctionName(endpoint, resolver.options)}(${args}));`;
3968
+ }
3969
+ function addAsteriskAfterNewLine(str) {
3970
+ return str.replace(/\n/g, "\n *");
3971
+ }
3972
+ function renderQueryJsDocs({ resolver, endpoint, mode, tag }) {
3973
+ const lines = ["/** "];
3974
+ if (mode === "infiniteQuery") lines.push(` * Infinite query \`${getInfiniteQueryName(endpoint)}${endpoint.summary ? "" : ""}`);
3975
+ else if (mode === "query") lines.push(` * Query \`${getQueryName(endpoint)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should be cached" : ""}`);
3976
+ else lines.push(` * Mutation \`${getQueryName(endpoint, true)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should not be cached" : ""}`);
3977
+ if (endpoint.summary) lines.push(` * @summary ${addAsteriskAfterNewLine(endpoint.summary)}`);
3978
+ if (endpoint.description) lines.push(` * @description ${addAsteriskAfterNewLine(endpoint.description)}`);
3979
+ if (endpoint.acl) lines.push(` * @permission Requires \`${getAbilityFunctionName(endpoint)}\` ability `);
3980
+ const params = getEndpointParamMapping(resolver, endpoint, {
3981
+ ...mode !== "infiniteQuery" ? { includeFileParam: true } : {},
3982
+ modelNamespaceTag: tag
3983
+ });
3984
+ for (const endpointParam of params) lines.push(` * @param { ${endpointParam.type} } ${endpointParam.name} ${renderEndpointParamDescription(endpointParam)}`);
3985
+ if (mode === "query") lines.push(" * @param { AppQueryOptions } options Query options");
3986
+ else if (mode === "mutation") lines.push(` * @param { AppMutationOptions${resolver.options.mutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""} } options Mutation options`);
3987
+ else lines.push(" * @param { AppInfiniteQueryOptions } options Infinite query options");
3988
+ const withAxiosResponse = endpoint.mediaDownload && mode !== "infiniteQuery";
3989
+ const resultType = `${withAxiosResponse ? "AxiosResponse<" : ""}${getImportedZodSchemaInferedTypeName(resolver, endpoint.response, void 0, tag)}${withAxiosResponse ? ">" : ""}`;
3990
+ if (mode === "query") lines.push(` * @returns { UseQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
3991
+ else if (mode === "mutation") lines.push(` * @returns { UseMutationResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
3992
+ else lines.push(` * @returns { UseInfiniteQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
3993
+ lines.push(` * @statusCodes [${endpoint.responseStatusCodes.join(", ")}]`);
3994
+ lines.push(" */");
3995
+ return lines.join("\n");
3996
+ }
3997
+ function renderQueryKeys({ resolver, queryEndpoints, tag }) {
3998
+ if (queryEndpoints.length === 0) return "";
3999
+ const lines = [];
4000
+ lines.push("export const keys = {");
4001
+ lines.push(` all: [${QUERIES_MODULE_NAME}] as const,`);
4002
+ for (const endpoint of queryEndpoints) {
4003
+ lines.push(` ${getEndpointName(endpoint)}: (${renderEndpointParams(resolver, endpoint, {
4004
+ pathParamsRequiredOnly: true,
4005
+ modelNamespaceTag: tag
4006
+ })}) => [...keys.all, "${endpoint.path}", ${renderEndpointArgs(resolver, endpoint, {})}] as const,`);
4007
+ if (resolver.options.infiniteQueries && isInfiniteQuery(endpoint, resolver.options)) lines.push(` ${getEndpointName(endpoint)}Infinite: (${renderEndpointParams(resolver, endpoint, {
4008
+ excludePageParam: true,
4009
+ pathParamsRequiredOnly: true,
4010
+ modelNamespaceTag: tag
4011
+ })}) => [...keys.all, "${endpoint.path}", "infinite", ${renderEndpointArgs(resolver, endpoint, { excludePageParam: true })}] as const,`);
4012
+ }
4013
+ lines.push("};");
4014
+ return lines.join("\n");
4015
+ }
4016
+ function renderInlineEndpoints({ resolver, endpoints, tag }) {
4017
+ const lines = [];
4018
+ for (const endpoint of endpoints) {
4019
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: tag });
4020
+ const endpointBody = getEndpointBody$1(endpoint);
4021
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
4022
+ const endpointConfig = renderInlineEndpointConfig(resolver, endpoint, tag);
4023
+ lines.push(`const ${getEndpointName(endpoint)} = (${endpointParams}${resolver.options.axiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4024
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
4025
+ lines.push(` { resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} },`);
4026
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
4027
+ if (endpointBody) lines.push(` ${resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
4028
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
4029
+ lines.push(` ${endpointConfig}`);
4030
+ lines.push(" );");
4031
+ lines.push("};");
4032
+ lines.push("");
4033
+ }
4034
+ return lines;
4035
+ }
4036
+ function renderInlineEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
4037
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
4038
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${addOptional ? ".optional()" : ""}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
4039
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
4040
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
4041
+ }
4042
+ function renderInlineEndpointConfig(resolver, endpoint, modelNamespaceTag) {
4043
+ const endpointConfig = getEndpointConfig(endpoint);
4044
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4045
+ if (Object.keys(endpointConfig).length === 0) return hasAxiosRequestConfig ? AXIOS_REQUEST_CONFIG_NAME : "";
4046
+ const lines = [];
4047
+ lines.push("{");
4048
+ if (hasAxiosRequestConfig) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
4049
+ if (endpointConfig.params) {
4050
+ lines.push(" params: {");
4051
+ for (const param of endpointConfig.params) {
4052
+ const value = resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
4053
+ lines.push(` ${param.name}: ${value},`);
4054
+ }
4055
+ lines.push(" },");
4056
+ }
4057
+ if (endpointConfig.headers) {
4058
+ lines.push(" headers: {");
4059
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
4060
+ lines.push(" },");
4061
+ }
4062
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
4063
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
4064
+ lines.push(" }");
4065
+ return lines.join("\n");
4066
+ }
4067
+ function renderQueryOptions({ resolver, endpoint, inlineEndpoints }) {
4068
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4069
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
4070
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4071
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4072
+ const lines = [];
4073
+ lines.push(`export const ${getQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => ({`);
4074
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}(${endpointArgs}),`);
4075
+ lines.push(` queryFn: () => ${endpointFunction}(${endpointArgs}${hasAxiosRequestConfig ? `${endpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}),`);
4076
+ lines.push("});");
4077
+ return lines.join("\n");
4078
+ }
4079
+ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
4080
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4081
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4082
+ excludePageParam: true,
4083
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
4084
+ });
4085
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4086
+ const endpointArgsWithPage = renderEndpointArgs(resolver, endpoint, { replacePageParam: true });
4087
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4088
+ const lines = [];
4089
+ lines.push(`export const ${getInfiniteQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => ({`);
4090
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}Infinite(${endpointArgsWithoutPage}),`);
4091
+ lines.push(` queryFn: ({ pageParam }: { pageParam: number }) => ${endpointFunction}(${endpointArgsWithPage}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}` : ""}),`);
4092
+ lines.push(" initialPageParam: 1,");
4093
+ lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }) => {`);
4094
+ lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
4095
+ lines.push(` return pageParam * limitParam < ${resolver.options.infiniteQueryResponseParamNames.totalItems} ? pageParam + 1 : null;`);
4096
+ lines.push(" },");
4097
+ lines.push("});");
4098
+ return lines.join("\n");
4099
+ }
4100
+ function renderPrefetchQuery({ resolver, endpoint }) {
4101
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4102
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
4103
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4104
+ const lines = [];
4105
+ lines.push(`export const ${getPrefetchQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}: ${AXIOS_REQUEST_CONFIG_TYPE}, ` : ""}options?: Omit<Parameters<QueryClient["prefetchQuery"]>[0], "queryKey" | "queryFn">) => {`);
4106
+ lines.push(` return queryClient.prefetchQuery({ ...${getQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options });`);
4107
+ lines.push("};");
4108
+ return lines.join("\n");
4109
+ }
4110
+ function renderPrefetchInfiniteQuery({ resolver, endpoint }) {
4111
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4112
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4113
+ excludePageParam: true,
4114
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
4115
+ });
4116
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4117
+ const lines = [];
4118
+ lines.push(`export const ${getPrefetchInfiniteQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}${hasAxiosRequestConfig ? `${AXIOS_REQUEST_CONFIG_NAME}: ${AXIOS_REQUEST_CONFIG_TYPE}, ` : ""}options?: Omit<Parameters<QueryClient["prefetchInfiniteQuery"]>[0], "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam">) => {`);
4119
+ lines.push(` return queryClient.prefetchInfiniteQuery({ ...${getInfiniteQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasAxiosRequestConfig ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options });`);
4120
+ lines.push("};");
4121
+ return lines.join("\n");
4122
+ }
4123
+ function renderQuery({ resolver, endpoint, inlineEndpoints }) {
4124
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4125
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4126
+ const tag = getEndpointTag(endpoint, resolver.options);
4127
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4128
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
4129
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
4130
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4131
+ optionalPathParams: resolver.options.workspaceContext,
4132
+ modelNamespaceTag: tag
4133
+ });
4134
+ const queryOptionsName = getQueryOptionsName(endpoint);
4135
+ const hasQueryFnOverride = hasAclCheck;
4136
+ const queryOptionsArgs = `${resolvedEndpointArgs ? `{ ${resolvedEndpointArgs} }` : ""}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
4137
+ const lines = [];
4138
+ lines.push(renderQueryJsDocs({
4139
+ resolver,
4140
+ endpoint,
4141
+ mode: "query",
4142
+ tag
4143
+ }));
4144
+ lines.push(`export const ${getQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: AppQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4145
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
4146
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4147
+ lines.push(...renderWorkspaceParamResolutions({
4148
+ replacements: workspaceParamReplacements,
4149
+ indent: " "
4150
+ }));
4151
+ lines.push(" ");
4152
+ lines.push(` return ${QUERY_HOOKS.query}({`);
4153
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
4154
+ if (hasQueryFnOverride) {
4155
+ lines.push(" queryFn: async () => {");
4156
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4157
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn();`);
4158
+ lines.push(" },");
4159
+ }
4160
+ lines.push(" ...options,");
4161
+ lines.push(" onError: options?.onError ?? queryConfig.onError,");
4162
+ lines.push(" });");
4163
+ lines.push("};");
4164
+ return lines.join("\n");
4165
+ }
4166
+ function renderMutation({ resolver, endpoint, inlineEndpoints, precomputed }) {
4167
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4168
+ const hasMutationEffects = resolver.options.mutationEffects;
4169
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4170
+ const tag = getEndpointTag(endpoint, resolver.options);
4171
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4172
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4173
+ includeFileParam: true,
4174
+ optionalPathParams: resolver.options.workspaceContext,
4175
+ modelNamespaceTag: tag
4176
+ });
4177
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
4178
+ const destructuredMutationArgs = renderEndpointArgs(resolver, endpoint, { includeFileParam: true });
4179
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
4180
+ const updateQueryEndpoints = precomputed?.updateQueryEndpoints ?? [];
4181
+ const destructuredVariables = precomputed?.destructuredVariables ?? getDestructuredVariables(resolver, endpoint, updateQueryEndpoints);
4182
+ const hasMutationFnBody = endpoint.mediaUpload || hasAclCheck || Object.keys(workspaceParamReplacements).length > 0;
4183
+ const mutationVariablesType = endpoint.mediaUpload ? `${endpointParams}${endpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : endpointParams;
4184
+ const lines = [];
4185
+ lines.push(renderQueryJsDocs({
4186
+ resolver,
4187
+ endpoint,
4188
+ mode: "mutation",
4189
+ tag
4190
+ }));
4191
+ lines.push(`export const ${getQueryName(endpoint, true)} = (options?: AppMutationOptions<typeof ${endpointFunction}, { ${mutationVariablesType} }>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4192
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
4193
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4194
+ if (Object.keys(workspaceParamReplacements).length > 0) lines.push(" const workspaceContext = OpenApiWorkspaceContext.useContext();");
4195
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<typeof ${QUERY_MODULE_ENUM}.${tag}>({ currentModule: ${QUERIES_MODULE_NAME} });`);
4196
+ lines.push("");
4197
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
4198
+ const mutationFnArg = endpointParams ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
4199
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => ${hasMutationFnBody ? "{ " : ""}`);
4200
+ for (const [paramName, resolvedParamName] of Object.entries(workspaceParamReplacements)) lines.push(` const ${resolvedParamName} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
4201
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4202
+ if (endpoint.mediaUpload) {
4203
+ lines.push(` const uploadInstructions = await ${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""});`);
4204
+ lines.push(" ");
4205
+ lines.push(" if (file && uploadInstructions.url) {");
4206
+ lines.push(" const method = (data?.method?.toLowerCase() ?? \"put\") as \"put\" | \"post\";");
4207
+ lines.push(" let dataToSend: File | FormData = file;");
4208
+ lines.push(" if (method === \"post\") {");
4209
+ lines.push(" dataToSend = new FormData();");
4210
+ lines.push(" if (uploadInstructions.fields) {");
4211
+ lines.push(" for (const [key, value] of uploadInstructions.fields) {");
4212
+ lines.push(" dataToSend.append(key, value);");
4213
+ lines.push(" }");
4214
+ lines.push(" }");
4215
+ lines.push(" dataToSend.append(\"file\", file);");
4216
+ lines.push(" }");
4217
+ lines.push(" await axios[method](uploadInstructions.url, dataToSend, {");
4218
+ lines.push(" headers: {");
4219
+ lines.push(" \"Content-Type\": file.type,");
4220
+ lines.push(" },");
4221
+ lines.push(" signal: abortController?.signal,");
4222
+ lines.push(" onUploadProgress: onUploadProgress");
4223
+ lines.push(" ? (progressEvent) => onUploadProgress({ loaded: progressEvent.loaded, total: progressEvent.total ?? 0 })");
4224
+ lines.push(" : undefined,");
4225
+ lines.push(" });");
4226
+ lines.push(" }");
4227
+ lines.push(" ");
4228
+ lines.push(" return uploadInstructions;");
4229
+ } else lines.push(` ${hasMutationFnBody ? "return " : ""}${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""})`);
4230
+ if (hasMutationFnBody) lines.push(" },");
4231
+ else lines.push(",");
4232
+ lines.push(" ...options,");
4233
+ lines.push(" onError: options?.onError ?? queryConfig.onError,");
4234
+ if (hasMutationEffects) {
4235
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
4236
+ if (updateQueryEndpoints.length > 0) {
4237
+ if (destructuredVariables.length > 0) lines.push(` const { ${destructuredVariables.join(", ")} } = variables;`);
4238
+ for (const [paramName, resolvedParamName] of Object.entries(workspaceParamReplacements)) lines.push(` const ${resolvedParamName} = OpenApiWorkspaceContext.resolveParam(workspaceContext, "${paramName}", ${paramName});`);
4239
+ lines.push(` const updateKeys = [${updateQueryEndpoints.map((e) => `keys.${getEndpointName(e)}(${renderEndpointArgs(resolver, e, { includeOnlyRequiredParams: true }, workspaceParamReplacements)})`).join(", ")}];`);
4240
+ lines.push(` await runMutationEffects(resData, variables, options, updateKeys);`);
4241
+ } else lines.push(" await runMutationEffects(resData, variables, options);");
4242
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
4243
+ lines.push(" },");
4244
+ }
4245
+ lines.push(" });");
4246
+ lines.push("};");
4247
+ return lines.join("\n");
4248
+ }
4249
+ function groupEndpoints(endpoints, resolver) {
4250
+ const queryEndpoints = [];
4251
+ const mutationEndpoints = [];
4252
+ const infiniteQueryEndpoints = [];
4253
+ const aclEndpoints = [];
4254
+ const infoByEndpoint = /* @__PURE__ */ new Map();
4255
+ const mutationDataByEndpoint = /* @__PURE__ */ new Map();
4256
+ for (const endpoint of endpoints) {
4257
+ const query = isQuery(endpoint);
4258
+ const mutation = isMutation(endpoint);
4259
+ const infiniteQuery = Boolean(resolver.options.infiniteQueries && query && isInfiniteQuery(endpoint, resolver.options));
4260
+ if (query) queryEndpoints.push(endpoint);
4261
+ if (mutation) mutationEndpoints.push(endpoint);
4262
+ if (infiniteQuery) infiniteQueryEndpoints.push(endpoint);
4263
+ if (endpoint.acl) aclEndpoints.push(endpoint);
4264
+ infoByEndpoint.set(endpoint, {
4265
+ query,
4266
+ mutation,
4267
+ infiniteQuery
4268
+ });
4269
+ }
4270
+ for (const endpoint of mutationEndpoints) {
4271
+ const updateQueryEndpoints = queryEndpoints.filter((queryEndpoint) => queryEndpoint.parameters.filter((param) => param.parameterObject?.required).every((pathParam) => endpoint.parameters.some((param) => param.name === pathParam.name)) && queryEndpoint.response === endpoint.response);
4272
+ mutationDataByEndpoint.set(endpoint, {
4273
+ updateQueryEndpoints,
4274
+ destructuredVariables: getDestructuredVariables(resolver, endpoint, updateQueryEndpoints)
4275
+ });
4276
+ }
4277
+ return {
4278
+ queryEndpoints,
4279
+ mutationEndpoints,
4280
+ infiniteQueryEndpoints,
4281
+ aclEndpoints,
4282
+ infoByEndpoint,
4283
+ mutationDataByEndpoint
4284
+ };
4285
+ }
4286
+ function renderInfiniteQuery({ resolver, endpoint, inlineEndpoints }) {
4287
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
4288
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
4289
+ const tag = getEndpointTag(endpoint, resolver.options);
4290
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
4291
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
4292
+ excludePageParam: true,
4293
+ optionalPathParams: resolver.options.workspaceContext,
4294
+ modelNamespaceTag: tag
4295
+ });
4296
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
4297
+ const resolvedEndpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true }, workspaceParamReplacements);
4298
+ const queryOptionsName = getInfiniteQueryOptionsName(endpoint);
4299
+ const queryOptionsArgs = `${resolvedEndpointArgsWithoutPage ? `{ ${resolvedEndpointArgsWithoutPage} }` : ""}${hasAxiosRequestConfig ? `${resolvedEndpointArgsWithoutPage ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
4300
+ const hasQueryFnOverride = hasAclCheck;
4301
+ const lines = [];
4302
+ lines.push(renderQueryJsDocs({
4303
+ resolver,
4304
+ endpoint,
4305
+ mode: "infiniteQuery",
4306
+ tag
4307
+ }));
4308
+ lines.push(`export const ${getInfiniteQueryName(endpoint)} = <TData>(${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }, ` : ""}options?: AppInfiniteQueryOptions<typeof ${inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options)}, TData>${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${AXIOS_REQUEST_CONFIG_TYPE}` : ""}) => {`);
4309
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
4310
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
4311
+ lines.push(...renderWorkspaceParamResolutions({
4312
+ replacements: workspaceParamReplacements,
4313
+ indent: " "
4314
+ }));
4315
+ lines.push("");
4316
+ lines.push(` return ${QUERY_HOOKS.infiniteQuery}({`);
4317
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
4318
+ if (hasQueryFnOverride) {
4319
+ lines.push(" queryFn: async ({ pageParam }) => {");
4320
+ lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
4321
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ pageParam });`);
4322
+ lines.push(" },");
4323
+ }
4324
+ lines.push(" ...options,");
4325
+ lines.push(" onError: options?.onError ?? queryConfig.onError,");
4326
+ lines.push(" });");
4327
+ lines.push("};");
4328
+ return lines.join("\n");
4329
+ }
4330
+
4331
+ //#endregion
4332
+ //#region src/generators/generate/generateAppRestClient.ts
4333
+ function generateAppRestClient(resolver) {
4334
+ return `import { RestClient } from "${PACKAGE_IMPORT_PATH}";
4335
+
4336
+ export const ${APP_REST_CLIENT_NAME} = new RestClient({
4337
+ config: {
4338
+ baseURL: "${resolver.getBaseUrl()}"
4339
+ },
4340
+ });
4341
+ `;
4342
+ }
4343
+
4344
+ //#endregion
4345
+ //#region src/generators/generate/generateQueryModules.ts
4346
+ function generateQueryModules({ resolver, data }) {
4347
+ const modules = [];
4348
+ data.forEach((_, tag) => {
4349
+ const endpoints = data.get(tag)?.endpoints;
4350
+ if (!endpoints || endpoints.length === 0) return;
4351
+ modules.push({
4352
+ tag,
4353
+ namespace: getNamespaceName({
4354
+ type: GenerateType.Queries,
4355
+ tag,
4356
+ options: resolver.options
4357
+ })
4358
+ });
4359
+ });
4360
+ const lines = [];
4361
+ lines.push("export const enum QueryModule {");
4362
+ for (const module of modules) lines.push(` ${module.tag} = "${module.namespace}",`);
4363
+ lines.push("}");
4364
+ return lines.join("\n");
4365
+ }
4366
+
4367
+ //#endregion
4368
+ //#region src/generators/utils/generate-files.utils.ts
4369
+ function getAclFiles(data, resolver) {
4370
+ if (!resolver.options.acl) return [];
4371
+ return [{
4372
+ fileName: getOutputFileName({
4373
+ output: resolver.options.output,
4374
+ fileName: getFileNameWithExtension(ACL_APP_ABILITY_FILE)
4375
+ }),
4376
+ content: generateAppAcl({
4377
+ resolver,
4378
+ data
4379
+ })
4380
+ }];
4381
+ }
4382
+ function getMutationEffectsFiles(data, resolver) {
4383
+ if (!resolver.options.mutationEffects) return [];
4384
+ return [{
4385
+ fileName: getOutputFileName({
4386
+ output: resolver.options.output,
4387
+ fileName: getFileNameWithExtension(QUERY_MODULES_FILE)
4388
+ }),
4389
+ content: generateQueryModules({
4390
+ resolver,
4391
+ data
4392
+ })
4393
+ }];
4394
+ }
4395
+ function getZodExtendedFiles(_data, _resolver) {
4396
+ return [];
4397
+ }
4398
+ function getAppRestClientFiles(resolver) {
4399
+ if (resolver.options.restClientImportPath !== DEFAULT_GENERATE_OPTIONS.restClientImportPath) return [];
4400
+ return [{
4401
+ fileName: getOutputFileName({
4402
+ output: resolver.options.output,
4403
+ fileName: getFileNameWithExtension(APP_REST_CLIENT_FILE)
4404
+ }),
4405
+ content: generateAppRestClient(resolver)
4406
+ }];
4407
+ }
4408
+
4409
+ //#endregion
4410
+ //#region src/generators/generateCodeFromOpenAPIDoc.ts
4411
+ function generateCodeFromOpenAPIDoc(openApiDoc, options, profiler) {
4412
+ const p = profiler ?? new Profiler(false);
4413
+ const importPath = options.standalone && options.importPath === "ts" ? "relative" : options.importPath;
4414
+ const { resolver, data } = p.runSync("data.extract", () => getDataFromOpenAPIDoc(openApiDoc, {
4415
+ ...options,
4416
+ importPath
4417
+ }, p));
4418
+ const generateFilesData = [];
4419
+ const appAclTags = [];
4420
+ const modelsOnly = Boolean(resolver.options.modelsOnly);
4421
+ const shouldGenerateEndpoints = !modelsOnly && Array.from(data.keys()).some((tag) => !shouldInlineEndpointsForTag(tag, resolver.options));
4422
+ const generateTypes = modelsOnly ? [GenerateType.Models] : [
4423
+ GenerateType.Models,
4424
+ ...shouldGenerateEndpoints ? [GenerateType.Endpoints] : [],
4425
+ GenerateType.Queries,
4426
+ ...resolver.options.acl ? [GenerateType.Acl] : [],
4427
+ ...resolver.options.builderConfigs ? [GenerateType.Configs] : []
4428
+ ];
4429
+ const generateFunctions = {
4430
+ [GenerateType.Models]: generateModels,
4431
+ [GenerateType.Endpoints]: generateEndpoints,
4432
+ [GenerateType.Queries]: generateQueries,
4433
+ [GenerateType.Acl]: generateAcl,
4434
+ [GenerateType.Configs]: generateConfigs
4435
+ };
4436
+ data.forEach((_, tag) => {
4437
+ generateTypes.forEach((type) => {
4438
+ const content = p.runSync(`render.${type}`, () => generateFunctions[type]({
4439
+ resolver,
4440
+ data,
4441
+ tag
4442
+ }));
4443
+ if (content) {
4444
+ const fileName = getOutputFileName({
4445
+ output: options.output,
4446
+ fileName: getTagFileName({
4447
+ tag,
4448
+ type,
4449
+ options
4450
+ })
4451
+ });
4452
+ generateFilesData.push({
4453
+ fileName,
4454
+ content
4455
+ });
4456
+ if (type === GenerateType.Acl) appAclTags.push(tag);
4457
+ }
4458
+ });
4459
+ });
4460
+ if (!modelsOnly) generateFilesData.push(...p.runSync("render.AclShared", () => getAclFiles(data, resolver)), ...p.runSync("render.MutationEffects", () => getMutationEffectsFiles(data, resolver)), ...p.runSync("render.ZodExtended", () => getZodExtendedFiles(data, resolver)), ...p.runSync("render.Standalone", () => getAppRestClientFiles(resolver)));
4461
+ return generateFilesData;
4462
+ }
4463
+
4464
+ //#endregion
4465
+ export { VALIDATION_ERROR_TYPE_TITLE as S, isMediaTypeAllowed as _, deepMerge as a, formatTag as b, getSchemaTsMetaType as c, getTagImportPath as d, getQueryName as f, groupByType as g, GenerateType as h, getDataFromOpenAPIDoc as i, getTsTypeBase as l, getNamespaceName as m, getOutputFileName as n, isMutation as o, DEFAULT_GENERATE_OPTIONS as p, writeGenerateFileData as r, isQuery as s, generateCodeFromOpenAPIDoc as t, getTagFileName as u, isParamMediaTypeAllowed as v, Profiler as x, invalidVariableNameCharactersToCamel as y };