@povio/openapi-codegen-cli 3.3.0-rc.2 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +125 -9
  2. package/dist/AuthGuard-GbtTDXs0.d.mts +32 -0
  3. package/dist/AuthGuard-qpAtHaBz.mjs +24 -0
  4. package/dist/acl.d.mts +6 -19
  5. package/dist/acl.mjs +7 -7
  6. package/dist/{auth.context-BAz8frX9.mjs → auth.context-COWO6ssl.mjs} +1 -18
  7. package/dist/auth.d.mts +2 -0
  8. package/dist/auth.mjs +3 -0
  9. package/dist/axios.d.mts +2 -0
  10. package/dist/axios.mjs +2 -0
  11. package/dist/{config-BQqze8rU.d.mts → config-FD2Y872S.d.mts} +1 -2
  12. package/dist/config.d.mts +4 -0
  13. package/dist/config.mjs +5 -0
  14. package/dist/{error-handling-D6ZYITQ3.d.mts → error-handling-LPEPQV1V.d.mts} +3 -42
  15. package/dist/{error-handling-CsnufAil.mjs → error-handling-uS0DgYUR.mjs} +23 -47
  16. package/dist/errors.d.mts +3 -0
  17. package/dist/errors.mjs +2 -0
  18. package/dist/generate.runner-CLK1FoLT.mjs +1669 -0
  19. package/dist/generate.utils-BSDYGp-0.cjs +2270 -0
  20. package/dist/{generateCodeFromOpenAPIDoc-SYuVswEJ.mjs → generateCodeFromOpenAPIDoc-BypeVKIE.cjs} +1496 -2258
  21. package/dist/generateCodeFromOpenAPIDoc-CDyGSv2w.mjs +2242 -0
  22. package/dist/generator.d.mts +3 -10
  23. package/dist/generator.mjs +6 -4
  24. package/dist/getDataFromOpenAPIDoc-DYiCTWno.mjs +2016 -0
  25. package/dist/i18n-B_brQh4X.d.mts +38 -0
  26. package/dist/i18n-D-FesqFb.mjs +36 -0
  27. package/dist/index.d.mts +12 -198
  28. package/dist/index.mjs +12 -256
  29. package/dist/metro.cjs +118 -4862
  30. package/dist/metro.d.mts +3 -4
  31. package/dist/metro.mjs +3 -3
  32. package/dist/native-rest-interceptor-Np4Ov54n.mjs +215 -0
  33. package/dist/native-rest-interceptor-PgziZt1f.d.mts +49 -0
  34. package/dist/native.d.mts +3 -0
  35. package/dist/native.mjs +3 -0
  36. package/dist/openapi-codegen-native-darwin-arm64.node +0 -0
  37. package/dist/openapi-codegen-native-linux-x64.node +0 -0
  38. package/dist/openapi-codegen-native-win32-x64.node +0 -0
  39. package/dist/{openapi-codegen.runner-CCXQsUum.mjs → openapi-codegen.runner-DUqQD2B5.mjs} +2 -2
  40. package/dist/{openapi-source.runner-B6KKrXw7.d.mts → openapi-source.runner-Bje-tMOV.d.mts} +2 -8
  41. package/dist/{openapi-source.runner-8kCe-g9S.mjs → openapi-source.runner-DPUNTduQ.mjs} +25 -11
  42. package/dist/{options-DdQJ9BSc.d.mts → options-rz2bcsaN.d.mts} +10 -1
  43. package/dist/query.d.mts +3 -0
  44. package/dist/query.mjs +3 -0
  45. package/dist/queryConfig.context-CRJOgf19.d.mts +22 -0
  46. package/dist/queryConfig.context-CldQ5YL9.mjs +34 -0
  47. package/dist/rest-client-CQyFvqYC.d.mts +55 -0
  48. package/dist/rest-interceptor-Dm9DFErh.mjs +115 -0
  49. package/dist/rest-transport.types-DM5-qyOJ.d.mts +66 -0
  50. package/dist/rest-transport.types-DxitRtsB.mjs +11 -0
  51. package/dist/rest.d.mts +2 -0
  52. package/dist/rest.mjs +2 -0
  53. package/dist/rest.utils-DpiFIdhF.d.mts +9 -0
  54. package/dist/router.context-EPlMBk3G.mjs +21 -0
  55. package/dist/sh.d.mts +1 -1
  56. package/dist/sh.mjs +50 -55
  57. package/dist/tiny.d.mts +1 -1
  58. package/dist/tiny.mjs +1 -1
  59. package/dist/useMutationEffects-DIdL8tlx.d.mts +29 -0
  60. package/dist/useMutationEffects-PB1fvKWM.mjs +68 -0
  61. package/dist/vite.d.mts +3 -4
  62. package/dist/vite.mjs +5 -4
  63. package/dist/workspace.context-XWvQ_7Hg.mjs +26 -0
  64. package/dist/workspace.context-isVY9ves.d.mts +23 -0
  65. package/dist/zod.d.mts +2 -7
  66. package/dist/zod.mjs +1 -1
  67. package/package.json +67 -19
  68. package/dist/generate.runner-B0Zm3pIl.mjs +0 -87
