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

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