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