@povio/openapi-codegen-cli 2.0.8-rc.38 → 2.0.8-rc.39

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