@@ -0,0 +1,2242 @@
1
+ import { r as getZodSchemaRefs, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-DYiCTWno.mjs";
2
+ import { $ as getImportedAbilityFunctionName, A as getEndpointsImports, An as NATIVE_RESPONSE_TYPE, At as APP_REST_CLIENT_NAME, B as getPrefetchInfiniteQueryName, Bt as NATIVE_PACKAGE_IMPORT_PATH, C as getAppRestClientImportPath, Cn as ZOD_IMPORT, D as getTagFileName, Dn as AXIOS_REQUEST_CONFIG_TYPE, Dt as isEnumZodSchema, E as getQueryTypesImportPath, En as AXIOS_REQUEST_CONFIG_NAME, F as mergeImports, Ft as QUERY_MODULE_ENUM, G as getAbilityConditionType, H as getQueryName, Ht as getNamespaceName, I as getImportedInfiniteQueryName, In as shouldInlineEndpointsForTag, It as QUERY_OPTIONS_TYPES, J as getAbilityFunctionName, K as getAbilityConditionsTypes, L as getImportedQueryName, Ln as camelToSpaceSeparated, Lt as ZOD_EXTENDED, M as getInfiniteQueriesImports, Mt as DOMAIN_ERRORS_FILE, N as getModelsImports, Nn as getEndpointTag, Nt as MUTATION_EFFECTS, O as getTagImportPath, Ot as isNamedZodSchema, P as getQueriesImports, Pt as QUERY_MODULES_FILE, Q as getAppAbilitiesType, R as getInfiniteQueryName, Rn as capitalize, Rt as AXIOS_PACKAGE_IMPORT_PATH, T as getQueryModulesImportPath, Tn as AXIOS_IMPORT, U as getQueryOptionsName, V as getPrefetchQueryName, Vn as kebabToCamel, Vt as REST_PACKAGE_IMPORT_PATH, W as getAbilityAction, Wn as Profiler, X as getAbilitySubjectTypes, Y as getAbilitySubject, Z as getAclData, Zt as isParamMediaTypeAllowed, _ as hasEndpointConfig, _t as isReadAllEndpoint, an as wrapWithQuotesIfNeeded, at as getZodSchemaInferedTypeName, b as requiresBody, bt as invalidVariableNameCharactersToCamel, c as getDestructuredVariables, cn as isReferenceObject, ct as getSchemaDescriptions, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, et as hasAbilityConditions, f as getEndpointBody, fn as ANY_SCHEMA, ft as getPathSegments, g as getImportedEndpointName, gt as isPathSegmentParam, h as getEndpointPath, ht as isDeleteEndpoint, i as shouldUseNativeCodegen, it as getZodSchemaDescription, j as getImportPath, jn as getRequestConfigTypeName, jt as BUILDERS_UTILS, k as getAclImports, kn as JSON_APPLICATION_FORMAT, kt as APP_REST_CLIENT_FILE, l as isInfiniteQuery, ln as isSchemaObject, m as getEndpointName, mt as isCreateEndpoint, nt as getImportedZodSchemaInferedTypeName, o as getOutputFileName, ot as getZodSchemaPropertyDescriptions, p as getEndpointConfig, pt as isBulkDeleteEndpoint, q as getAbilityDescription, r as compileNativeData, rt as getImportedZodSchemaName, st as getZodSchemaType, tt as renderAclCheckCall, u as isMutation, ut as getUniqueArray, v as mapEndpointParamsToFunctionParams, vt as isReadEndpoint, w as getFileNameWithExtension, wn as AXIOS_DEFAULT_IMPORT_NAME, y as renderMediaUploadMutationBody, yt as isUpdateEndpoint, z as getInfiniteQueryOptionsName, zt as CONFIG_PACKAGE_IMPORT_PATH } from "./generate.runner-CLK1FoLT.mjs";
3
+ import "node:module";
4
+ //#region \0rolldown/runtime.js
5
+ var __defProp = Object.defineProperty;
6
+ var __exportAll = (all, no_symbols) => {
7
+ let target = {};
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
13
+ return target;
14
+ };
15
+ //#endregion
16
+ //#region src/generators/const/acl.const.ts
17
+ const ACL_APP_ABILITY_FILE = {
18
+ fileName: "acl/app.ability",
19
+ extension: "ts"
20
+ };
21
+ const ACL_APP_ABILITIES = "AppAbilities";
22
+ const ACL_CHECK_HOOK = "useAclCheck";
23
+ const CASL_ABILITY_BINDING = {
24
+ abilityTuple: "AbilityTuple",
25
+ pureAbility: "PureAbility",
26
+ forcedSubject: "ForcedSubject",
27
+ subjectType: "Subject",
28
+ subject: "subject"
29
+ };
30
+ const CASL_ABILITY_IMPORT = {
31
+ bindings: [
32
+ CASL_ABILITY_BINDING.abilityTuple,
33
+ CASL_ABILITY_BINDING.pureAbility,
34
+ CASL_ABILITY_BINDING.forcedSubject,
35
+ CASL_ABILITY_BINDING.subjectType,
36
+ CASL_ABILITY_BINDING.subject
37
+ ],
38
+ from: "@casl/ability"
39
+ };
40
+ //#endregion
41
+ //#region src/generators/generate/generateAcl.ts
42
+ function generateAcl({ resolver, data, tag }) {
43
+ const nativeContent = resolver.getNativeRenderedAcl?.(tag);
44
+ if (nativeContent) return nativeContent;
45
+ const aclData = getAclData({
46
+ resolver,
47
+ data,
48
+ tag
49
+ });
50
+ if (!aclData) return;
51
+ const { hasAdditionalAbilityImports, modelsImports, endpoints } = aclData;
52
+ const hasWorkspaceContext = endpoints.some((endpoint) => getWorkspaceConditionNames(resolver, endpoint).length > 0);
53
+ const caslAbilityTupleImport = {
54
+ bindings: [...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject, CASL_ABILITY_BINDING.subject] : []],
55
+ typeBindings: [CASL_ABILITY_BINDING.abilityTuple],
56
+ from: CASL_ABILITY_IMPORT.from
57
+ };
58
+ const workspaceContextImport = {
59
+ bindings: ["useWorkspaceContext"],
60
+ from: CONFIG_PACKAGE_IMPORT_PATH
61
+ };
62
+ const lines = [];
63
+ lines.push(renderImport$4(caslAbilityTupleImport));
64
+ if (hasWorkspaceContext) lines.push(renderImport$4(workspaceContextImport));
65
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
66
+ lines.push("");
67
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
68
+ type: "acl",
69
+ tag,
70
+ options: resolver.options
71
+ })} {`);
72
+ for (const endpoint of endpoints) {
73
+ lines.push(renderAbilityFunction({
74
+ resolver,
75
+ endpoint
76
+ }));
77
+ lines.push("");
78
+ }
79
+ if (resolver.options.tsNamespaces) lines.push("}");
80
+ return lines.join("\n").trimEnd() + "\n";
81
+ }
82
+ function generateAppAcl({ resolver, data }) {
83
+ const nativeContent = resolver.getNativeRenderedShared?.("appAcl");
84
+ if (nativeContent) return nativeContent;
85
+ const { appAbilitiesType, hasAdditionalAbilityImports, modelsImports } = getAppAbilitiesType({
86
+ resolver,
87
+ data
88
+ });
89
+ const caslAbilityTupleImport = {
90
+ bindings: [],
91
+ typeBindings: [
92
+ CASL_ABILITY_BINDING.pureAbility,
93
+ CASL_ABILITY_BINDING.abilityTuple,
94
+ ...!appAbilitiesType ? [CASL_ABILITY_BINDING.subjectType] : [],
95
+ ...hasAdditionalAbilityImports ? [CASL_ABILITY_BINDING.forcedSubject] : []
96
+ ],
97
+ from: CASL_ABILITY_IMPORT.from,
98
+ typeOnly: true
99
+ };
100
+ const lines = [];
101
+ lines.push(renderImport$4(caslAbilityTupleImport));
102
+ for (const modelsImport of modelsImports) lines.push(renderImport$4(modelsImport));
103
+ lines.push("");
104
+ if (appAbilitiesType) {
105
+ lines.push(`export type ${ACL_APP_ABILITIES} = `);
106
+ for (const [action, subjects] of Object.entries(appAbilitiesType)) lines.push(`| ${CASL_ABILITY_BINDING.abilityTuple}<"${action}", ${subjects.join(" | ")}>`);
107
+ } else lines.push(`export type ${ACL_APP_ABILITIES} = ${CASL_ABILITY_BINDING.abilityTuple}<string, ${CASL_ABILITY_BINDING.subjectType}>;`);
108
+ lines.push("");
109
+ lines.push(`export type AppAbility = PureAbility<${ACL_APP_ABILITIES}>;`);
110
+ return lines.join("\n");
111
+ }
112
+ function renderImport$4(importData) {
113
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
114
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
115
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
116
+ }
117
+ function getWorkspaceContextAllowList$1(workspaceContext) {
118
+ return new Set(workspaceContext);
119
+ }
120
+ function getWorkspaceConditionNames(resolver, endpoint) {
121
+ const allowList = getWorkspaceContextAllowList$1(resolver.options.workspaceContext);
122
+ return (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => condition.name).filter((name) => allowList.has(name));
123
+ }
124
+ function renderWorkspaceAclHook({ resolver, endpoint }) {
125
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
126
+ const workspaceConditionNames = getWorkspaceConditionNames(resolver, endpoint);
127
+ if (workspaceConditionNames.length === 0) return;
128
+ const workspaceConditionNameSet = new Set(workspaceConditionNames);
129
+ const objectRequired = abilityConditionsTypes.some((propertyType) => propertyType.required && !workspaceConditionNameSet.has(propertyType.name));
130
+ const objectParams = abilityConditionsTypes.map((propertyType) => {
131
+ const isWorkspaceCondition = workspaceConditionNameSet.has(propertyType.name);
132
+ return `${propertyType.name}${propertyType.required && !isWorkspaceCondition ? "" : "?"}: ${renderConditionType(resolver, endpoint, propertyType)}, `;
133
+ }).join("");
134
+ const contextType = abilityConditionsTypes.filter((propertyType) => workspaceConditionNameSet.has(propertyType.name)).map((propertyType) => `${propertyType.name}?: ${renderConditionType(resolver, endpoint, propertyType)}`).join("; ");
135
+ const contextBindings = workspaceConditionNames.map((name) => `${name}: ${name}Workspace`).join(", ");
136
+ const lines = [];
137
+ lines.push(`export const use${capitalize(getAbilityFunctionName(endpoint))} = (`);
138
+ lines.push(` object${objectRequired ? "" : "?"}: { ${objectParams} } `);
139
+ lines.push(") => {");
140
+ lines.push(` const { ${contextBindings} } = useWorkspaceContext<{ ${contextType} }>();`);
141
+ for (const conditionName of workspaceConditionNames) {
142
+ const resolvedName = `normalize${capitalize(conditionName)}`;
143
+ lines.push(` const ${resolvedName} = object?.${conditionName} ?? ${conditionName}Workspace;`);
144
+ lines.push(` if (!${resolvedName}) {`);
145
+ lines.push(` throw Error(\`${capitalize(conditionName)} not provided\`);`);
146
+ lines.push(" }");
147
+ }
148
+ lines.push(` return ${getAbilityFunctionName(endpoint)}({ ...object, ${workspaceConditionNames.map((conditionName) => `${conditionName}: normalize${capitalize(conditionName)}`).join(", ")} });`);
149
+ lines.push("};");
150
+ return lines.join("\n");
151
+ }
152
+ function renderAbilityFunction({ resolver, endpoint }) {
153
+ const abilityConditionsTypes = getAbilityConditionsTypes(endpoint) ?? [];
154
+ const hasConditions = hasAbilityConditions(endpoint);
155
+ const lines = [];
156
+ const abilityQuery = endpoint.method === "get" ? endpoint.mediaDownload ? `\`${getQueryName(endpoint)}\` query or \`${getQueryName(endpoint, true)}\` mutation` : `\`${getQueryName(endpoint)}\` query` : `\`${getQueryName(endpoint)}\` mutation`;
157
+ lines.push("/**");
158
+ lines.push(` * Use for ${abilityQuery} ability. ${hasConditions ? "For global ability, omit the object parameter." : ""}${getAbilityDescription(endpoint) ? "" : ""}`);
159
+ if (getAbilityDescription(endpoint)) lines.push(` * @description ${getAbilityDescription(endpoint)}`);
160
+ if (hasConditions) for (const propertyType of abilityConditionsTypes) lines.push(` * @param { ${renderConditionType(resolver, endpoint, propertyType)} } object.${propertyType.name} ${propertyType.name} from ${propertyType.info}`);
161
+ lines.push(` * @returns { AbilityTuple } An ability tuple indicating the user's ability to use ${abilityQuery}`);
162
+ lines.push(" */");
163
+ lines.push(`export const ${getAbilityFunctionName(endpoint)} = (`);
164
+ if (hasConditions) lines.push(` object?: { ${abilityConditionsTypes.map((propertyType) => `${propertyType.name}${propertyType.required ? "" : "?"}: ${renderConditionType(resolver, endpoint, propertyType)}, `).join("")} } `);
165
+ lines.push(") => [");
166
+ lines.push(` "${getAbilityAction(endpoint)}",`);
167
+ lines.push(` ${hasConditions ? `object ? subject("${getAbilitySubject(endpoint)}", object) : "${getAbilitySubject(endpoint)}"` : `"${getAbilitySubject(endpoint)}"`}`);
168
+ lines.push(`] as ${CASL_ABILITY_BINDING.abilityTuple}<"${getAbilityAction(endpoint)}", ${getAbilitySubjectTypes(endpoint, resolver, getEndpointTag(endpoint, resolver.options)).join(" | ")}>;`);
169
+ const workspaceAclHook = renderWorkspaceAclHook({
170
+ resolver,
171
+ endpoint
172
+ });
173
+ if (workspaceAclHook) {
174
+ lines.push("");
175
+ lines.push(workspaceAclHook);
176
+ }
177
+ return lines.join("\n");
178
+ }
179
+ function renderConditionType(resolver, endpoint, propertyType) {
180
+ return getAbilityConditionType(propertyType, resolver, getEndpointTag(endpoint, resolver.options));
181
+ }
182
+ //#endregion
183
+ //#region src/generators/const/buildConfigs.const.ts
184
+ const BUILD_CONFIG_SUFFIX = "config";
185
+ //#endregion
186
+ //#region src/generators/utils/generate/generate.configs.utils.ts
187
+ function getBuilderConfigs({ data, tag, resolver }) {
188
+ const endpoints = data.get(tag)?.endpoints;
189
+ if (!endpoints || endpoints.length === 0) return {
190
+ configs: [],
191
+ hasZodImport: false,
192
+ modelsImports: [],
193
+ queriesImports: [],
194
+ aclImports: []
195
+ };
196
+ const extendedEndpoints = endpoints.map((endpoint) => ({
197
+ ...endpoint,
198
+ pathSegments: getPathSegments(endpoint.path)
199
+ }));
200
+ const namedReadAllEndpoints = resolveBuilderConfigNames(extendedEndpoints.filter((endpoint) => isReadAllEndpoint(endpoint, resolver.options)));
201
+ let hasZodImport = false;
202
+ const importedZodSchemas = [];
203
+ const importedEndpoints = [];
204
+ const importedInfiniteEndpoints = [];
205
+ const configs = Object.entries(namedReadAllEndpoints).map(([name, readAllEndpoint]) => {
206
+ const columnsConfig = getColumnsConfig(resolver, readAllEndpoint);
207
+ if (!columnsConfig) return;
208
+ importedEndpoints.push(readAllEndpoint);
209
+ importedInfiniteEndpoints.push(readAllEndpoint);
210
+ if (columnsConfig.zodSchema) {
211
+ if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
212
+ else hasZodImport = true;
213
+ }
214
+ if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
215
+ const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
216
+ if (filter) importedZodSchemas.push(filter.zodSchema);
217
+ const config = {
218
+ name,
219
+ title: capitalize(camelToSpaceSeparated(name.replace(/config$/i, ""))),
220
+ readAll: {
221
+ acl: getAclConfig(readAllEndpoint, resolver.options),
222
+ paginated: getImportedQueryName(readAllEndpoint, resolver.options),
223
+ infinite: resolver.options.infiniteQueries ? getImportedInfiniteQueryName(readAllEndpoint, resolver.options) : void 0,
224
+ filters: getInputsConfig(resolver, filter),
225
+ columns: columnsConfig.columns
226
+ }
227
+ };
228
+ const readEndpoint = extendedEndpoints.find((endpoint) => isReadEndpoint(endpoint, readAllEndpoint));
229
+ if (readEndpoint) {
230
+ importedEndpoints.push(readEndpoint);
231
+ let responseSchema = readEndpoint.response;
232
+ if (isNamedZodSchema(responseSchema)) {
233
+ importedZodSchemas.push(responseSchema);
234
+ responseSchema = getImportedZodSchemaName(resolver, responseSchema);
235
+ } else hasZodImport = true;
236
+ config.read = {
237
+ acl: getAclConfig(readEndpoint, resolver.options),
238
+ schema: responseSchema,
239
+ query: getImportedQueryName(readEndpoint, resolver.options)
240
+ };
241
+ }
242
+ const createEndpoint = extendedEndpoints.find((endpoint) => isCreateEndpoint(endpoint, readAllEndpoint));
243
+ if (createEndpoint) {
244
+ importedEndpoints.push(createEndpoint);
245
+ const body = getEndpointBody(createEndpoint);
246
+ if (body) {
247
+ importedZodSchemas.push(body.zodSchema);
248
+ config.create = {
249
+ acl: getAclConfig(createEndpoint, resolver.options),
250
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
251
+ mutation: createEndpoint,
252
+ inputDefs: getInputsConfig(resolver, body)
253
+ };
254
+ }
255
+ }
256
+ const updateEndpoint = extendedEndpoints.find((endpoint) => isUpdateEndpoint(endpoint, readAllEndpoint));
257
+ if (updateEndpoint) {
258
+ importedEndpoints.push(updateEndpoint);
259
+ const body = getEndpointBody(updateEndpoint);
260
+ if (body) {
261
+ importedZodSchemas.push(body.zodSchema);
262
+ config.update = {
263
+ acl: getAclConfig(updateEndpoint, resolver.options),
264
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
265
+ mutation: updateEndpoint,
266
+ inputDefs: getInputsConfig(resolver, body)
267
+ };
268
+ }
269
+ }
270
+ const deleteEndpoint = extendedEndpoints.find((endpoint) => isDeleteEndpoint(endpoint, readAllEndpoint));
271
+ if (deleteEndpoint) {
272
+ importedEndpoints.push(deleteEndpoint);
273
+ const body = getEndpointBody(deleteEndpoint);
274
+ if (body) {
275
+ importedZodSchemas.push(body.zodSchema);
276
+ config.delete = {
277
+ acl: getAclConfig(deleteEndpoint, resolver.options),
278
+ mutation: deleteEndpoint
279
+ };
280
+ }
281
+ }
282
+ const bulkDeleteEndpoint = extendedEndpoints.find((endpoint) => isBulkDeleteEndpoint(endpoint, readAllEndpoint));
283
+ if (bulkDeleteEndpoint) {
284
+ importedEndpoints.push(bulkDeleteEndpoint);
285
+ const body = getEndpointBody(bulkDeleteEndpoint);
286
+ if (body) {
287
+ importedZodSchemas.push(body.zodSchema);
288
+ config.bulkDelete = {
289
+ acl: getAclConfig(bulkDeleteEndpoint, resolver.options),
290
+ schema: getImportedZodSchemaName(resolver, body.zodSchema),
291
+ mutation: bulkDeleteEndpoint,
292
+ inputDefs: getInputsConfig(resolver, body)
293
+ };
294
+ }
295
+ }
296
+ return config;
297
+ });
298
+ const modelsImports = getModelsImports({
299
+ resolver,
300
+ tag,
301
+ zodSchemas: importedZodSchemas
302
+ });
303
+ const queriesImports = getQueriesImports({
304
+ tag,
305
+ endpoints: importedEndpoints,
306
+ options: resolver.options
307
+ });
308
+ const infiniteQueriesImports = resolver.options.infiniteQueries ? getInfiniteQueriesImports({
309
+ tag,
310
+ endpoints: importedInfiniteEndpoints,
311
+ options: resolver.options
312
+ }) : [];
313
+ const aclImports = getAclImports({
314
+ tag,
315
+ endpoints: importedEndpoints.filter((endpoint) => endpoint.acl),
316
+ options: resolver.options
317
+ });
318
+ return {
319
+ configs: configs.filter(Boolean),
320
+ hasZodImport,
321
+ modelsImports,
322
+ queriesImports: mergeImports(resolver.options, queriesImports, infiniteQueriesImports),
323
+ aclImports
324
+ };
325
+ }
326
+ function resolveBuilderConfigNames(endpoints) {
327
+ const sortedEndpoints = endpoints.map((endpoint) => ({
328
+ ...endpoint,
329
+ namePathSegments: endpoint.pathSegments.filter((segment) => !isPathSegmentParam(segment))
330
+ })).toSorted((a, b) => a.namePathSegments.length - b.namePathSegments.length);
331
+ const namedEndpoints = {};
332
+ for (const endpoint of sortedEndpoints) {
333
+ const namePathSegments = endpoint.namePathSegments;
334
+ let name = namePathSegments.length > 0 ? `${kebabToCamel(namePathSegments.pop())}${capitalize(BUILD_CONFIG_SUFFIX)}` : BUILD_CONFIG_SUFFIX;
335
+ while (namedEndpoints[name]) {
336
+ if (namePathSegments.length === 0) throw new Error(`Can't uniquely resolve builder config name: ${name}`);
337
+ name = `${kebabToCamel(namePathSegments.pop())}${capitalize(name)}`;
338
+ }
339
+ namedEndpoints[name] = endpoint;
340
+ }
341
+ return namedEndpoints;
342
+ }
343
+ function getAclConfig(endpoint, options) {
344
+ return options.acl && endpoint.acl ? getImportedAbilityFunctionName(endpoint, options) : void 0;
345
+ }
346
+ function getInputsConfig(resolver, endpointParameter) {
347
+ if (!endpointParameter) return;
348
+ let schema;
349
+ if (endpointParameter.type === "Body") schema = endpointParameter.bodyObject?.content?.[JSON_APPLICATION_FORMAT]?.schema;
350
+ else schema = endpointParameter.parameterObject?.schema;
351
+ if (!schema) return;
352
+ const schemaObj = resolver.resolveObject(schema);
353
+ const inputs = Object.keys(schemaObj?.properties ?? {}).reduce((acc, key) => ({
354
+ ...acc,
355
+ [key]: true
356
+ }), {});
357
+ return {
358
+ schema: getImportedZodSchemaName(resolver, endpointParameter.zodSchema),
359
+ options: { inputs }
360
+ };
361
+ }
362
+ function resolveReadAllItemZodSchema(resolver, endpoint, itemSchema, itemsPropertyKey) {
363
+ if (isReferenceObject(itemSchema)) return resolver.getZodSchemaNameByRef(itemSchema.$ref);
364
+ if (isNamedZodSchema(endpoint.response)) return `${getImportedZodSchemaName(resolver, endpoint.response)}.shape.${itemsPropertyKey}.element`;
365
+ return ANY_SCHEMA;
366
+ }
367
+ function getColumnsConfig(resolver, endpoint) {
368
+ const endpointResponse = endpoint.responseObject;
369
+ if (!endpointResponse) return;
370
+ const schema = endpointResponse.content?.[JSON_APPLICATION_FORMAT]?.schema;
371
+ if (!schema) return;
372
+ const properties = getSchemaProperties(resolver, schema);
373
+ const arrayPropertyKeys = Object.keys(properties).filter((key) => resolver.resolveObject(properties[key]).type === "array");
374
+ arrayPropertyKeys.sort((a, b) => {
375
+ const aIndex = resolver.options.dataResponseParamNames.indexOf(a);
376
+ const bIndex = resolver.options.dataResponseParamNames.indexOf(b);
377
+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
378
+ if (aIndex !== -1) return -1;
379
+ if (bIndex !== -1) return 1;
380
+ return a.localeCompare(b);
381
+ });
382
+ const propertyKey = arrayPropertyKeys[0];
383
+ if (!propertyKey) return;
384
+ const dataSchemaObj = resolver.resolveObject(properties[propertyKey]);
385
+ if (!dataSchemaObj || dataSchemaObj.type !== "array") return;
386
+ const itemSchema = dataSchemaObj.items;
387
+ const itemSchemaObj = resolver.resolveObject(itemSchema);
388
+ if (!itemSchemaObj) return;
389
+ const zodSchema = resolveReadAllItemZodSchema(resolver, endpoint, itemSchema, propertyKey);
390
+ const columns = Object.keys(itemSchemaObj?.properties ?? {}).reduce((acc, key) => ({
391
+ ...acc,
392
+ [key]: true
393
+ }), {});
394
+ const sortableEnumSchemaName = endpoint.parameters.find((param) => param.parameterSortingEnumSchemaName)?.parameterSortingEnumSchemaName;
395
+ return {
396
+ columns: {
397
+ schema: getImportedZodSchemaName(resolver, zodSchema),
398
+ options: {
399
+ columns,
400
+ sortable: sortableEnumSchemaName ? getImportedZodSchemaName(resolver, sortableEnumSchemaName) : void 0
401
+ }
402
+ },
403
+ zodSchema,
404
+ sortableEnumSchemaName
405
+ };
406
+ }
407
+ function getSchemaProperties(resolver, schema) {
408
+ const schemaObj = resolver.resolveObject(schema);
409
+ if (schemaObj.properties) return schemaObj.properties;
410
+ else if ("allOf" in schemaObj && schemaObj.allOf) return schemaObj.allOf.reduce((acc, cur) => ({
411
+ ...acc,
412
+ ...getSchemaProperties(resolver, cur)
413
+ }), {});
414
+ return {};
415
+ }
416
+ //#endregion
417
+ //#region src/generators/const/queries.const.ts
418
+ const QUERY_HOOKS = {
419
+ query: "useQuery",
420
+ infiniteQuery: "useInfiniteQuery",
421
+ mutation: "useMutation"
422
+ };
423
+ const QUERY_IMPORT = {
424
+ bindings: [
425
+ QUERY_HOOKS.query,
426
+ QUERY_HOOKS.infiniteQuery,
427
+ QUERY_HOOKS.mutation
428
+ ],
429
+ from: "@tanstack/react-query"
430
+ };
431
+ const QUERIES_MODULE_NAME = "moduleName";
432
+ //#endregion
433
+ //#region src/generators/generate/generateConfigs.ts
434
+ function generateConfigs(generateTypeParams) {
435
+ const { configs, hasZodImport, modelsImports, queriesImports, aclImports } = getBuilderConfigs(generateTypeParams);
436
+ if (configs.length === 0) return;
437
+ const { resolver, tag } = generateTypeParams;
438
+ const endpoints = configs.flatMap((config) => [
439
+ config.create?.mutation,
440
+ config.update?.mutation,
441
+ config.delete?.mutation,
442
+ config.bulkDelete?.mutation
443
+ ]).filter((m) => typeof m !== "string" && m !== void 0);
444
+ const hasMutation = endpoints.length > 0;
445
+ const hasAclCheck = resolver.options.checkAcl && endpoints.some((e) => e.acl);
446
+ const hasMutationEffects = resolver.options.mutationEffects && hasMutation;
447
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError && hasMutation;
448
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
449
+ const nativeClient = resolver.options.restClient === "native";
450
+ const hasAxiosDefaultImport = !nativeClient && endpoints.some((e) => e.mediaUpload);
451
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasAxiosDefaultImport);
452
+ const axiosImport = {
453
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
454
+ bindings: [],
455
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
456
+ from: "axios"
457
+ };
458
+ const nativeImport = {
459
+ bindings: [],
460
+ typeBindings: nativeClient && hasAxiosRequestConfig ? [getRequestConfigTypeName("native")] : [],
461
+ from: REST_PACKAGE_IMPORT_PATH
462
+ };
463
+ const appRestClientImport = {
464
+ bindings: [APP_REST_CLIENT_NAME],
465
+ from: getAppRestClientImportPath(resolver.options)
466
+ };
467
+ const endpointsImports = getEndpointsImports({
468
+ tag,
469
+ endpoints,
470
+ options: resolver.options
471
+ });
472
+ const queryImport = {
473
+ bindings: [QUERY_HOOKS.mutation],
474
+ from: "@tanstack/react-query"
475
+ };
476
+ const queryTypesImport = {
477
+ bindings: [...hasMutationDefaultOnError ? ["OpenApiQueryConfig"] : []],
478
+ typeBindings: [QUERY_OPTIONS_TYPES.mutation],
479
+ from: getQueryTypesImportPath(resolver.options)
480
+ };
481
+ const mutationEffectsImport = {
482
+ bindings: [MUTATION_EFFECTS.hookName],
483
+ typeBindings: [MUTATION_EFFECTS.optionsType],
484
+ from: resolver.options.mutationEffectsImportPath
485
+ };
486
+ const queryModulesImport = {
487
+ bindings: [QUERY_MODULE_ENUM],
488
+ from: getQueryModulesImportPath(resolver.options)
489
+ };
490
+ const aclCheckImport = {
491
+ bindings: [ACL_CHECK_HOOK],
492
+ from: resolver.options.aclCheckImportPath
493
+ };
494
+ const hasDynamicInputsImport = configs.some((config) => config.readAll.filters || config.create?.inputDefs || config.update?.inputDefs);
495
+ const dynamicInputsImport = {
496
+ bindings: [BUILDERS_UTILS.dynamicInputs],
497
+ from: resolver.options.dynamicInputsImportPath
498
+ };
499
+ const hasDynamicColumnsImport = configs.some((config) => config.readAll.columns);
500
+ const dynamicColumnsImport = {
501
+ bindings: [BUILDERS_UTILS.dynamicColumns],
502
+ from: resolver.options.dynamicColumnsImportPath
503
+ };
504
+ const lines = [];
505
+ if (hasAxiosImport) lines.push(renderImport$3(axiosImport));
506
+ if (nativeImport.typeBindings?.length) lines.push(renderImport$3(nativeImport));
507
+ if (nativeClient && endpoints.some((endpoint) => endpoint.mediaUpload)) lines.push(renderImport$3(appRestClientImport));
508
+ if (hasZodImport) lines.push(renderImport$3(ZOD_IMPORT));
509
+ if (hasDynamicInputsImport) lines.push(renderImport$3(dynamicInputsImport));
510
+ if (hasDynamicColumnsImport) lines.push(renderImport$3(dynamicColumnsImport));
511
+ for (const modelsImport of modelsImports) lines.push(renderImport$3(modelsImport));
512
+ for (const queriesImport of queriesImports) lines.push(renderImport$3(queriesImport));
513
+ for (const endpointsImport of endpointsImports) lines.push(renderImport$3(endpointsImport));
514
+ if (hasMutation) {
515
+ lines.push(renderImport$3(queryImport));
516
+ lines.push(renderImport$3(queryTypesImport));
517
+ if (hasMutationEffects) {
518
+ lines.push(renderImport$3(queryModulesImport));
519
+ lines.push(renderImport$3(mutationEffectsImport));
520
+ }
521
+ if (hasAclCheck) lines.push(renderImport$3(aclCheckImport));
522
+ }
523
+ for (const aclImport of aclImports) lines.push(renderImport$3(aclImport));
524
+ lines.push("");
525
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
526
+ type: "configs",
527
+ tag,
528
+ options: resolver.options
529
+ })} {`);
530
+ for (const config of configs) {
531
+ lines.push(renderBuilderConfig(config, generateTypeParams));
532
+ lines.push("");
533
+ }
534
+ if (resolver.options.tsNamespaces) lines.push("}");
535
+ return lines.join("\n").trimEnd() + "\n";
536
+ }
537
+ function renderImport$3(importData) {
538
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
539
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
540
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
541
+ }
542
+ function renderInputsConfig(inputsConfig) {
543
+ const lines = [];
544
+ lines.push("{");
545
+ lines.push(` schema: ${inputsConfig.schema},`);
546
+ lines.push(" options: {");
547
+ lines.push(" inputs: {");
548
+ for (const key of Object.keys(inputsConfig.options.inputs)) lines.push(` ${key}: true,`);
549
+ lines.push(" },");
550
+ lines.push(" },");
551
+ lines.push("}");
552
+ return lines.join("\n");
553
+ }
554
+ function renderColumnsConfig(columnsConfig) {
555
+ const lines = [];
556
+ lines.push("{");
557
+ lines.push(` schema: ${columnsConfig.schema},`);
558
+ lines.push(" options: {");
559
+ lines.push(" columns: {");
560
+ for (const key of Object.keys(columnsConfig.options.columns)) lines.push(` ${key}: true,`);
561
+ lines.push(" },");
562
+ if (columnsConfig.options.sortable) lines.push(` sortable: ${columnsConfig.options.sortable},`);
563
+ lines.push(" },");
564
+ lines.push("}");
565
+ return lines.join("\n");
566
+ }
567
+ function renderMutationContent(resolver, endpoint, tag) {
568
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
569
+ const hasMutationEffects = resolver.options.mutationEffects;
570
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError;
571
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
572
+ const endpointTag = getEndpointTag(endpoint, resolver.options);
573
+ const endpointParams = mapEndpointParamsToFunctionParams(resolver, endpoint, {
574
+ includeFileParam: true,
575
+ modelNamespaceTag: endpointTag
576
+ });
577
+ const endpointParamsStr = endpointParams.map((p) => `${p.name}${p.required ? "" : "?"}: ${p.type}`).join("; ");
578
+ const destructuredMutationArgs = endpointParams.map((p) => p.name).join(", ");
579
+ const resolvedEndpointArgs = mapEndpointParamsToFunctionParams(resolver, endpoint, { modelNamespaceTag: endpointTag }).map((p) => p.name).join(", ");
580
+ const endpointFunction = getImportedEndpointName(endpoint, resolver.options);
581
+ const mutationVariablesType = endpoint.mediaUpload ? `{ ${endpointParamsStr}${endpointParamsStr ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void }` : `{ ${endpointParamsStr} }`;
582
+ const lines = [];
583
+ lines.push(`(options?: AppMutationOptions<typeof ${endpointFunction}, ${mutationVariablesType}>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, config?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
584
+ if (hasMutationDefaultOnError) lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
585
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<${QUERY_MODULE_ENUM}.${endpointTag}>({ currentModule: ${QUERY_MODULE_ENUM}.${tag} });`);
586
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
587
+ lines.push("");
588
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
589
+ const mutationFnArg = destructuredMutationArgs ? `{ ${destructuredMutationArgs}${endpoint.mediaUpload ? `${destructuredMutationArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
590
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => {`);
591
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, void 0, " "));
592
+ if (endpoint.mediaUpload) lines.push(...renderMediaUploadMutationBody({
593
+ resolver,
594
+ endpointFunction,
595
+ resolvedEndpointArgs
596
+ }).map((line) => ` ${line}`));
597
+ else lines.push(` return ${endpointFunction}(${destructuredMutationArgs}${hasAxiosRequestConfig ? `${destructuredMutationArgs ? ", " : ""}config` : ""});`);
598
+ lines.push(" },");
599
+ lines.push(" ...options,");
600
+ if (hasMutationDefaultOnError) lines.push(" onError: options?.onError ?? queryConfig.onError,");
601
+ if (hasMutationEffects) {
602
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
603
+ lines.push(" await runMutationEffects(resData, variables, options);");
604
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
605
+ lines.push(" },");
606
+ }
607
+ lines.push(" });");
608
+ lines.push("}");
609
+ return lines.map((line) => " " + line).join("\n").trimStart();
610
+ }
611
+ function renderBuilderConfig(config, params) {
612
+ const { resolver, tag } = params;
613
+ const lines = [];
614
+ lines.push(`export const ${config.name} = {`);
615
+ lines.push(" meta: {");
616
+ lines.push(` title: "${config.title}",`);
617
+ lines.push(" },");
618
+ lines.push(" readAll: {");
619
+ if (config.readAll.acl) lines.push(` acl: ${config.readAll.acl},`);
620
+ lines.push(` schema: ${config.readAll.columns.schema},`);
621
+ lines.push(` paginated: ${config.readAll.paginated},`);
622
+ if (config.readAll.infinite) lines.push(` infinite: ${config.readAll.infinite},`);
623
+ if (config.readAll.filters) {
624
+ lines.push(" filters: {");
625
+ lines.push(` schema: ${config.readAll.filters.schema},`);
626
+ lines.push(` filterDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.readAll.filters)})`);
627
+ lines.push(" },");
628
+ }
629
+ lines.push(` columns: ${BUILDERS_UTILS.dynamicColumns}(${renderColumnsConfig(config.readAll.columns)}),`);
630
+ lines.push(" },");
631
+ if (config.read) {
632
+ lines.push(" read: {");
633
+ if (config.read.acl) lines.push(` acl: ${config.read.acl},`);
634
+ lines.push(` schema: ${config.read.schema},`);
635
+ lines.push(` query: ${config.read.query},`);
636
+ lines.push(" },");
637
+ }
638
+ if (config.create) {
639
+ lines.push(" create: {");
640
+ if (config.create.acl) lines.push(` acl: ${config.create.acl},`);
641
+ if (config.create.schema) lines.push(` schema: ${config.create.schema},`);
642
+ lines.push(` mutation: ${typeof config.create.mutation === "string" ? config.create.mutation : renderMutationContent(resolver, config.create.mutation, tag)},`);
643
+ if (config.create.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.create.inputDefs)})`);
644
+ lines.push(" },");
645
+ }
646
+ if (config.update) {
647
+ lines.push(" update: {");
648
+ if (config.update.acl) lines.push(` acl: ${config.update.acl},`);
649
+ if (config.update.schema) lines.push(` schema: ${config.update.schema},`);
650
+ lines.push(` mutation: ${typeof config.update.mutation === "string" ? config.update.mutation : renderMutationContent(resolver, config.update.mutation, tag)},`);
651
+ if (config.update.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.update.inputDefs)})`);
652
+ lines.push(" },");
653
+ }
654
+ if (config.delete) {
655
+ lines.push(" delete: {");
656
+ if (config.delete.acl) lines.push(` acl: ${config.delete.acl},`);
657
+ lines.push(` mutation: ${typeof config.delete.mutation === "string" ? config.delete.mutation : renderMutationContent(resolver, config.delete.mutation, tag)},`);
658
+ lines.push(" },");
659
+ }
660
+ if (config.bulkDelete) {
661
+ lines.push(" bulkDelete: {");
662
+ if (config.bulkDelete.acl) lines.push(` acl: ${config.bulkDelete.acl},`);
663
+ if (config.bulkDelete.schema) lines.push(` schema: ${config.bulkDelete.schema},`);
664
+ lines.push(` mutation: ${typeof config.bulkDelete.mutation === "string" ? config.bulkDelete.mutation : renderMutationContent(resolver, config.bulkDelete.mutation, tag)},`);
665
+ if (config.bulkDelete.inputDefs) lines.push(` inputDefs: ${BUILDERS_UTILS.dynamicInputs}(${renderInputsConfig(config.bulkDelete.inputDefs)})`);
666
+ lines.push(" },");
667
+ }
668
+ lines.push("};");
669
+ return lines.join("\n");
670
+ }
671
+ //#endregion
672
+ //#region src/generators/generate/generateEndpoints.ts
673
+ function generateEndpoints({ resolver, data, tag }) {
674
+ const nativeContent = resolver.getNativeRenderedEndpoints?.(tag);
675
+ if (nativeContent) return nativeContent;
676
+ if (shouldInlineEndpointsForTag(tag, resolver.options)) return;
677
+ const endpoints = data.get(tag)?.endpoints;
678
+ if (!endpoints || endpoints.length === 0) return;
679
+ const appRestClientImport = {
680
+ bindings: [APP_REST_CLIENT_NAME],
681
+ from: getAppRestClientImportPath(resolver.options)
682
+ };
683
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
684
+ const hasGetEndpoints = endpoints.some((endpoint) => endpoint.method === "get");
685
+ const nativeClient = resolver.options.restClient === "native";
686
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasGetEndpoints);
687
+ const axiosImport = {
688
+ bindings: [],
689
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
690
+ from: AXIOS_IMPORT.from
691
+ };
692
+ const nativeImport = {
693
+ bindings: [],
694
+ typeBindings: nativeClient && (hasAxiosRequestConfig || hasGetEndpoints) ? [getRequestConfigTypeName("native")] : [],
695
+ from: REST_PACKAGE_IMPORT_PATH
696
+ };
697
+ const generateParse = resolver.options.parseRequestParams;
698
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
699
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
700
+ const endpointResponseSchemas = endpoints.map((endpoint) => endpoint.response);
701
+ const zodSchemas = getUniqueArray([...endpointResponseSchemas, ...generateParse ? endpointParamsParseSchemas : []]);
702
+ const hasZodImport = zodSchemas.some((schema) => !isNamedZodSchema(schema));
703
+ const hasZodExtendedImport = resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
704
+ const zodExtendedImport = {
705
+ bindings: [ZOD_EXTENDED.namespace],
706
+ from: resolver.options.zodImportPath
707
+ };
708
+ const modelsImports = getModelsImports({
709
+ resolver,
710
+ tag,
711
+ zodSchemas: zodSchemas.filter(isNamedZodSchema),
712
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
713
+ });
714
+ const lines = [];
715
+ lines.push(renderImport$2(appRestClientImport));
716
+ if (hasAxiosImport) lines.push(renderImport$2(axiosImport));
717
+ if (nativeImport.typeBindings?.length) lines.push(renderImport$2(nativeImport));
718
+ if (hasZodImport) lines.push(renderImport$2(ZOD_IMPORT));
719
+ if (hasZodExtendedImport) lines.push(renderImport$2(zodExtendedImport));
720
+ for (const modelsImport of modelsImports) lines.push(renderImport$2(modelsImport));
721
+ lines.push("");
722
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
723
+ type: "endpoints",
724
+ tag,
725
+ options: resolver.options
726
+ })} {`);
727
+ for (const endpoint of endpoints) {
728
+ const endpointParamOptions = { modelNamespaceTag: tag };
729
+ const endpointParams = renderEndpointParams$1(resolver, endpoint, endpointParamOptions);
730
+ renderEndpointArgs$1(resolver, endpoint, endpointParamOptions);
731
+ const endpointBody = getEndpointBody(endpoint);
732
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
733
+ const endpointConfig = renderEndpointConfig(resolver, endpoint, tag);
734
+ const hasRequestConfigParam = hasAxiosRequestConfig || endpoint.method === "get";
735
+ lines.push(`export const ${getEndpointName(endpoint)} = (${endpointParams}${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType$1(resolver)}` : ""}) => {`);
736
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
737
+ lines.push(` ${renderRequestInfo(resolver, endpoint, tag)},`);
738
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
739
+ if (endpointBody) lines.push(` ${generateParse ? renderEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
740
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
741
+ lines.push(` ${endpointConfig}`);
742
+ lines.push(" )");
743
+ lines.push("};");
744
+ }
745
+ if (resolver.options.tsNamespaces) lines.push("}");
746
+ return lines.join("\n").trimEnd() + "\n";
747
+ }
748
+ function renderRequestInfo(resolver, endpoint, tag) {
749
+ return `{ resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, (resolver.options.modelsInCommon || resolver.options.modelsInModules) && resolver.options.splitByTags ? tag : void 0)} }`;
750
+ }
751
+ function getRequestConfigType$1(resolver) {
752
+ return `${getRequestConfigTypeName(resolver.options.restClient)} & { allowInvalidResponseData?: boolean }`;
753
+ }
754
+ function renderImport$2(importData) {
755
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
756
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
757
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
758
+ }
759
+ function renderEndpointParams$1(resolver, endpoint, options) {
760
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}, `).join("");
761
+ }
762
+ function renderEndpointArgs$1(resolver, endpoint, options) {
763
+ return mapEndpointParamsToFunctionParams(resolver, endpoint, options).map((param) => param.name).join(", ");
764
+ }
765
+ function renderEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
766
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
767
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${getSortingPresenceChain$1(resolver, param)}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
768
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
769
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
770
+ }
771
+ function getSortingPresenceChain$1(resolver, param) {
772
+ const zodSchemaCode = resolver.getCodeByZodSchemaName(param.zodSchema) ?? param.zodSchema;
773
+ if (zodSchemaCode.includes(".nullish()")) return ".nullish()";
774
+ if (zodSchemaCode.includes(".nullable()")) return ".nullable()";
775
+ return !(param.parameterObject ?? param.bodyObject)?.required ? ".optional()" : "";
776
+ }
777
+ function renderEndpointConfig(resolver, endpoint, modelNamespaceTag) {
778
+ const endpointConfig = getEndpointConfig(endpoint);
779
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
780
+ const needsBlobConfig = endpoint.mediaDownload || endpoint.response === "z.instanceof(Blob)";
781
+ if (Object.keys(endpointConfig).length === 0 && !needsBlobConfig) return hasRequestConfigParam ? AXIOS_REQUEST_CONFIG_NAME : "";
782
+ const lines = [];
783
+ lines.push("{");
784
+ if (hasRequestConfigParam) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
785
+ if (endpointConfig.params) {
786
+ lines.push(" params: {");
787
+ for (const param of endpointConfig.params) {
788
+ const value = resolver.options.parseRequestParams ? renderEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
789
+ lines.push(` ${param.name}: ${value},`);
790
+ }
791
+ lines.push(" },");
792
+ }
793
+ if (endpointConfig.headers) {
794
+ lines.push(" headers: {");
795
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
796
+ lines.push(" },");
797
+ }
798
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
799
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
800
+ lines.push("}");
801
+ return lines.join("\n ");
802
+ }
803
+ //#endregion
804
+ //#region src/generators/utils/generate/generate.lazy.utils.ts
805
+ const ONCE_HELPER_LINES = [
806
+ "const once = <T>(create: () => T) => {",
807
+ " let value: T | undefined;",
808
+ " return () => (value ??= create());",
809
+ "};"
810
+ ];
811
+ const isIdentifierChar = (char) => /[A-Za-z0-9_$]/.test(char);
812
+ const findLiteralEnd = (code, start, quote) => {
813
+ let index = start + 1;
814
+ while (index < code.length) {
815
+ const char = code[index];
816
+ if (char === "\\") {
817
+ index += 2;
818
+ continue;
819
+ }
820
+ index += 1;
821
+ if (char === quote) break;
822
+ }
823
+ return Math.min(index, code.length);
824
+ };
825
+ const findRegexEnd = (code, start) => {
826
+ let escaped = false;
827
+ let characterClass = false;
828
+ for (let index = start + 1; index < code.length; index += 1) {
829
+ const char = code[index];
830
+ if (escaped) {
831
+ escaped = false;
832
+ continue;
833
+ }
834
+ if (char === "\\") {
835
+ escaped = true;
836
+ continue;
837
+ }
838
+ if (char === "[") characterClass = true;
839
+ if (char === "]") characterClass = false;
840
+ if (char === "/" && !characterClass) return index + 1;
841
+ }
842
+ return code.length;
843
+ };
844
+ /**
845
+ * Rewrites bare references to sibling schemas (`PetSchema`) into factory calls (`PetSchema()`).
846
+ * Member accesses (`CommonModels.PetSchema`, `.enum`), object keys and literal values are left alone.
847
+ */
848
+ function callLazySchemaReferences(code, schemaNames) {
849
+ let output = "";
850
+ let index = 0;
851
+ while (index < code.length) {
852
+ const char = code[index];
853
+ if (char === "\"" || char === "'" || char === "`") {
854
+ const end = findLiteralEnd(code, index, char);
855
+ output += code.slice(index, end);
856
+ index = end;
857
+ continue;
858
+ }
859
+ if (char === "/" && output.trimEnd().endsWith(".regex(")) {
860
+ const end = findRegexEnd(code, index);
861
+ output += code.slice(index, end);
862
+ index = end;
863
+ continue;
864
+ }
865
+ if (isIdentifierChar(char)) {
866
+ let end = index + 1;
867
+ while (end < code.length && isIdentifierChar(code[end])) end += 1;
868
+ const identifier = code.slice(index, end);
869
+ const isMemberAccess = output.endsWith(".");
870
+ const isObjectKey = code.slice(end).trimStart().startsWith(":");
871
+ output += schemaNames.has(identifier) && !isMemberAccess && !isObjectKey ? `${identifier}()` : identifier;
872
+ index = end;
873
+ continue;
874
+ }
875
+ output += char;
876
+ index += 1;
877
+ }
878
+ return output;
879
+ }
880
+ //#endregion
881
+ //#region src/generators/generate/generateModels.ts
882
+ function generateModels({ resolver, data, tag }) {
883
+ const nativeContent = resolver.getNativeRenderedModels?.(tag);
884
+ if (nativeContent) return nativeContent;
885
+ if (resolver.options.modelsInCommon && resolver.options.splitByTags && tag !== resolver.options.defaultTag) return renderModelsProxy({
886
+ resolver,
887
+ data,
888
+ tag
889
+ });
890
+ const zodSchemas = data.get(tag)?.zodSchemas;
891
+ if (!zodSchemas || Object.keys(zodSchemas).length === 0) return;
892
+ const refZodSchemas = [];
893
+ for (const zodSchema of Object.keys(zodSchemas)) {
894
+ const refs = getZodSchemaRefs(resolver, zodSchema);
895
+ for (const ref of refs) if (!zodSchemas[ref]) refZodSchemas.push(ref);
896
+ }
897
+ const modelsImports = getModelsImports({
898
+ resolver,
899
+ tag,
900
+ zodSchemas: refZodSchemas
901
+ });
902
+ const zodSchemasData = {};
903
+ for (const [key, code] of Object.entries(zodSchemas)) {
904
+ const schemaRef = resolver.getRefByZodSchemaName(key);
905
+ zodSchemasData[key] = {
906
+ code: resolver.options.modelsInModules ? code.replace(/\b[A-Z][A-Za-z0-9]*Models\./g, "") : code,
907
+ isCircular: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
908
+ isEnum: isEnumZodSchema(code),
909
+ schemaObj: resolver.getZodSchemaObj(key)
910
+ };
911
+ }
912
+ const lines = [];
913
+ lines.push(renderImport$1(ZOD_IMPORT));
914
+ for (const modelsImport of modelsImports) lines.push(renderImport$1(modelsImport));
915
+ lines.push("");
916
+ if (resolver.options.lazySchemas && resolver.options.tsNamespaces) return renderLazyModels({
917
+ resolver,
918
+ tag,
919
+ zodSchemasData,
920
+ lines
921
+ });
922
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${getNamespaceName({
923
+ type: "models",
924
+ tag,
925
+ options: resolver.options
926
+ })} {`);
927
+ for (const [name, zodSchema] of Object.entries(zodSchemasData)) {
928
+ lines.push(renderModelJsDocs({
929
+ name,
930
+ zodSchema,
931
+ tag,
932
+ resolver
933
+ }));
934
+ const inferredTypeName = getZodSchemaInferedTypeName(name, resolver.options);
935
+ if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
936
+ const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
937
+ const schemaCode = resolver.options.compileSchemas && !zodSchema.isCircular ? `z.compile(${zodSchema.code})` : zodSchema.code;
938
+ lines.push(`export const ${name}${typeAnnotation} = ${schemaCode};`);
939
+ if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
940
+ if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
941
+ lines.push("");
942
+ }
943
+ if (resolver.options.tsNamespaces) lines.push("}");
944
+ return lines.join("\n").trimEnd() + "\n";
945
+ }
946
+ function renderLazyModels({ resolver, tag, zodSchemasData, lines }) {
947
+ const namespace = getNamespaceName({
948
+ type: "models",
949
+ tag,
950
+ options: resolver.options
951
+ });
952
+ const schemaNames = new Set(Object.keys(zodSchemasData));
953
+ const members = [];
954
+ const types = [];
955
+ lines.push(...ONCE_HELPER_LINES, "");
956
+ for (const [name, zodSchema] of Object.entries(zodSchemasData)) {
957
+ const inferredTypeName = getZodSchemaInferedTypeName(name, resolver.options);
958
+ const typeAnnotation = zodSchema.isCircular ? `: () => z.ZodObject<z.ZodRawShape> & z.ZodType<${namespace}.${inferredTypeName}>` : "";
959
+ const schemaCode = resolver.options.compileSchemas && !zodSchema.isCircular ? `z.compile(${zodSchema.code})` : zodSchema.code;
960
+ lines.push(`const ${name}${typeAnnotation} = once(() => ${callLazySchemaReferences(schemaCode, schemaNames)});`);
961
+ members.push(...indent(renderModelJsDocs({
962
+ name,
963
+ zodSchema,
964
+ tag,
965
+ resolver
966
+ }).split("\n")));
967
+ members.push(...renderLazyMember(name, `${name}()`));
968
+ if (zodSchema.isCircular && zodSchema.schemaObj) types.push(` export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
969
+ else types.push(` export type ${inferredTypeName} = z.infer<typeof ${namespace}.${name}>;`);
970
+ if (zodSchema.isEnum) {
971
+ lines.push(`const ${inferredTypeName} = once(() => ${name}().enum);`);
972
+ members.push(...renderLazyMember(inferredTypeName, `${inferredTypeName}()`));
973
+ }
974
+ }
975
+ lines.push("");
976
+ lines.push(`export const ${namespace} = {`, ...members, "};");
977
+ lines.push(`export declare namespace ${namespace} {`, ...types, "}");
978
+ return lines.join("\n") + "\n";
979
+ }
980
+ function renderLazyMember(name, value) {
981
+ return [
982
+ ` get ${name}() {`,
983
+ ` return ${value};`,
984
+ ` },`
985
+ ];
986
+ }
987
+ function indent(lines) {
988
+ return lines.map((line) => ` ${line}`);
989
+ }
990
+ function renderSchemaType(schema, resolver) {
991
+ if (isReferenceObject(schema)) {
992
+ const schemaName = resolver.getZodSchemaNameByRef(schema.$ref);
993
+ return schemaName ? getZodSchemaInferedTypeName(schemaName, resolver.options) : "unknown";
994
+ }
995
+ const composite = schema.allOf ?? schema.oneOf ?? schema.anyOf;
996
+ if (composite?.length) {
997
+ const separator = schema.allOf ? " & " : " | ";
998
+ return addNullable(schema, composite.map((part) => renderSchemaType(part, resolver)).join(separator));
999
+ }
1000
+ if (schema.enum?.length) return addNullable(schema, schema.enum.map((value) => JSON.stringify(value)).join(" | "));
1001
+ if (schema.type === "array") return addNullable(schema, `Array<${schema.items ? renderSchemaType(schema.items, resolver) : "unknown"}>`);
1002
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
1003
+ const properties = Object.entries(schema.properties ?? {}).map(([name, property]) => {
1004
+ const isRequired = resolver.options.withImplicitRequiredProps || schema.required?.includes(name);
1005
+ const hasDefault = !isReferenceObject(property) && property.default !== void 0;
1006
+ const optional = isRequired || hasDefault ? "" : "?";
1007
+ const propertyType = renderSchemaType(property, resolver);
1008
+ const outputType = resolver.options.replaceOptionalWithNullish && optional && (isReferenceObject(property) || !property.nullable) ? `${propertyType} | null` : propertyType;
1009
+ return `${wrapWithQuotesIfNeeded(name)}${optional}: ${outputType}`;
1010
+ });
1011
+ if (schema.additionalProperties) {
1012
+ const valueType = typeof schema.additionalProperties === "object" ? renderSchemaType(schema.additionalProperties, resolver) : "unknown";
1013
+ properties.push(`[key: string]: ${valueType}`);
1014
+ }
1015
+ return addNullable(schema, `{ ${properties.join("; ")} }`);
1016
+ }
1017
+ const primitiveType = schema.type;
1018
+ return addNullable(schema, primitiveType === "string" ? "string" : primitiveType === "number" || primitiveType === "integer" ? "number" : primitiveType === "boolean" ? "boolean" : primitiveType === "null" ? "null" : "unknown");
1019
+ }
1020
+ function addNullable(schema, type) {
1021
+ return schema.nullable && type !== "null" ? `${type} | null` : type;
1022
+ }
1023
+ function renderModelsProxy({ resolver, data, tag }) {
1024
+ const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
1025
+ const schemaNames = getUsedSchemaNames({
1026
+ resolver,
1027
+ endpoints: data.get(tag)?.endpoints ?? []
1028
+ }).filter((schemaName) => Boolean(commonZodSchemas[schemaName]));
1029
+ if (schemaNames.length === 0) return;
1030
+ const modelsNamespace = getNamespaceName({
1031
+ type: "models",
1032
+ tag,
1033
+ options: resolver.options
1034
+ });
1035
+ const commonNamespace = getNamespaceName({
1036
+ type: "models",
1037
+ tag: resolver.options.defaultTag,
1038
+ options: resolver.options
1039
+ });
1040
+ const commonModelsPath = `${getImportPath(resolver.options)}${getTagImportPath({
1041
+ type: "models",
1042
+ tag: resolver.options.defaultTag,
1043
+ includeTagDir: true,
1044
+ options: resolver.options
1045
+ })}`;
1046
+ const inferredTypeNames = schemaNames.map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
1047
+ const enumInferredTypeNames = schemaNames.filter((schemaName) => isEnumZodSchema(commonZodSchemas[schemaName] ?? "")).map((schemaName) => getZodSchemaInferedTypeName(schemaName, resolver.options));
1048
+ if (resolver.options.tsNamespaces && resolver.options.lazySchemas) {
1049
+ const lines = [];
1050
+ lines.push(`import { ${commonNamespace} } from "${commonModelsPath}";`);
1051
+ lines.push("");
1052
+ lines.push(`export const ${modelsNamespace} = {`);
1053
+ for (const schemaName of schemaNames) lines.push(...renderLazyMember(schemaName, `${commonNamespace}.${schemaName}`));
1054
+ for (const enumName of enumInferredTypeNames) lines.push(...renderLazyMember(enumName, `${commonNamespace}.${enumName}`));
1055
+ lines.push("};");
1056
+ lines.push(`export declare namespace ${modelsNamespace} {`);
1057
+ for (const typeName of inferredTypeNames) lines.push(` export type ${typeName} = ${commonNamespace}.${typeName};`);
1058
+ lines.push("}");
1059
+ lines.push("");
1060
+ return lines.join("\n");
1061
+ }
1062
+ if (resolver.options.tsNamespaces) {
1063
+ const lines = [];
1064
+ lines.push(`import { ${commonNamespace} } from "${commonModelsPath}";`);
1065
+ lines.push("");
1066
+ lines.push(`export namespace ${modelsNamespace} {`);
1067
+ for (const schemaName of schemaNames) lines.push(` export const ${schemaName} = ${commonNamespace}.${schemaName};`);
1068
+ for (const typeName of inferredTypeNames) lines.push(` export type ${typeName} = ${commonNamespace}.${typeName};`);
1069
+ for (const enumName of enumInferredTypeNames) lines.push(` export const ${enumName} = ${commonNamespace}.${enumName};`);
1070
+ lines.push("}");
1071
+ lines.push("");
1072
+ return lines.join("\n");
1073
+ }
1074
+ const valueExports = getUniqueArray([...schemaNames, ...enumInferredTypeNames]);
1075
+ const lines = [];
1076
+ if (valueExports.length > 0) lines.push(`export { ${valueExports.join(", ")} } from "${commonModelsPath}";`);
1077
+ if (inferredTypeNames.length > 0) lines.push(`export type { ${inferredTypeNames.join(", ")} } from "${commonModelsPath}";`);
1078
+ return lines.join("\n") + "\n";
1079
+ }
1080
+ function getUsedSchemaNames({ resolver, endpoints }) {
1081
+ const usedSchemaNames = /* @__PURE__ */ new Set();
1082
+ const queue = [];
1083
+ const enqueue = (schemaName) => {
1084
+ if (!schemaName || !isNamedZodSchema(schemaName) || usedSchemaNames.has(schemaName)) return;
1085
+ usedSchemaNames.add(schemaName);
1086
+ queue.push(schemaName);
1087
+ };
1088
+ for (const endpoint of endpoints) {
1089
+ enqueue(endpoint.response);
1090
+ for (const error of endpoint.errors) enqueue(error.zodSchema);
1091
+ for (const param of endpoint.parameters) {
1092
+ enqueue(param.zodSchema);
1093
+ enqueue(param.parameterSortingEnumSchemaName);
1094
+ }
1095
+ }
1096
+ let queueIndex = 0;
1097
+ while (queueIndex < queue.length) {
1098
+ const schemaName = queue[queueIndex++];
1099
+ if (!schemaName) continue;
1100
+ const refs = getZodSchemaRefs(resolver, schemaName);
1101
+ for (const ref of refs) enqueue(ref);
1102
+ }
1103
+ return Array.from(usedSchemaNames);
1104
+ }
1105
+ function renderImport$1(importData) {
1106
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
1107
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
1108
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
1109
+ }
1110
+ function renderModelJsDocs({ name, zodSchema, tag, resolver }) {
1111
+ const lines = [
1112
+ `/** `,
1113
+ ` * ${name} `,
1114
+ ` * @type { ${getZodSchemaType(zodSchema)} }`
1115
+ ];
1116
+ const description = getZodSchemaDescription(zodSchema);
1117
+ if (description) lines.push(` * @description ${description.replace(/\n/g, "\n *")}`);
1118
+ const propertyDescriptions = getZodSchemaPropertyDescriptions(resolver, zodSchema, tag);
1119
+ if (propertyDescriptions) for (const [property, info] of Object.entries(propertyDescriptions)) lines.push(` * @property { ${info.type} } ${property} ${info.description.replace(/\n/g, "\n *")} `);
1120
+ lines.push(" */");
1121
+ return lines.join("\n");
1122
+ }
1123
+ //#endregion
1124
+ //#region src/generators/generate/generateQueries.ts
1125
+ const endpointParamMappingCache = /* @__PURE__ */ new WeakMap();
1126
+ const workspaceParamNamesCache = /* @__PURE__ */ new WeakMap();
1127
+ const endpointParamDescriptionCache = /* @__PURE__ */ new WeakMap();
1128
+ function generateQueries(params) {
1129
+ const { resolver, data, tag } = params;
1130
+ const nativeContent = resolver.getNativeRenderedQueries?.(tag);
1131
+ if (nativeContent) return nativeContent;
1132
+ const mutationScopeOption = resolver.options.mutationScope;
1133
+ if (mutationScopeOption && typeof mutationScopeOption === "object") {
1134
+ if ("include" in mutationScopeOption && "exclude" in mutationScopeOption) throw new Error("mutationScope cannot specify both 'include' and 'exclude'");
1135
+ }
1136
+ const inlineEndpoints = shouldInlineEndpointsForTag(tag, resolver.options);
1137
+ const endpoints = data.get(tag)?.endpoints;
1138
+ if (!endpoints || endpoints.length === 0) return;
1139
+ const endpointGroups = groupEndpoints(endpoints, resolver);
1140
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1141
+ const nativeClient = resolver.options.restClient === "native";
1142
+ const hasNativeMediaUpload = nativeClient && endpoints.some(({ mediaUpload }) => mediaUpload);
1143
+ const requestConfigType = getRequestConfigTypeName(resolver.options.restClient);
1144
+ const hasAxiosDefaultImport = !nativeClient && endpoints.some(({ mediaUpload }) => mediaUpload);
1145
+ const hasGetEndpoints = endpoints.some((endpoint) => endpoint.method === "get");
1146
+ const hasAxiosImport = !nativeClient && (hasAxiosRequestConfig || hasAxiosDefaultImport || hasGetEndpoints);
1147
+ const axiosImport = {
1148
+ defaultImport: hasAxiosDefaultImport ? AXIOS_DEFAULT_IMPORT_NAME : void 0,
1149
+ bindings: [],
1150
+ typeBindings: hasAxiosImport ? [AXIOS_REQUEST_CONFIG_TYPE] : [],
1151
+ from: AXIOS_IMPORT.from
1152
+ };
1153
+ const nativeTransportImport = {
1154
+ bindings: [],
1155
+ typeBindings: nativeClient ? [...hasAxiosRequestConfig || hasGetEndpoints ? [requestConfigType] : [], ...endpoints.some(({ mediaDownload }) => mediaDownload) ? [NATIVE_RESPONSE_TYPE] : []] : [],
1156
+ from: REST_PACKAGE_IMPORT_PATH
1157
+ };
1158
+ const { queryEndpoints, infiniteQueryEndpoints, mutationEndpoints, aclEndpoints } = endpointGroups;
1159
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError && mutationEndpoints.length > 0;
1160
+ const queryImport = {
1161
+ bindings: [
1162
+ ...resolver.options.prefetchQueries && queryEndpoints.length > 0 ? ["QueryClient"] : [],
1163
+ ...queryEndpoints.length > 0 ? [QUERY_HOOKS.query] : [],
1164
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_HOOKS.infiniteQuery] : [],
1165
+ ...mutationEndpoints.length > 0 ? [QUERY_HOOKS.mutation] : []
1166
+ ],
1167
+ from: QUERY_IMPORT.from
1168
+ };
1169
+ const hasMutationEffects = resolver.options.mutationEffects;
1170
+ const queryModulesImport = {
1171
+ bindings: [QUERY_MODULE_ENUM],
1172
+ from: getQueryModulesImportPath(resolver.options)
1173
+ };
1174
+ const hasMutationEffectsImport = hasMutationEffects && mutationEndpoints.length > 0;
1175
+ const mutationEffectsImport = {
1176
+ bindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.hookName] : []],
1177
+ typeBindings: [...mutationEndpoints.length > 0 ? [MUTATION_EFFECTS.optionsType] : []],
1178
+ from: resolver.options.mutationEffectsImportPath
1179
+ };
1180
+ const hasAclCheck = resolver.options.checkAcl && aclEndpoints.length > 0;
1181
+ const aclCheckImport = {
1182
+ bindings: [ACL_CHECK_HOOK],
1183
+ from: resolver.options.aclCheckImportPath
1184
+ };
1185
+ const queryTypesImport = {
1186
+ bindings: [...queryEndpoints.length > 0 || infiniteQueryEndpoints.length > 0 || hasMutationDefaultOnError ? ["OpenApiQueryConfig"] : []],
1187
+ typeBindings: [
1188
+ ...queryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.query] : [],
1189
+ ...resolver.options.infiniteQueries && infiniteQueryEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.infiniteQuery] : [],
1190
+ ...mutationEndpoints.length > 0 ? [QUERY_OPTIONS_TYPES.mutation] : []
1191
+ ],
1192
+ from: getQueryTypesImportPath(resolver.options)
1193
+ };
1194
+ const hasWorkspaceContext = resolver.options.workspaceContext && endpoints.some((endpoint) => getWorkspaceParamNames(resolver, endpoint).length > 0);
1195
+ const workspaceContextImport = {
1196
+ bindings: ["useWorkspaceContext"],
1197
+ from: CONFIG_PACKAGE_IMPORT_PATH
1198
+ };
1199
+ const endpointParams = endpoints.flatMap((endpoint) => endpoint.parameters);
1200
+ const endpointParamsParseSchemas = endpointParams.filter((param) => !["Path", "Header"].includes(param.type)).map((param) => param.parameterSortingEnumSchemaName ?? param.zodSchema);
1201
+ const endpointResponseSchemas = endpoints.map((endpoint) => endpoint.response);
1202
+ const endpointRuntimeSchemas = getUniqueArray([...endpointResponseSchemas, ...resolver.options.parseRequestParams ? endpointParamsParseSchemas : []]);
1203
+ const hasZodImport = inlineEndpoints && endpointRuntimeSchemas.some((schema) => !isNamedZodSchema(schema));
1204
+ const hasZodExtendedImport = inlineEndpoints && resolver.options.parseRequestParams && endpointParamsParseSchemas.length > 0;
1205
+ const appRestClientImport = {
1206
+ bindings: [APP_REST_CLIENT_NAME],
1207
+ from: getAppRestClientImportPath(resolver.options)
1208
+ };
1209
+ const zodExtendedImport = {
1210
+ bindings: [ZOD_EXTENDED.namespace],
1211
+ from: resolver.options.zodImportPath
1212
+ };
1213
+ const modelsImports = getModelsImports({
1214
+ resolver,
1215
+ tag,
1216
+ zodSchemas: inlineEndpoints ? endpointRuntimeSchemas.filter(isNamedZodSchema) : [],
1217
+ zodSchemasAsTypes: getUniqueArray(endpointParams.map((param) => param.zodSchema).filter(isNamedZodSchema))
1218
+ });
1219
+ const endpointsImports = inlineEndpoints ? [] : getEndpointsImports({
1220
+ tag,
1221
+ endpoints,
1222
+ options: resolver.options
1223
+ });
1224
+ const aclImports = getAclImports({
1225
+ tag,
1226
+ endpoints: aclEndpoints,
1227
+ options: resolver.options
1228
+ });
1229
+ const namespace = getNamespaceName({
1230
+ type: "queries",
1231
+ tag,
1232
+ options: resolver.options
1233
+ });
1234
+ const lines = [];
1235
+ if (hasAxiosImport) lines.push(renderImport(axiosImport));
1236
+ if (nativeTransportImport.typeBindings?.length) lines.push(renderImport(nativeTransportImport));
1237
+ if (inlineEndpoints || hasNativeMediaUpload) lines.push(renderImport(appRestClientImport));
1238
+ if (inlineEndpoints) {
1239
+ if (hasZodImport) lines.push(renderImport(ZOD_IMPORT));
1240
+ if (hasZodExtendedImport) lines.push(renderImport(zodExtendedImport));
1241
+ }
1242
+ lines.push(renderImport(queryImport));
1243
+ if (hasMutationEffects) lines.push(renderImport(queryModulesImport));
1244
+ if (hasMutationEffectsImport) lines.push(renderImport(mutationEffectsImport));
1245
+ if (hasAclCheck) {
1246
+ lines.push(renderImport(aclCheckImport));
1247
+ for (const aclImport of aclImports) lines.push(renderImport(aclImport));
1248
+ }
1249
+ lines.push(renderImport(queryTypesImport));
1250
+ if (hasWorkspaceContext) lines.push(renderImport(workspaceContextImport));
1251
+ for (const modelsImport of modelsImports) lines.push(renderImport(modelsImport));
1252
+ for (const endpointsImport of endpointsImports) lines.push(renderImport(endpointsImport));
1253
+ lines.push("");
1254
+ if (resolver.options.tsNamespaces) lines.push(`export namespace ${namespace} {`);
1255
+ if (inlineEndpoints) {
1256
+ lines.push(...renderInlineEndpoints({
1257
+ resolver,
1258
+ endpoints,
1259
+ tag
1260
+ }));
1261
+ lines.push("");
1262
+ }
1263
+ lines.push(`export const ${QUERIES_MODULE_NAME} = ${hasMutationEffects ? `${QUERY_MODULE_ENUM}.${tag}` : `"${namespace}"`};`);
1264
+ lines.push("");
1265
+ lines.push(renderQueryKeys({
1266
+ resolver,
1267
+ queryEndpoints,
1268
+ tag
1269
+ }));
1270
+ lines.push("");
1271
+ for (const endpoint of endpoints) {
1272
+ const endpointInfo = endpointGroups.infoByEndpoint.get(endpoint);
1273
+ if (endpointInfo?.query) {
1274
+ lines.push(renderQueryOptions({
1275
+ resolver,
1276
+ endpoint,
1277
+ inlineEndpoints
1278
+ }));
1279
+ lines.push("");
1280
+ lines.push(renderQuery({
1281
+ resolver,
1282
+ endpoint,
1283
+ inlineEndpoints
1284
+ }));
1285
+ lines.push("");
1286
+ if (resolver.options.prefetchQueries) {
1287
+ lines.push(renderPrefetchQuery({
1288
+ resolver,
1289
+ endpoint
1290
+ }));
1291
+ lines.push("");
1292
+ }
1293
+ }
1294
+ if (endpointInfo?.mutation) {
1295
+ lines.push(renderMutation({
1296
+ resolver,
1297
+ endpoint,
1298
+ inlineEndpoints,
1299
+ precomputed: endpointGroups.mutationDataByEndpoint.get(endpoint)
1300
+ }));
1301
+ lines.push("");
1302
+ }
1303
+ if (endpointInfo?.infiniteQuery) {
1304
+ lines.push(renderInfiniteQueryOptions({
1305
+ resolver,
1306
+ endpoint,
1307
+ inlineEndpoints
1308
+ }));
1309
+ lines.push("");
1310
+ lines.push(renderInfiniteQuery({
1311
+ resolver,
1312
+ endpoint,
1313
+ inlineEndpoints
1314
+ }));
1315
+ lines.push("");
1316
+ if (resolver.options.prefetchQueries) {
1317
+ lines.push(renderPrefetchInfiniteQuery({
1318
+ resolver,
1319
+ endpoint
1320
+ }));
1321
+ lines.push("");
1322
+ }
1323
+ }
1324
+ }
1325
+ if (resolver.options.tsNamespaces) lines.push("}");
1326
+ return lines.join("\n").trimEnd() + "\n";
1327
+ }
1328
+ function getEndpointParamMapping(resolver, endpoint, options) {
1329
+ let resolverCache = endpointParamMappingCache.get(resolver);
1330
+ if (!resolverCache) {
1331
+ resolverCache = /* @__PURE__ */ new WeakMap();
1332
+ endpointParamMappingCache.set(resolver, resolverCache);
1333
+ }
1334
+ let endpointCache = resolverCache.get(endpoint);
1335
+ if (!endpointCache) {
1336
+ endpointCache = /* @__PURE__ */ new Map();
1337
+ resolverCache.set(endpoint, endpointCache);
1338
+ }
1339
+ const key = JSON.stringify([
1340
+ options?.excludeBodyParam,
1341
+ options?.excludePageParam,
1342
+ options?.replacePageParam,
1343
+ options?.includeFileParam,
1344
+ options?.includeOnlyRequiredParams,
1345
+ options?.pathParamsRequiredOnly,
1346
+ options?.optionalPathParams,
1347
+ options?.modelNamespaceTag,
1348
+ options?.excludePathParams
1349
+ ]);
1350
+ const cached = endpointCache.get(key);
1351
+ if (cached) return cached;
1352
+ const computed = mapEndpointParamsToFunctionParams(resolver, endpoint, options);
1353
+ endpointCache.set(key, computed);
1354
+ return computed;
1355
+ }
1356
+ function getWorkspaceContextAllowList(workspaceContext) {
1357
+ return new Set(workspaceContext);
1358
+ }
1359
+ function renderImport(importData) {
1360
+ const namedImports = [...importData.bindings, ...(importData.typeBindings ?? []).map((binding) => importData.typeOnly ? binding : `type ${binding}`)];
1361
+ const names = [...importData.defaultImport ? [importData.defaultImport] : [], ...namedImports.length > 0 ? [`{ ${namedImports.join(", ")} }`] : []].join(", ");
1362
+ return `import${importData.typeOnly ? " type" : ""} ${names} from "${importData.from}";`;
1363
+ }
1364
+ function renderEndpointParams(resolver, endpoint, options) {
1365
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => `${param.name}${param.required ? "" : "?"}: ${param.type}`).join(", ");
1366
+ }
1367
+ function renderEndpointArgs(resolver, endpoint, options, replacements) {
1368
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => replacements?.[param.name] ?? param.name).join(", ");
1369
+ }
1370
+ function renderEndpointObjectArgs(resolver, endpoint, options, replacements) {
1371
+ return getEndpointParamMapping(resolver, endpoint, options).map((param) => {
1372
+ const replacement = replacements?.[param.name];
1373
+ return replacement && replacement !== param.name ? `${param.name}: ${replacement}` : param.name;
1374
+ }).join(", ");
1375
+ }
1376
+ function renderEndpointParamDescription(endpointParam) {
1377
+ const cached = endpointParamDescriptionCache.get(endpointParam);
1378
+ if (cached !== void 0) return cached;
1379
+ const strs = [`${endpointParam.paramType} parameter`];
1380
+ const description = endpointParam.parameterObject?.description || endpointParam.bodyObject?.description;
1381
+ if (description) strs.push(description);
1382
+ let schema = void 0;
1383
+ let mediaTypeObject = void 0;
1384
+ if (endpointParam.parameterObject?.schema && isSchemaObject(endpointParam.parameterObject.schema)) schema = endpointParam.parameterObject?.schema;
1385
+ if (endpointParam.bodyObject?.content) {
1386
+ const matchingMediaType = Object.keys(endpointParam.bodyObject.content ?? {}).find(isParamMediaTypeAllowed);
1387
+ if (matchingMediaType) {
1388
+ mediaTypeObject = endpointParam.bodyObject.content[matchingMediaType];
1389
+ if (mediaTypeObject.schema && isSchemaObject(mediaTypeObject.schema)) schema = mediaTypeObject.schema;
1390
+ }
1391
+ }
1392
+ if (schema) strs.push(...getSchemaDescriptions(schema));
1393
+ if (mediaTypeObject?.example) strs.push(`Example: \`${mediaTypeObject.example}\``);
1394
+ const renderedDescription = strs.join(". ");
1395
+ endpointParamDescriptionCache.set(endpointParam, renderedDescription);
1396
+ return renderedDescription;
1397
+ }
1398
+ function getWorkspaceParamNames(resolver, endpoint) {
1399
+ let resolverCache = workspaceParamNamesCache.get(resolver);
1400
+ if (!resolverCache) {
1401
+ resolverCache = /* @__PURE__ */ new WeakMap();
1402
+ workspaceParamNamesCache.set(resolver, resolverCache);
1403
+ }
1404
+ const cached = resolverCache.get(endpoint);
1405
+ if (cached) return cached;
1406
+ const allowList = getWorkspaceContextAllowList(resolver.options.workspaceContext);
1407
+ const endpointParams = getEndpointParamMapping(resolver, endpoint, {});
1408
+ const endpointParamNames = new Set(endpointParams.map((param) => param.name));
1409
+ const workspaceParamNames = endpointParams.filter((param) => param.paramType === "Path").map((param) => param.name);
1410
+ const aclParamNames = (getAbilityConditionsTypes(endpoint) ?? []).map((condition) => invalidVariableNameCharactersToCamel(condition.name)).filter((name) => endpointParamNames.has(name));
1411
+ const names = getUniqueArray([...workspaceParamNames, ...aclParamNames]).filter((name) => allowList.has(name));
1412
+ resolverCache.set(endpoint, names);
1413
+ return names;
1414
+ }
1415
+ function getWorkspaceParamReplacements(resolver, endpoint) {
1416
+ return Object.fromEntries(getWorkspaceParamNames(resolver, endpoint).map((name) => [name, `normalize${capitalize(name)}`]));
1417
+ }
1418
+ function getWorkspaceParamTypes(resolver, endpoint, modelNamespaceTag) {
1419
+ const workspaceParamNames = new Set(getWorkspaceParamNames(resolver, endpoint));
1420
+ return Object.fromEntries(getEndpointParamMapping(resolver, endpoint, { modelNamespaceTag }).filter((param) => workspaceParamNames.has(param.name)).map((param) => [param.name, param.type]));
1421
+ }
1422
+ function renderWorkspaceContextDestructure({ replacements, paramTypes, indent }) {
1423
+ const workspaceParamNames = Object.keys(replacements);
1424
+ if (workspaceParamNames.length === 0) return [];
1425
+ const workspaceParamBindings = workspaceParamNames.map((paramName) => `${paramName}: ${paramName}Workspace`);
1426
+ const workspaceContextType = workspaceParamNames.map((paramName) => `${paramName}?: ${paramTypes[paramName] ?? "unknown"}`).join("; ");
1427
+ return [`${indent}const { ${workspaceParamBindings.join(", ")} } = useWorkspaceContext<{ ${workspaceContextType} }>();`];
1428
+ }
1429
+ function renderWorkspaceParamCoalescing({ replacements, indent }) {
1430
+ const workspaceParamNames = Object.keys(replacements);
1431
+ const lines = [];
1432
+ for (const paramName of workspaceParamNames) {
1433
+ lines.push(`${indent}const ${replacements[paramName]} = ${paramName} ?? ${paramName}Workspace;`);
1434
+ lines.push(`${indent}if (!${replacements[paramName]}) {`);
1435
+ lines.push(`${indent} throw Error(\`${capitalize(paramName)} not provided\`);`);
1436
+ lines.push(`${indent}}`);
1437
+ }
1438
+ return lines;
1439
+ }
1440
+ function renderWorkspaceParamResolutions({ replacements, paramTypes, indent }) {
1441
+ return [...renderWorkspaceContextDestructure({
1442
+ replacements,
1443
+ paramTypes,
1444
+ indent
1445
+ }), ...renderWorkspaceParamCoalescing({
1446
+ replacements,
1447
+ indent
1448
+ })];
1449
+ }
1450
+ function addAsteriskAfterNewLine(str) {
1451
+ return str.replace(/\n/g, "\n *");
1452
+ }
1453
+ function renderQueryJsDocs({ resolver, endpoint, mode, tag }) {
1454
+ const lines = ["/** "];
1455
+ if (mode === "infiniteQuery") lines.push(` * Infinite query \`${getInfiniteQueryName(endpoint)}${endpoint.summary ? "" : ""}`);
1456
+ else if (mode === "query") lines.push(` * Query \`${getQueryName(endpoint)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should be cached" : ""}`);
1457
+ else lines.push(` * Mutation \`${getQueryName(endpoint, true)}\`${endpoint.summary && endpoint.mediaDownload ? " - recommended when file should not be cached" : ""}`);
1458
+ if (endpoint.summary) lines.push(` * @summary ${addAsteriskAfterNewLine(endpoint.summary)}`);
1459
+ if (endpoint.description) lines.push(` * @description ${addAsteriskAfterNewLine(endpoint.description)}`);
1460
+ if (endpoint.acl) lines.push(` * @permission Requires \`${getAbilityFunctionName(endpoint)}\` ability `);
1461
+ const params = getEndpointParamMapping(resolver, endpoint, {
1462
+ ...mode !== "infiniteQuery" ? { includeFileParam: true } : {},
1463
+ modelNamespaceTag: tag
1464
+ });
1465
+ for (const endpointParam of params) lines.push(` * @param { ${endpointParam.type} } ${endpointParam.name} ${renderEndpointParamDescription(endpointParam)}`);
1466
+ if (mode === "query") lines.push(" * @param { AppQueryOptions } options Query options");
1467
+ else if (mode === "mutation") lines.push(` * @param { AppMutationOptions${resolver.options.mutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""} } options Mutation options`);
1468
+ else lines.push(" * @param { AppInfiniteQueryOptions } options Infinite query options");
1469
+ const withRawResponse = endpoint.mediaDownload && mode !== "infiniteQuery";
1470
+ const responseType = resolver.options.restClient === "native" ? NATIVE_RESPONSE_TYPE : "AxiosResponse";
1471
+ const resultType = `${withRawResponse ? `${responseType}<` : ""}${getImportedZodSchemaInferedTypeName(resolver, endpoint.response, void 0, tag)}${withRawResponse ? ">" : ""}`;
1472
+ if (mode === "query") lines.push(` * @returns { UseQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1473
+ else if (mode === "mutation") lines.push(` * @returns { UseMutationResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1474
+ else lines.push(` * @returns { UseInfiniteQueryResult<${resultType}> } ${endpoint.responseDescription ?? ""}`);
1475
+ lines.push(` * @statusCodes [${endpoint.responseStatusCodes.join(", ")}]`);
1476
+ lines.push(" */");
1477
+ return lines.join("\n");
1478
+ }
1479
+ function renderQueryKeys({ resolver, queryEndpoints, tag }) {
1480
+ if (queryEndpoints.length === 0) return "";
1481
+ const lines = [];
1482
+ lines.push("export const keys = {");
1483
+ lines.push(` all: [${QUERIES_MODULE_NAME}] as const,`);
1484
+ for (const endpoint of queryEndpoints) {
1485
+ lines.push(` ${getEndpointName(endpoint)}: (${renderEndpointParams(resolver, endpoint, {
1486
+ pathParamsRequiredOnly: true,
1487
+ modelNamespaceTag: tag
1488
+ })}) => [...keys.all, "${endpoint.path}", ${renderEndpointArgs(resolver, endpoint, {})}] as const,`);
1489
+ if (resolver.options.infiniteQueries && isInfiniteQuery(endpoint, resolver.options)) lines.push(` ${getEndpointName(endpoint)}Infinite: (${renderEndpointParams(resolver, endpoint, {
1490
+ excludePageParam: true,
1491
+ pathParamsRequiredOnly: true,
1492
+ modelNamespaceTag: tag
1493
+ })}) => [...keys.all, "${endpoint.path}", "infinite", ${renderEndpointArgs(resolver, endpoint, { excludePageParam: true })}] as const,`);
1494
+ }
1495
+ lines.push("};");
1496
+ return lines.join("\n");
1497
+ }
1498
+ function renderInlineEndpoints({ resolver, endpoints, tag }) {
1499
+ const lines = [];
1500
+ for (const endpoint of endpoints) {
1501
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: tag });
1502
+ const endpointBody = getEndpointBody(endpoint);
1503
+ const hasUndefinedEndpointBody = requiresBody(endpoint) && !endpointBody && hasEndpointConfig(endpoint, resolver);
1504
+ const endpointConfig = renderInlineEndpointConfig(resolver, endpoint, tag);
1505
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1506
+ lines.push(`const ${getEndpointName(endpoint)} = (${endpointParams}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => {`);
1507
+ lines.push(` return ${APP_REST_CLIENT_NAME}.${endpoint.method}(`);
1508
+ lines.push(` ${renderInlineRequestInfo(resolver, endpoint, tag)},`);
1509
+ lines.push(` \`${getEndpointPath(endpoint)}\`,`);
1510
+ if (endpointBody) lines.push(` ${resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, endpointBody, endpointBody.name, tag) : endpointBody.name},`);
1511
+ else if (hasUndefinedEndpointBody) lines.push(" undefined,");
1512
+ lines.push(` ${endpointConfig}`);
1513
+ lines.push(" );");
1514
+ lines.push("};");
1515
+ lines.push("");
1516
+ }
1517
+ return lines;
1518
+ }
1519
+ function renderInlineRequestInfo(resolver, endpoint, tag) {
1520
+ return `{ resSchema: ${getImportedZodSchemaName(resolver, endpoint.response, tag)} }`;
1521
+ }
1522
+ function getRequestConfigType(resolver) {
1523
+ return `${getRequestConfigTypeName(resolver.options.restClient)} & { allowInvalidResponseData?: boolean }`;
1524
+ }
1525
+ function renderRequestConfigWithSignal(hasRequestConfigParam) {
1526
+ return `{ ${hasRequestConfigParam ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}signal }`;
1527
+ }
1528
+ function renderInlineEndpointParamParse(resolver, param, paramName, modelNamespaceTag) {
1529
+ const addOptional = !(param.parameterObject ?? param.bodyObject)?.required && (Boolean(param.parameterSortingEnumSchemaName) || isNamedZodSchema(param.zodSchema));
1530
+ const schemaValue = param.parameterSortingEnumSchemaName ? `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.sortExp}(${getImportedZodSchemaName(resolver, param.parameterSortingEnumSchemaName, modelNamespaceTag)})${getSortingPresenceChain(resolver, param)}` : `${getImportedZodSchemaName(resolver, param.zodSchema, modelNamespaceTag)}${addOptional ? ".optional()" : ""}`;
1531
+ const queryArgs = param.type === "Query" ? `, { type: "query", name: "${paramName}" }` : "";
1532
+ return `${ZOD_EXTENDED.namespace}.${ZOD_EXTENDED.exports.parse}(${schemaValue}, ${paramName}${queryArgs})`;
1533
+ }
1534
+ function getSortingPresenceChain(resolver, param) {
1535
+ const zodSchemaCode = resolver.getCodeByZodSchemaName(param.zodSchema) ?? param.zodSchema;
1536
+ if (zodSchemaCode.includes(".nullish()")) return ".nullish()";
1537
+ if (zodSchemaCode.includes(".nullable()")) return ".nullable()";
1538
+ return !(param.parameterObject ?? param.bodyObject)?.required ? ".optional()" : "";
1539
+ }
1540
+ function renderInlineEndpointConfig(resolver, endpoint, modelNamespaceTag) {
1541
+ const endpointConfig = getEndpointConfig(endpoint);
1542
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1543
+ const needsBlobConfig = endpoint.mediaDownload || endpoint.response === "z.instanceof(Blob)";
1544
+ if (Object.keys(endpointConfig).length === 0 && !needsBlobConfig) return hasRequestConfigParam ? AXIOS_REQUEST_CONFIG_NAME : "";
1545
+ const lines = [];
1546
+ lines.push("{");
1547
+ if (hasRequestConfigParam) lines.push(` ...${AXIOS_REQUEST_CONFIG_NAME},`);
1548
+ if (endpointConfig.params) {
1549
+ lines.push(" params: {");
1550
+ for (const param of endpointConfig.params) {
1551
+ const value = resolver.options.parseRequestParams ? renderInlineEndpointParamParse(resolver, param, param.value, modelNamespaceTag) : param.value;
1552
+ lines.push(` ${param.name}: ${value},`);
1553
+ }
1554
+ lines.push(" },");
1555
+ }
1556
+ if (endpointConfig.headers) {
1557
+ lines.push(" headers: {");
1558
+ for (const [key, value] of Object.entries(endpointConfig.headers)) lines.push(` '${key}': ${value},`);
1559
+ lines.push(" },");
1560
+ }
1561
+ if (endpoint.response === "z.instanceof(Blob)") lines.push(" responseType: \"blob\",");
1562
+ if (endpoint.mediaDownload) lines.push(" rawResponse: true,");
1563
+ lines.push(" }");
1564
+ return lines.join("\n");
1565
+ }
1566
+ function renderQueryOptions({ resolver, endpoint, inlineEndpoints }) {
1567
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1568
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
1569
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1570
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1571
+ const lines = [];
1572
+ lines.push(`const ${getQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => ({`);
1573
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}(${endpointArgs}),`);
1574
+ const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
1575
+ lines.push(` queryFn: ({ signal }: { signal: AbortSignal }) => ${endpointFunction}(${endpointArgs}${hasRequestConfigParam ? `${endpointArgs ? ", " : ""}${requestConfigWithSignal}` : ""}),`);
1576
+ lines.push("});");
1577
+ return lines.join("\n");
1578
+ }
1579
+ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
1580
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1581
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1582
+ excludePageParam: true,
1583
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
1584
+ });
1585
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1586
+ const endpointArgsWithPage = renderEndpointArgs(resolver, endpoint, { replacePageParam: true });
1587
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1588
+ const lines = [];
1589
+ lines.push(`const ${getInfiniteQueryOptionsName(endpoint)} = (${endpointParams ? `{ ${endpointArgsWithoutPage} }: { ${endpointParams} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigType(resolver)}` : ""}) => ({`);
1590
+ lines.push(` queryKey: keys.${getEndpointName(endpoint)}Infinite(${endpointArgsWithoutPage}),`);
1591
+ const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
1592
+ lines.push(` queryFn: ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => ${endpointFunction}(${endpointArgsWithPage}${hasRequestConfigParam ? `, ${requestConfigWithSignal}` : ""}),`);
1593
+ lines.push(" initialPageParam: 1,");
1594
+ lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>> & Partial<Record<${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.page)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.totalItems)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.limit)}, number | null>>) => {`);
1595
+ lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
1596
+ lines.push(" const pageSize = limitParam ?? 0;");
1597
+ lines.push(` return pageParam * pageSize < (${resolver.options.infiniteQueryResponseParamNames.totalItems} ?? 0) ? pageParam + 1 : null;`);
1598
+ lines.push(" },");
1599
+ lines.push("});");
1600
+ return lines.join("\n");
1601
+ }
1602
+ function renderPrefetchQuery({ resolver, endpoint }) {
1603
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1604
+ const endpointParams = renderEndpointParams(resolver, endpoint, { modelNamespaceTag: getEndpointTag(endpoint, resolver.options) });
1605
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1606
+ const lines = [];
1607
+ lines.push(`export const ${getPrefetchQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: Omit<Parameters<QueryClient["prefetchQuery"]>[0], "queryKey" | "queryFn">, ${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}, ` : ""}throwOnError = false) => {`);
1608
+ lines.push(` const queryOptions = { ...${getQueryOptionsName(endpoint)}(${endpointParams ? `{ ${endpointArgs} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}), ...options };`);
1609
+ lines.push(` return throwOnError ? queryClient.fetchQuery(queryOptions) : queryClient.prefetchQuery(queryOptions);`);
1610
+ lines.push("};");
1611
+ return lines.join("\n");
1612
+ }
1613
+ function renderPrefetchInfiniteQuery({ resolver, endpoint }) {
1614
+ const hasRequestConfigParam = resolver.options.axiosRequestConfig || endpoint.method === "get";
1615
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1616
+ excludePageParam: true,
1617
+ modelNamespaceTag: getEndpointTag(endpoint, resolver.options)
1618
+ });
1619
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1620
+ const optionsArgs = `${endpointParams ? `{ ${endpointArgs} }` : ""}${hasRequestConfigParam ? `${endpointParams ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""}`;
1621
+ const lines = [];
1622
+ lines.push(`export const ${getPrefetchInfiniteQueryName(endpoint)} = (queryClient: QueryClient, ${endpointParams ? `{ ${endpointArgs} }: { ${endpointParams} }, ` : ""}options?: Omit<Parameters<QueryClient["prefetchInfiniteQuery"]>[0], "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam">, ${hasRequestConfigParam ? `${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}, ` : ""}throwOnError = false) => {`);
1623
+ lines.push(` const queryOptions = { ...${getInfiniteQueryOptionsName(endpoint)}(${optionsArgs}), ...(options as {}) };`);
1624
+ lines.push(` return throwOnError ? queryClient.fetchInfiniteQuery(queryOptions) : queryClient.prefetchInfiniteQuery(queryOptions);`);
1625
+ lines.push("};");
1626
+ return lines.join("\n");
1627
+ }
1628
+ function renderQuery({ resolver, endpoint, inlineEndpoints }) {
1629
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1630
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1631
+ const tag = getEndpointTag(endpoint, resolver.options);
1632
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1633
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1634
+ const endpointArgs = renderEndpointArgs(resolver, endpoint, {});
1635
+ const resolvedEndpointArgs = renderEndpointObjectArgs(resolver, endpoint, {}, workspaceParamReplacements);
1636
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1637
+ optionalPathParams: resolver.options.workspaceContext,
1638
+ modelNamespaceTag: tag
1639
+ });
1640
+ const queryOptionsName = getQueryOptionsName(endpoint);
1641
+ const hasQueryFnOverride = hasAclCheck;
1642
+ const requestConfig = `{ ${hasAxiosRequestConfig ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}allowInvalidResponseData: queryConfig.allowInvalidResponseData }`;
1643
+ const queryOptionsArgs = `${resolvedEndpointArgs ? `{ ${resolvedEndpointArgs} }, ` : ""}${requestConfig}`;
1644
+ const lines = [];
1645
+ lines.push(renderQueryJsDocs({
1646
+ resolver,
1647
+ endpoint,
1648
+ mode: "query",
1649
+ tag
1650
+ }));
1651
+ 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}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1652
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1653
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1654
+ lines.push(...renderWorkspaceParamResolutions({
1655
+ replacements: workspaceParamReplacements,
1656
+ paramTypes: workspaceParamTypes,
1657
+ indent: " "
1658
+ }));
1659
+ lines.push(" ");
1660
+ lines.push(` return ${QUERY_HOOKS.query}({`);
1661
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
1662
+ if (hasQueryFnOverride) {
1663
+ lines.push(" queryFn: async ({ signal }: { signal: AbortSignal }) => {");
1664
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1665
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ signal });`);
1666
+ lines.push(" },");
1667
+ }
1668
+ lines.push(" ...options,");
1669
+ lines.push(" });");
1670
+ lines.push("};");
1671
+ return lines.join("\n");
1672
+ }
1673
+ function renderMutation({ resolver, endpoint, inlineEndpoints, precomputed }) {
1674
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1675
+ const hasMutationEffects = resolver.options.mutationEffects;
1676
+ const hasMutationDefaultOnError = resolver.options.mutationDefaultOnError;
1677
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1678
+ const tag = getEndpointTag(endpoint, resolver.options);
1679
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1680
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1681
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1682
+ includeFileParam: true,
1683
+ optionalPathParams: resolver.options.workspaceContext,
1684
+ modelNamespaceTag: tag
1685
+ });
1686
+ const resolvedEndpointArgs = renderEndpointArgs(resolver, endpoint, {}, workspaceParamReplacements);
1687
+ const destructuredMutationArgs = renderEndpointArgs(resolver, endpoint, { includeFileParam: true });
1688
+ const endpointFunction = inlineEndpoints ? getEndpointName(endpoint) : getImportedEndpointName(endpoint, resolver.options);
1689
+ const updateQueryEndpoints = precomputed?.updateQueryEndpoints ?? [];
1690
+ const destructuredVariables = precomputed?.destructuredVariables ?? getDestructuredVariables(resolver, endpoint, updateQueryEndpoints);
1691
+ const hasMutationFnBody = endpoint.mediaUpload || hasAclCheck || Object.keys(workspaceParamReplacements).length > 0;
1692
+ const mutationVariablesType = endpoint.mediaUpload ? `${endpointParams}${endpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : endpointParams;
1693
+ const isPost = endpoint.method === "post";
1694
+ const mutationScopeOption = resolver.options.mutationScope;
1695
+ const operationId = getEndpointName(endpoint);
1696
+ const scopeMatchKey = `${tag}/${operationId}`;
1697
+ let scopeEnabled = false;
1698
+ if (!isPost && mutationScopeOption) {
1699
+ if (mutationScopeOption === true) scopeEnabled = true;
1700
+ else if (typeof mutationScopeOption === "object" && "include" in mutationScopeOption) scopeEnabled = mutationScopeOption.include.some((id) => id === operationId || id === scopeMatchKey);
1701
+ else if (typeof mutationScopeOption === "object" && "exclude" in mutationScopeOption) scopeEnabled = !mutationScopeOption.exclude.some((id) => id === operationId || id === scopeMatchKey);
1702
+ }
1703
+ const scopePathParams = scopeEnabled ? getEndpointParamMapping(resolver, endpoint, { modelNamespaceTag: tag }).filter((p) => p.paramType === "Path") : [];
1704
+ const isScoped = scopePathParams.length > 0;
1705
+ const nonPathEndpointParams = isScoped ? renderEndpointParams(resolver, endpoint, {
1706
+ includeFileParam: true,
1707
+ optionalPathParams: resolver.options.workspaceContext,
1708
+ modelNamespaceTag: tag,
1709
+ excludePathParams: true
1710
+ }) : endpointParams;
1711
+ const nonPathMutationVariablesType = isScoped ? endpoint.mediaUpload ? `${nonPathEndpointParams}${nonPathEndpointParams ? "; " : ""}abortController?: AbortController; onUploadProgress?: (progress: { loaded: number; total: number }) => void` : nonPathEndpointParams : mutationVariablesType;
1712
+ const pathParamFirstArg = isScoped ? `{ ${scopePathParams.map((p) => p.name).join(", ")} }: { ${scopePathParams.map((p) => `${p.name}: ${p.type}`).join("; ")} }, ` : "";
1713
+ const mutationOptionsTypeArg = isScoped ? nonPathMutationVariablesType ? `, { ${nonPathMutationVariablesType} }` : "" : `, { ${mutationVariablesType} }`;
1714
+ const lines = [];
1715
+ lines.push(renderQueryJsDocs({
1716
+ resolver,
1717
+ endpoint,
1718
+ mode: "mutation",
1719
+ tag
1720
+ }));
1721
+ lines.push(`export const ${getQueryName(endpoint, true)} = (${pathParamFirstArg}options?: AppMutationOptions<typeof ${endpointFunction}${mutationOptionsTypeArg}>${hasMutationEffects ? ` & ${MUTATION_EFFECTS.optionsType}` : ""}${hasAxiosRequestConfig ? `, ${AXIOS_REQUEST_CONFIG_NAME}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1722
+ if (hasMutationDefaultOnError) lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1723
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1724
+ lines.push(...renderWorkspaceContextDestructure({
1725
+ replacements: workspaceParamReplacements,
1726
+ paramTypes: workspaceParamTypes,
1727
+ indent: " "
1728
+ }));
1729
+ if (hasMutationEffects) lines.push(` const { runMutationEffects } = useMutationEffects<${QUERY_MODULE_ENUM}.${tag}>({ currentModule: ${QUERIES_MODULE_NAME} });`);
1730
+ lines.push("");
1731
+ lines.push(` return ${QUERY_HOOKS.mutation}({`);
1732
+ const nonPathDestructuredArgs = isScoped ? renderEndpointArgs(resolver, endpoint, {
1733
+ includeFileParam: true,
1734
+ excludePathParams: true
1735
+ }) : destructuredMutationArgs;
1736
+ const effectiveParams = isScoped ? nonPathEndpointParams : endpointParams;
1737
+ const effectiveArgs = isScoped ? nonPathDestructuredArgs : destructuredMutationArgs;
1738
+ const mutationFnArg = effectiveParams || endpoint.mediaUpload ? `{ ${effectiveArgs}${endpoint.mediaUpload ? `${effectiveArgs ? ", " : ""}abortController, onUploadProgress` : ""} }` : "";
1739
+ lines.push(` mutationFn: ${endpoint.mediaUpload ? "async " : ""}(${mutationFnArg}) => ${hasMutationFnBody ? "{ " : ""}`);
1740
+ lines.push(...renderWorkspaceParamCoalescing({
1741
+ replacements: workspaceParamReplacements,
1742
+ indent: " "
1743
+ }));
1744
+ if (hasAclCheck) lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1745
+ if (endpoint.mediaUpload) lines.push(...renderMediaUploadMutationBody({
1746
+ resolver,
1747
+ endpointFunction,
1748
+ resolvedEndpointArgs
1749
+ }).map((line) => ` ${line}`));
1750
+ else lines.push(` ${hasMutationFnBody ? "return " : ""}${endpointFunction}(${resolvedEndpointArgs}${hasAxiosRequestConfig ? `${resolvedEndpointArgs ? ", " : ""}${AXIOS_REQUEST_CONFIG_NAME}` : ""})`);
1751
+ if (hasMutationFnBody) lines.push(" },");
1752
+ else lines.push(",");
1753
+ if (isScoped) {
1754
+ const scopePathParamInterpolations = scopePathParams.map((p) => `:\${${p.name}}`).join("");
1755
+ lines.push(` scope: { id: \`${getEndpointName(endpoint)}${scopePathParamInterpolations}\` },`);
1756
+ }
1757
+ lines.push(" ...options,");
1758
+ if (hasMutationDefaultOnError) lines.push(" onError: options?.onError ?? queryConfig.onError,");
1759
+ if (hasMutationEffects) {
1760
+ lines.push(" onSuccess: async (resData, variables, onMutateResult, context) => {");
1761
+ if (updateQueryEndpoints.length > 0) {
1762
+ const scopedPathParamNames = new Set(scopePathParams.map((p) => p.name));
1763
+ const variablesDestructure = destructuredVariables.filter((v) => !scopedPathParamNames.has(v));
1764
+ if (variablesDestructure.length > 0) lines.push(` const { ${variablesDestructure.join(", ")} } = variables;`);
1765
+ lines.push(...renderWorkspaceParamCoalescing({
1766
+ replacements: workspaceParamReplacements,
1767
+ indent: " "
1768
+ }));
1769
+ lines.push(` const updateKeys = [${updateQueryEndpoints.map((e) => `keys.${getEndpointName(e)}(${renderEndpointArgs(resolver, e, { includeOnlyRequiredParams: true }, workspaceParamReplacements)})`).join(", ")}];`);
1770
+ lines.push(` await runMutationEffects(resData, variables, options, updateKeys);`);
1771
+ } else lines.push(" await runMutationEffects(resData, variables, options);");
1772
+ lines.push(" options?.onSuccess?.(resData, variables, onMutateResult, context);");
1773
+ lines.push(" },");
1774
+ }
1775
+ lines.push(" });");
1776
+ lines.push("};");
1777
+ return lines.join("\n");
1778
+ }
1779
+ function groupEndpoints(endpoints, resolver) {
1780
+ const queryEndpoints = [];
1781
+ const mutationEndpoints = [];
1782
+ const infiniteQueryEndpoints = [];
1783
+ const aclEndpoints = [];
1784
+ const infoByEndpoint = /* @__PURE__ */ new Map();
1785
+ const mutationDataByEndpoint = /* @__PURE__ */ new Map();
1786
+ for (const endpoint of endpoints) {
1787
+ const query = isQuery(endpoint);
1788
+ const mutation = isMutation(endpoint);
1789
+ const infiniteQuery = Boolean(resolver.options.infiniteQueries && query && isInfiniteQuery(endpoint, resolver.options));
1790
+ if (query) queryEndpoints.push(endpoint);
1791
+ if (mutation) mutationEndpoints.push(endpoint);
1792
+ if (infiniteQuery) infiniteQueryEndpoints.push(endpoint);
1793
+ if (endpoint.acl) aclEndpoints.push(endpoint);
1794
+ infoByEndpoint.set(endpoint, {
1795
+ query,
1796
+ mutation,
1797
+ infiniteQuery
1798
+ });
1799
+ }
1800
+ for (const endpoint of mutationEndpoints) {
1801
+ 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);
1802
+ mutationDataByEndpoint.set(endpoint, {
1803
+ updateQueryEndpoints,
1804
+ destructuredVariables: getDestructuredVariables(resolver, endpoint, updateQueryEndpoints)
1805
+ });
1806
+ }
1807
+ return {
1808
+ queryEndpoints,
1809
+ mutationEndpoints,
1810
+ infiniteQueryEndpoints,
1811
+ aclEndpoints,
1812
+ infoByEndpoint,
1813
+ mutationDataByEndpoint
1814
+ };
1815
+ }
1816
+ function renderInfiniteQuery({ resolver, endpoint, inlineEndpoints }) {
1817
+ const hasAclCheck = resolver.options.checkAcl && endpoint.acl;
1818
+ const hasAxiosRequestConfig = resolver.options.axiosRequestConfig;
1819
+ const tag = getEndpointTag(endpoint, resolver.options);
1820
+ const workspaceParamReplacements = resolver.options.workspaceContext ? getWorkspaceParamReplacements(resolver, endpoint) : {};
1821
+ const workspaceParamTypes = getWorkspaceParamTypes(resolver, endpoint, tag);
1822
+ const endpointParams = renderEndpointParams(resolver, endpoint, {
1823
+ excludePageParam: true,
1824
+ optionalPathParams: resolver.options.workspaceContext,
1825
+ modelNamespaceTag: tag
1826
+ });
1827
+ const endpointArgsWithoutPage = renderEndpointArgs(resolver, endpoint, { excludePageParam: true });
1828
+ const resolvedEndpointArgsWithoutPage = renderEndpointObjectArgs(resolver, endpoint, { excludePageParam: true }, workspaceParamReplacements);
1829
+ const queryOptionsName = getInfiniteQueryOptionsName(endpoint);
1830
+ const requestConfig = `{ ${hasAxiosRequestConfig ? `...${AXIOS_REQUEST_CONFIG_NAME}, ` : ""}allowInvalidResponseData: queryConfig.allowInvalidResponseData }`;
1831
+ const queryOptionsArgs = `${resolvedEndpointArgsWithoutPage ? `{ ${resolvedEndpointArgsWithoutPage} }, ` : ""}${requestConfig}`;
1832
+ const hasQueryFnOverride = hasAclCheck;
1833
+ const lines = [];
1834
+ lines.push(renderQueryJsDocs({
1835
+ resolver,
1836
+ endpoint,
1837
+ mode: "infiniteQuery",
1838
+ tag
1839
+ }));
1840
+ 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}?: ${getRequestConfigTypeName(resolver.options.restClient)}` : ""}) => {`);
1841
+ lines.push(" const queryConfig = OpenApiQueryConfig.useConfig();");
1842
+ if (hasAclCheck) lines.push(` const { checkAcl } = ${ACL_CHECK_HOOK}();`);
1843
+ lines.push(...renderWorkspaceParamResolutions({
1844
+ replacements: workspaceParamReplacements,
1845
+ paramTypes: workspaceParamTypes,
1846
+ indent: " "
1847
+ }));
1848
+ lines.push("");
1849
+ lines.push(` return ${QUERY_HOOKS.infiniteQuery}({`);
1850
+ lines.push(` ...${queryOptionsName}(${queryOptionsArgs}),`);
1851
+ if (hasQueryFnOverride) {
1852
+ lines.push(" queryFn: async ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => {");
1853
+ lines.push(renderAclCheckCall(resolver, endpoint, workspaceParamReplacements, " "));
1854
+ lines.push(` return ${queryOptionsName}(${queryOptionsArgs}).queryFn({ pageParam, signal });`);
1855
+ lines.push(" },");
1856
+ }
1857
+ lines.push(" ...options,");
1858
+ lines.push(" });");
1859
+ lines.push("};");
1860
+ return lines.join("\n");
1861
+ }
1862
+ //#endregion
1863
+ //#region src/generators/generate/generateAppRestClient.ts
1864
+ function generateAppRestClient(resolver) {
1865
+ const clientName = resolver.options.restClient === "native" ? "NativeRestClient" : "RestClient";
1866
+ return `import { ${clientName} } from "${resolver.options.restClient === "native" ? NATIVE_PACKAGE_IMPORT_PATH : AXIOS_PACKAGE_IMPORT_PATH}";
1867
+
1868
+ export const ${APP_REST_CLIENT_NAME} = new ${clientName}({
1869
+ config: {
1870
+ baseURL: "${resolver.getBaseUrl()}"
1871
+ },
1872
+ });
1873
+ `;
1874
+ }
1875
+ //#endregion
1876
+ //#region src/generators/generate/generateDomainErrors.ts
1877
+ function domainToPascalCase(domain) {
1878
+ return domain.split(/[-_]/).map(capitalize).join("");
1879
+ }
1880
+ const VALID_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1881
+ function generateDomainErrors({ resolver, data }) {
1882
+ const nativeContent = resolver.getNativeRenderedShared?.("domainErrors");
1883
+ if (nativeContent) return nativeContent;
1884
+ const byDomain = /* @__PURE__ */ new Map();
1885
+ for (const { endpoints } of data.values()) for (const endpoint of endpoints) for (const error of endpoint.errors) {
1886
+ if (!error.domainError) continue;
1887
+ const { domain, code } = error.domainError;
1888
+ if (!byDomain.has(domain)) byDomain.set(domain, /* @__PURE__ */ new Map());
1889
+ const domainMap = byDomain.get(domain);
1890
+ if (!domainMap.has(code)) domainMap.set(code, {
1891
+ code,
1892
+ name: error.domainError.name,
1893
+ description: error.description
1894
+ });
1895
+ }
1896
+ if (byDomain.size === 0) return void 0;
1897
+ const blocks = [];
1898
+ for (const [domain, codes] of [...byDomain.entries()].sort(([a], [b]) => a.localeCompare(b))) {
1899
+ const pascalName = domainToPascalCase(domain);
1900
+ const entries = [...codes.values()].sort((a, b) => {
1901
+ if (typeof a.code === "number" && typeof b.code === "number") return a.code - b.code;
1902
+ const sa = String(a.code);
1903
+ const sb = String(b.code);
1904
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
1905
+ }).map(({ code, name, description }) => {
1906
+ const comment = description ? ` /** ${description} */\n ` : " ";
1907
+ const key = name ?? (typeof code === "string" ? code : `ERROR_${code}`);
1908
+ if (!VALID_IDENTIFIER.test(key)) throw new Error(`Domain error code "${code}" produces an invalid identifier "${key}". Use the 'name' field on @ApiDomainErrorResponse to provide a valid identifier.`);
1909
+ return `${comment}${key}: ${typeof code === "string" ? `"${code}"` : String(code)}`;
1910
+ }).join(",\n");
1911
+ blocks.push(`export const ${pascalName}DomainErrors = {\n${entries},\n} as const;`);
1912
+ blocks.push(`export type ${pascalName}DomainErrorCode = (typeof ${pascalName}DomainErrors)[keyof typeof ${pascalName}DomainErrors];`);
1913
+ }
1914
+ return blocks.join("\n\n") + "\n";
1915
+ }
1916
+ //#endregion
1917
+ //#region src/generators/generate/generateQueryModules.ts
1918
+ function generateQueryModules({ resolver, data }) {
1919
+ const nativeContent = resolver.getNativeRenderedShared?.("queryModules");
1920
+ if (nativeContent) return nativeContent;
1921
+ const modules = [];
1922
+ data.forEach((_, tag) => {
1923
+ const endpoints = data.get(tag)?.endpoints;
1924
+ if (!endpoints || endpoints.length === 0) return;
1925
+ modules.push({
1926
+ tag,
1927
+ namespace: getNamespaceName({
1928
+ type: "queries",
1929
+ tag,
1930
+ options: resolver.options
1931
+ })
1932
+ });
1933
+ });
1934
+ const lines = [];
1935
+ lines.push("export const enum QueryModule {");
1936
+ for (const module of modules) lines.push(` ${module.tag} = "${module.namespace}",`);
1937
+ lines.push("}");
1938
+ return lines.join("\n");
1939
+ }
1940
+ //#endregion
1941
+ //#region src/generators/utils/generate-files.utils.ts
1942
+ function getAclFiles(data, resolver) {
1943
+ if (!resolver.options.acl) return [];
1944
+ return [{
1945
+ fileName: getOutputFileName({
1946
+ output: resolver.options.output,
1947
+ fileName: getFileNameWithExtension(ACL_APP_ABILITY_FILE)
1948
+ }),
1949
+ content: generateAppAcl({
1950
+ resolver,
1951
+ data
1952
+ })
1953
+ }];
1954
+ }
1955
+ function getMutationEffectsFiles(data, resolver) {
1956
+ if (!resolver.options.mutationEffects) return [];
1957
+ return [{
1958
+ fileName: getOutputFileName({
1959
+ output: resolver.options.output,
1960
+ fileName: getFileNameWithExtension(QUERY_MODULES_FILE)
1961
+ }),
1962
+ content: generateQueryModules({
1963
+ resolver,
1964
+ data
1965
+ })
1966
+ }];
1967
+ }
1968
+ function getZodExtendedFiles(_data, _resolver) {
1969
+ return [];
1970
+ }
1971
+ function getDomainErrorsFiles(data, resolver) {
1972
+ const content = generateDomainErrors({
1973
+ resolver,
1974
+ data
1975
+ });
1976
+ if (!content) return [];
1977
+ return [{
1978
+ fileName: getOutputFileName({
1979
+ output: resolver.options.output,
1980
+ fileName: getFileNameWithExtension(DOMAIN_ERRORS_FILE)
1981
+ }),
1982
+ content
1983
+ }];
1984
+ }
1985
+ function getAppRestClientFiles(resolver) {
1986
+ if (resolver.options.restClientImportPath !== DEFAULT_GENERATE_OPTIONS.restClientImportPath) return [];
1987
+ return [{
1988
+ fileName: getOutputFileName({
1989
+ output: resolver.options.output,
1990
+ fileName: getFileNameWithExtension(APP_REST_CLIENT_FILE)
1991
+ }),
1992
+ content: generateAppRestClient(resolver)
1993
+ }];
1994
+ }
1995
+ //#endregion
1996
+ //#region src/native/getDataFromNativeOpenAPIDoc.ts
1997
+ var NativeSchemaResolver = class {
1998
+ nativeData;
1999
+ options;
2000
+ openApiDoc;
2001
+ dependencyGraph;
2002
+ refByName;
2003
+ nameByRef;
2004
+ circularSchemas;
2005
+ referencedNames = /* @__PURE__ */ new Map();
2006
+ enumObjectsByCode;
2007
+ constructor(openApiDoc, options, nativeData) {
2008
+ this.nativeData = nativeData;
2009
+ this.openApiDoc = openApiDoc;
2010
+ this.options = options;
2011
+ this.refByName = new Map(Object.entries(nativeData.schemaRefs));
2012
+ for (const name of Object.keys(nativeData.generatedObjects)) if (!this.refByName.has(name)) this.refByName.set(name, `#/x-native-schemas/${encodeURIComponent(name)}`);
2013
+ this.nameByRef = new Map([...this.refByName].map(([name, ref]) => [ref, name]));
2014
+ this.circularSchemas = new Set(nativeData.circularSchemas);
2015
+ const refsDependencyGraph = Object.fromEntries(Object.entries(nativeData.dependencies).map(([ref, dependencies]) => [ref, new Set(dependencies)]));
2016
+ this.dependencyGraph = {
2017
+ refsDependencyGraph,
2018
+ deepDependencyGraph: {}
2019
+ };
2020
+ for (const name of Object.keys(nativeData.generatedObjects)) {
2021
+ const ref = this.refByName.get(name);
2022
+ const dependencies = /* @__PURE__ */ new Set();
2023
+ const addDependency = (dependency) => {
2024
+ if (dependency === ref || dependencies.has(dependency)) return;
2025
+ dependencies.add(dependency);
2026
+ for (const child of this.dependencyGraph.refsDependencyGraph[dependency] ?? []) addDependency(child);
2027
+ };
2028
+ for (const dependencyName of nativeData.generatedDependencies[name] ?? []) {
2029
+ const dependency = this.refByName.get(dependencyName);
2030
+ if (dependency) addDependency(dependency);
2031
+ }
2032
+ this.dependencyGraph.refsDependencyGraph[ref] = dependencies;
2033
+ }
2034
+ }
2035
+ getCodeByZodSchemaName(name) {
2036
+ return this.nativeData.schemas[name];
2037
+ }
2038
+ getNativeRenderedModels(tag) {
2039
+ return this.nativeData.renderedModels[tag];
2040
+ }
2041
+ getNativeRenderedEndpoints(tag) {
2042
+ return this.nativeData.renderedEndpoints[tag];
2043
+ }
2044
+ getNativeRenderedQueries(tag) {
2045
+ return this.nativeData.renderedQueries[tag];
2046
+ }
2047
+ getNativeRenderedAcl(tag) {
2048
+ return this.nativeData.renderedAcl[tag];
2049
+ }
2050
+ getNativeRenderedShared(name) {
2051
+ return this.nativeData.renderedShared[name];
2052
+ }
2053
+ getRefByZodSchemaName(name) {
2054
+ return this.refByName.get(name);
2055
+ }
2056
+ getZodSchemaNameByRef(ref) {
2057
+ return this.nameByRef.get(normalizeRef(ref));
2058
+ }
2059
+ getTagByZodSchemaName(name) {
2060
+ return !this.options.splitByTags || this.options.modelsInCommon ? this.options.defaultTag : this.nativeData.schemaOwners[name] ?? this.options.defaultTag;
2061
+ }
2062
+ isSchemaCircular(ref) {
2063
+ const name = this.nameByRef.get(normalizeRef(ref));
2064
+ return Boolean(name && this.circularSchemas.has(name));
2065
+ }
2066
+ getZodSchemaObj(name) {
2067
+ if (this.nativeData.generatedObjects[name]) return this.nativeData.generatedObjects[name];
2068
+ const ref = this.refByName.get(name);
2069
+ if (ref) return this.resolveRef(ref);
2070
+ const code = this.nativeData.schemas[name];
2071
+ if (!code?.startsWith("z.enum(")) return void 0;
2072
+ this.enumObjectsByCode ??= collectEnumObjects(this.openApiDoc);
2073
+ return this.enumObjectsByCode.get(code);
2074
+ }
2075
+ getExtractedEnumZodSchemaNamesReferencedBySchemaRef(ref) {
2076
+ const normalizedRef = normalizeRef(ref);
2077
+ const cached = this.referencedNames.get(normalizedRef);
2078
+ if (cached) return cached;
2079
+ const name = this.nameByRef.get(normalizedRef);
2080
+ const code = name ? this.nativeData.schemas[name] : void 0;
2081
+ const directNames = new Set([...this.dependencyGraph.refsDependencyGraph[normalizedRef] ?? []].map((dependency) => this.nameByRef.get(dependency)).filter((value) => Boolean(value)));
2082
+ const references = [...code ? [...code.matchAll(/\b[A-Za-z_$][\w$]*Schema\b/g)].map(([match]) => match).filter((match, index, values) => match !== name && values.indexOf(match) === index && match in this.nativeData.schemas && !directNames.has(match)) : []].filter((value, index, values) => values.indexOf(value) === index);
2083
+ this.referencedNames.set(normalizedRef, references);
2084
+ return references;
2085
+ }
2086
+ getCompositeZodSchemaByZodSchemaName() {}
2087
+ resolveObject(value) {
2088
+ if (value && typeof value === "object" && "$ref" in value) return this.resolveRef(value.$ref);
2089
+ return value;
2090
+ }
2091
+ getBaseUrl() {
2092
+ return this.nativeData.baseUrl;
2093
+ }
2094
+ resolveRef(ref) {
2095
+ const segments = normalizeRef(ref).slice(2).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
2096
+ let value = this.openApiDoc;
2097
+ for (const segment of segments) value = value?.[segment];
2098
+ return value;
2099
+ }
2100
+ };
2101
+ function collectEnumObjects(document) {
2102
+ const enums = /* @__PURE__ */ new Map();
2103
+ const visit = (value) => {
2104
+ if (!value || typeof value !== "object") return;
2105
+ if (Array.isArray(value)) {
2106
+ value.forEach(visit);
2107
+ return;
2108
+ }
2109
+ const object = value;
2110
+ if (Array.isArray(object.enum)) {
2111
+ const code = `z.enum(${JSON.stringify(object.enum)})`.replaceAll(",", ", ");
2112
+ Object.assign(enums.get(code) ?? {}, object);
2113
+ enums.set(code, {
2114
+ ...enums.get(code) ?? {},
2115
+ ...object
2116
+ });
2117
+ }
2118
+ Object.values(object).forEach(visit);
2119
+ };
2120
+ visit(document.components?.schemas ?? {});
2121
+ return enums;
2122
+ }
2123
+ function normalizeRef(ref) {
2124
+ if (ref.startsWith("#/")) return ref;
2125
+ if (ref.startsWith("#")) return `#/${ref.slice(1).replace(/^\//, "")}`;
2126
+ return ref;
2127
+ }
2128
+ function getTagElement(tag, data) {
2129
+ let value = data.get(tag);
2130
+ if (!value) {
2131
+ value = {
2132
+ endpoints: [],
2133
+ zodSchemas: {}
2134
+ };
2135
+ data.set(tag, value);
2136
+ }
2137
+ return value;
2138
+ }
2139
+ function getDataFromNativeOpenAPIDoc(openApiDoc, options, nativeSource) {
2140
+ const started = performance.now();
2141
+ const source = nativeSource?.source ?? JSON.stringify(openApiDoc);
2142
+ const afterLoad = performance.now();
2143
+ const nativeResult = compileNativeData(source, nativeSource?.yaml ?? false, JSON.stringify({
2144
+ ...options,
2145
+ nativeCompact: true
2146
+ }));
2147
+ const afterNative = performance.now();
2148
+ const nativeData = nativeResult.data;
2149
+ const afterParse = performance.now();
2150
+ const resolver = new NativeSchemaResolver(nativeData.document ?? openApiDoc, options, nativeData);
2151
+ const afterResolver = performance.now();
2152
+ const data = /* @__PURE__ */ new Map();
2153
+ if (nativeData.renderedComplete) {
2154
+ for (const tag of nativeData.renderedTags) data.set(tag, {
2155
+ endpoints: [],
2156
+ zodSchemas: {}
2157
+ });
2158
+ if (process.env.OPENAPI_NATIVE_PROFILE === "1") console.error(`native bridge load=${(afterLoad - started).toFixed(1)}ms call=${(afterNative - afterLoad).toFixed(1)}ms parse=${(afterParse - afterNative).toFixed(1)}ms facade=${(performance.now() - afterParse).toFixed(1)}ms compact=true`);
2159
+ return {
2160
+ resolver,
2161
+ data
2162
+ };
2163
+ }
2164
+ if (!options.splitByTags) {
2165
+ data.set(options.defaultTag, {
2166
+ endpoints: nativeData.endpoints,
2167
+ zodSchemas: nativeData.schemas
2168
+ });
2169
+ return {
2170
+ resolver,
2171
+ data
2172
+ };
2173
+ }
2174
+ for (const endpoint of nativeData.endpoints) getTagElement(getEndpointTag(endpoint, options), data).endpoints.push(endpoint);
2175
+ for (const [name, code] of Object.entries(nativeData.schemas)) {
2176
+ const tags = options.modelsInModules ? nativeData.schemaUsageTags[name] ?? [options.defaultTag] : [options.modelsInCommon ? options.defaultTag : nativeData.schemaOwners[name]];
2177
+ for (const tag of tags) if (tag) getTagElement(tag, data).zodSchemas[name] = code;
2178
+ }
2179
+ if (process.env.OPENAPI_NATIVE_PROFILE === "1") console.error(`native bridge load=${(afterLoad - started).toFixed(1)}ms call=${(afterNative - afterLoad).toFixed(1)}ms parse=${(afterParse - afterNative).toFixed(1)}ms facade=${(afterResolver - afterParse).toFixed(1)}ms split=${(performance.now() - afterResolver).toFixed(1)}ms`);
2180
+ return {
2181
+ resolver,
2182
+ data
2183
+ };
2184
+ }
2185
+ //#endregion
2186
+ //#region src/generators/generateCodeFromOpenAPIDoc.ts
2187
+ var generateCodeFromOpenAPIDoc_exports = /* @__PURE__ */ __exportAll({ generateCodeFromOpenAPIDoc: () => generateCodeFromOpenAPIDoc });
2188
+ function generateCodeFromOpenAPIDoc(openApiDoc, options, profiler, nativeSource) {
2189
+ const p = profiler ?? new Profiler(false);
2190
+ const importPath = options.standalone && options.importPath === "ts" ? "relative" : options.importPath;
2191
+ const resolvedOptions = {
2192
+ ...options,
2193
+ importPath
2194
+ };
2195
+ const { resolver, data } = p.runSync("data.extract", () => nativeSource && shouldUseNativeCodegen() ? getDataFromNativeOpenAPIDoc(openApiDoc, resolvedOptions, nativeSource) : getDataFromOpenAPIDoc(openApiDoc, resolvedOptions, p));
2196
+ const generateFilesData = [];
2197
+ const appAclTags = [];
2198
+ const modelsOnly = Boolean(resolver.options.modelsOnly);
2199
+ const shouldGenerateEndpoints = !modelsOnly && Array.from(data.keys()).some((tag) => !shouldInlineEndpointsForTag(tag, resolver.options));
2200
+ const generateTypes = modelsOnly ? ["models"] : [
2201
+ "models",
2202
+ ...shouldGenerateEndpoints ? ["endpoints"] : [],
2203
+ "queries",
2204
+ ...resolver.options.acl ? ["acl"] : [],
2205
+ ...resolver.options.builderConfigs ? ["configs"] : []
2206
+ ];
2207
+ const generateFunctions = {
2208
+ ["models"]: generateModels,
2209
+ ["endpoints"]: generateEndpoints,
2210
+ ["queries"]: generateQueries,
2211
+ ["acl"]: generateAcl,
2212
+ ["configs"]: generateConfigs
2213
+ };
2214
+ data.forEach((_, tag) => {
2215
+ generateTypes.forEach((type) => {
2216
+ const content = p.runSync(`render.${type}`, () => generateFunctions[type]({
2217
+ resolver,
2218
+ data,
2219
+ tag
2220
+ }));
2221
+ if (content) {
2222
+ const fileName = getOutputFileName({
2223
+ output: options.output,
2224
+ fileName: getTagFileName({
2225
+ tag,
2226
+ type,
2227
+ options
2228
+ })
2229
+ });
2230
+ generateFilesData.push({
2231
+ fileName,
2232
+ content
2233
+ });
2234
+ if (type === "acl") appAclTags.push(tag);
2235
+ }
2236
+ });
2237
+ });
2238
+ 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)), ...p.runSync("render.DomainErrors", () => getDomainErrorsFiles(data, resolver)));
2239
+ return generateFilesData;
2240
+ }
2241
+ //#endregion
2242
+ export { generateCodeFromOpenAPIDoc_exports as n, generateCodeFromOpenAPIDoc as t };