@7nohe/openapi-react-query-codegen 4.0.0-beta.4 → 4.0.0-beta.5

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 (45) hide show
  1. package/AGENTS.md +4 -0
  2. package/dist/client/emitSchemas.mjs +12 -9
  3. package/dist/client/emitSdk.d.mts +2 -0
  4. package/dist/client/emitSdk.mjs +24 -27
  5. package/dist/client/emitTransformers.mjs +21 -72
  6. package/dist/client/emitTypes.d.mts +2 -1
  7. package/dist/client/emitTypes.mjs +5 -5
  8. package/dist/client/index.mjs +13 -5
  9. package/dist/client/naming.d.mts +5 -2
  10. package/dist/client/naming.mjs +7 -3
  11. package/dist/client/operations.d.mts +3 -2
  12. package/dist/client/operations.mjs +10 -47
  13. package/dist/client/runtime/axios.runtime.ts +15 -10
  14. package/dist/client/schema.d.mts +24 -2
  15. package/dist/client/schema.mjs +135 -33
  16. package/dist/client/spec.d.mts +6 -0
  17. package/dist/client/spec.mjs +15 -5
  18. package/dist/common.d.mts +0 -2
  19. package/dist/common.mjs +0 -10
  20. package/dist/createSource.d.mts +1 -1
  21. package/dist/createSource.mjs +1 -3
  22. package/dist/generate.mjs +1 -2
  23. package/dist/hooks/buildCommon.d.mts +12 -16
  24. package/dist/hooks/buildCommon.mjs +25 -35
  25. package/dist/hooks/buildMutationHooks.d.mts +3 -2
  26. package/dist/hooks/buildMutationHooks.mjs +6 -11
  27. package/dist/hooks/buildQueryHooks.d.mts +21 -15
  28. package/dist/hooks/buildQueryHooks.mjs +35 -69
  29. package/dist/hooks/buildQueryOptions.d.mts +4 -3
  30. package/dist/hooks/buildQueryOptions.mjs +9 -22
  31. package/dist/hooks/generateFiles.mjs +54 -81
  32. package/dist/hooks/hookNames.d.mts +69 -0
  33. package/dist/hooks/hookNames.mjs +82 -0
  34. package/dist/hooks/imports.d.mts +27 -52
  35. package/dist/hooks/imports.mjs +82 -164
  36. package/dist/hooks/operationNames.d.mts +10 -0
  37. package/dist/hooks/operationNames.mjs +22 -0
  38. package/dist/hooks/statement.d.mts +15 -6
  39. package/dist/hooks/statement.mjs +19 -14
  40. package/dist/types.d.mts +5 -7
  41. package/package.json +1 -1
  42. package/dist/hooks/index.d.mts +0 -4
  43. package/dist/hooks/index.mjs +0 -4
  44. package/dist/print.d.mts +0 -5
  45. package/dist/print.mjs +0 -22
@@ -1,4 +1,5 @@
1
- import type { GenerationContext, OperationInfo } from "../types.mjs";
1
+ import type { GenerationContext } from "../types.mjs";
2
+ import { type HookOperation } from "./hookNames.mjs";
2
3
  import type { ConstStatement } from "./statement.mjs";
3
4
  /**
4
5
  * SDK call arguments shared by every generated queryFn/mutationFn.
@@ -10,24 +11,29 @@ export declare const SDK_CALL_ARGS = "{ ...clientOptions, throwOnError: true }";
10
11
  /** SDK call arguments for TanStack query functions with cancellation. */
11
12
  export declare const QUERY_SDK_CALL_ARGS = "{ ...clientOptions, signal, throwOnError: true }";
12
13
  /** Resolve the OpenAPI page parameter type, preserving older numeric output. */
13
- export declare function getPageParamType(op: OperationInfo): string;
14
+ export declare function getPageParamType(op: HookOperation): string;
14
15
  /**
15
16
  * Build the client options parameter string.
16
17
  */
17
- export declare function buildClientOptionsParam(op: OperationInfo): string;
18
+ export declare function buildClientOptionsParam(op: HookOperation): string;
18
19
  /**
19
20
  * Build the clientOptions parameter typed with the page-less infinite
20
21
  * options type — the page parameter is supplied by TanStack Query's
21
22
  * pageParam mechanism.
22
23
  */
23
- export declare function buildInfiniteClientOptionsParam(op: OperationInfo): string;
24
+ export declare function buildInfiniteClientOptionsParam(op: HookOperation): string;
24
25
  /**
25
26
  * The type of a single page. TanStack Query instantiates the infinite options
26
27
  * with this as TQueryFnData, so it is what `getNextPageParam` receives as
27
28
  * `lastPage` (#203). NonNullable because `throwOnError: true` means a resolved
28
29
  * page is always present.
29
30
  */
30
- export declare function getPageType(op: OperationInfo): string;
31
+ export declare function getPageType(op: HookOperation): string;
32
+ /**
33
+ * The models a paginated query names: the Data type in `buildPagedQueryFn`,
34
+ * and whatever the page parameter's type refers to.
35
+ */
36
+ export declare function pagedModels(op: HookOperation): string[];
31
37
  /**
32
38
  * Build the paginated SDK call shared by every infinite query builder.
33
39
  * The resolved response is narrowed to the page type so it matches the
@@ -35,13 +41,13 @@ export declare function getPageType(op: OperationInfo): string;
35
41
  * a cast rather than `!` because generated code is linted downstream, and a
36
42
  * non-null assertion trips biome's noNonNullAssertion.
37
43
  */
38
- export declare function buildPagedQueryFn(op: OperationInfo, ctx: GenerationContext): string;
44
+ export declare function buildPagedQueryFn(op: HookOperation, ctx: GenerationContext): string;
39
45
  /**
40
46
  * Format the initialPageParam literal. Emits `undefined` when the caller opted
41
47
  * to omit it (#177); otherwise a numeric literal when possible so the inferred
42
48
  * pageParam type matches what getNextPageParam returns.
43
49
  */
44
- export declare function formatInitialPageParam(ctx: GenerationContext, op?: OperationInfo): string;
50
+ export declare function formatInitialPageParam(ctx: GenerationContext, op?: HookOperation): string;
45
51
  /**
46
52
  * Build the nested type for getNextPageParam.
47
53
  * E.g., "meta.next" becomes "{ meta: { next: number } }"
@@ -52,7 +58,7 @@ export declare function buildNestedNextPageType(nextPageParam: string, pageParam
52
58
  * not every TanStack entry point contextually types it (prefetchInfiniteQuery
53
59
  * does not, which would fail noImplicitAny).
54
60
  */
55
- export declare function buildGetNextPageParamExpr(ctx: GenerationContext, op?: OperationInfo): string;
61
+ export declare function buildGetNextPageParamExpr(ctx: GenerationContext, op?: HookOperation): string;
56
62
  /**
57
63
  * Build an options type where the pagination fields TanStack Query marks as
58
64
  * required become optional overrides: the generator supplies them, and
@@ -79,19 +85,19 @@ export declare function buildOverridableInfiniteOptionsType(optionsTypeName: str
79
85
  * ...options
80
86
  * });
81
87
  */
82
- export declare function buildUseQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement;
88
+ export declare function buildUseQueryHook(op: HookOperation, ctx: GenerationContext): ConstStatement;
83
89
  /**
84
90
  * Build useSuspenseQuery hook.
85
91
  */
86
- export declare function buildUseSuspenseQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement;
92
+ export declare function buildUseSuspenseQueryHook(op: HookOperation, ctx: GenerationContext): ConstStatement;
87
93
  /**
88
94
  * Build useInfiniteQuery hook.
89
95
  */
90
- export declare function buildUseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
96
+ export declare function buildUseInfiniteQueryHook(op: HookOperation, ctx: GenerationContext): ConstStatement;
91
97
  /**
92
98
  * Build useSuspenseInfiniteQuery hook.
93
99
  */
94
- export declare function buildUseSuspenseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
100
+ export declare function buildUseSuspenseInfiniteQueryHook(op: HookOperation, ctx: GenerationContext): ConstStatement;
95
101
  /**
96
102
  * Build prefetch function.
97
103
  * Example:
@@ -102,7 +108,7 @@ export declare function buildUseSuspenseInfiniteQueryHook(op: OperationInfo, ctx
102
108
  * ...options
103
109
  * });
104
110
  */
105
- export declare function buildPrefetchFn(op: OperationInfo): ConstStatement;
111
+ export declare function buildPrefetchFn(op: HookOperation): ConstStatement;
106
112
  /**
107
113
  * Build prefetchInfiniteQuery function for a paginatable operation.
108
114
  * Example:
@@ -115,7 +121,7 @@ export declare function buildPrefetchFn(op: OperationInfo): ConstStatement;
115
121
  * ...options
116
122
  * });
117
123
  */
118
- export declare function buildPrefetchInfiniteQueryFn(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
124
+ export declare function buildPrefetchInfiniteQueryFn(op: HookOperation, ctx: GenerationContext): ConstStatement;
119
125
  /**
120
126
  * Build ensureQueryData function.
121
127
  * Example:
@@ -126,4 +132,4 @@ export declare function buildPrefetchInfiniteQueryFn(op: OperationInfo, ctx: Gen
126
132
  * ...options
127
133
  * });
128
134
  */
129
- export declare function buildEnsureQueryDataFn(op: OperationInfo): ConstStatement;
135
+ export declare function buildEnsureQueryDataFn(op: HookOperation): ConstStatement;
@@ -1,5 +1,6 @@
1
1
  import { isValidIdentifier, propertyKey } from "../client/naming.mjs";
2
- import { getDataTypeName, getErrorType } from "./operationNames.mjs";
2
+ import { hookNames } from "./hookNames.mjs";
3
+ import { dataModels, errorModels, getDataTypeName, getErrorType, operationConst, } from "./operationNames.mjs";
3
4
  /**
4
5
  * SDK call arguments shared by every generated queryFn/mutationFn.
5
6
  * throwOnError: true forces the SDK call to reject on error responses; the
@@ -27,7 +28,7 @@ export function buildClientOptionsParam(op) {
27
28
  */
28
29
  export function buildInfiniteClientOptionsParam(op) {
29
30
  const defaultValue = op.allParamsOptional ? " = {}" : "";
30
- return `clientOptions: Common.${op.capitalizedMethodName}InfiniteClientOptions${defaultValue}`;
31
+ return `clientOptions: Common.${hookNames(op).infiniteClientOptions}${defaultValue}`;
31
32
  }
32
33
  /**
33
34
  * The type of a single page. TanStack Query instantiates the infinite options
@@ -36,7 +37,14 @@ export function buildInfiniteClientOptionsParam(op) {
36
37
  * page is always present.
37
38
  */
38
39
  export function getPageType(op) {
39
- return `NonNullable<Common.${op.capitalizedMethodName}DefaultResponse>`;
40
+ return `NonNullable<Common.${hookNames(op).defaultResponse}>`;
41
+ }
42
+ /**
43
+ * The models a paginated query names: the Data type in `buildPagedQueryFn`,
44
+ * and whatever the page parameter's type refers to.
45
+ */
46
+ export function pagedModels(op) {
47
+ return [...dataModels(op), ...(op.pageParamModels ?? [])];
40
48
  }
41
49
  /**
42
50
  * Build the paginated SDK call shared by every infinite query builder.
@@ -138,37 +146,25 @@ export function buildOverridableInfiniteOptionsType(optionsTypeName, pageType) {
138
146
  * });
139
147
  */
140
148
  export function buildUseQueryHook(op, ctx) {
141
- const hookName = `use${op.capitalizedMethodName}`;
149
+ const hookName = hookNames(op).hook;
142
150
  const errorType = getErrorType(op, ctx);
143
- const dataTypeDefault = `Common.${op.capitalizedMethodName}DefaultResponse`;
151
+ const dataTypeDefault = `Common.${hookNames(op).defaultResponse}`;
144
152
  const clientOptionsParam = buildClientOptionsParam(op);
145
153
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data as TData) as TData`;
146
- const body = `useQuery<TData, TError>({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
147
- return {
148
- kind: "const",
149
- // The operation's JSDoc (description and @deprecated), as on the SDK function
150
- jsDoc: op.jsDoc,
151
- name: hookName,
152
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
153
- };
154
+ const body = `useQuery<TData, TError>({ queryKey: Common.${hookNames(op).keyFn}(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
155
+ return operationConst(op, hookName, `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`, [...dataModels(op), ...errorModels(op)]);
154
156
  }
155
157
  /**
156
158
  * Build useSuspenseQuery hook.
157
159
  */
158
160
  export function buildUseSuspenseQueryHook(op, ctx) {
159
- const hookName = `use${op.capitalizedMethodName}Suspense`;
161
+ const hookName = hookNames(op).suspenseHook;
160
162
  const errorType = getErrorType(op, ctx);
161
- const dataTypeDefault = `NonNullable<Common.${op.capitalizedMethodName}DefaultResponse>`;
163
+ const dataTypeDefault = `NonNullable<Common.${hookNames(op).defaultResponse}>`;
162
164
  const clientOptionsParam = buildClientOptionsParam(op);
163
165
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data as TData) as TData`;
164
- const body = `useSuspenseQuery<TData, TError>({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
165
- return {
166
- kind: "const",
167
- // The operation's JSDoc (description and @deprecated), as on the SDK function
168
- jsDoc: op.jsDoc,
169
- name: hookName,
170
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseSuspenseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
171
- };
166
+ const body = `useSuspenseQuery<TData, TError>({ queryKey: Common.${hookNames(op).keyFn}(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
167
+ return operationConst(op, hookName, `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseSuspenseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`, [...dataModels(op), ...errorModels(op)]);
172
168
  }
173
169
  /**
174
170
  * Build a useInfiniteQuery / useSuspenseInfiniteQuery hook. Both variants
@@ -177,31 +173,22 @@ export function buildUseSuspenseQueryHook(op, ctx) {
177
173
  * default of the suspense variant.
178
174
  */
179
175
  function buildInfiniteHook(op, ctx, suspense) {
180
- if (!op.isPaginatable) {
181
- return null;
182
- }
183
176
  const hookCall = suspense ? "useSuspenseInfiniteQuery" : "useInfiniteQuery";
184
177
  const optionsTypeName = suspense
185
178
  ? "UseSuspenseInfiniteQueryOptions"
186
179
  : "UseInfiniteQueryOptions";
187
180
  const hookName = suspense
188
- ? `use${op.capitalizedMethodName}SuspenseInfinite`
189
- : `use${op.capitalizedMethodName}Infinite`;
181
+ ? hookNames(op).suspenseInfiniteHook
182
+ : hookNames(op).infiniteHook;
190
183
  const errorType = getErrorType(op, ctx);
191
- const baseDataType = `Common.${op.capitalizedMethodName}DefaultResponse`;
184
+ const baseDataType = `Common.${hookNames(op).defaultResponse}`;
192
185
  const dataTypeDefault = suspense
193
186
  ? `InfiniteData<NonNullable<${baseDataType}>>`
194
187
  : `InfiniteData<${baseDataType}>`;
195
188
  const queryFn = buildPagedQueryFn(op, ctx);
196
189
  const infiniteOptions = `initialPageParam: ${formatInitialPageParam(ctx, op)}, getNextPageParam: ${buildGetNextPageParamExpr(ctx, op)}`;
197
- const body = `${hookCall}({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
198
- return {
199
- kind: "const",
200
- // The operation's JSDoc (description and @deprecated), as on the SDK function
201
- jsDoc: op.jsDoc,
202
- name: hookName,
203
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${buildInfiniteClientOptionsParam(op)}, queryKey?: TQueryKey, options?: ${buildOverridableInfiniteOptionsType(optionsTypeName, getPageType(op))}) => ${body}`,
204
- };
190
+ const body = `${hookCall}({ queryKey: Common.${hookNames(op).infiniteKeyFn}(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
191
+ return operationConst(op, hookName, `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${buildInfiniteClientOptionsParam(op)}, queryKey?: TQueryKey, options?: ${buildOverridableInfiniteOptionsType(optionsTypeName, getPageType(op))}) => ${body}`, [...pagedModels(op), ...errorModels(op)]);
205
192
  }
206
193
  /**
207
194
  * Build useInfiniteQuery hook.
@@ -226,17 +213,11 @@ export function buildUseSuspenseInfiniteQueryHook(op, ctx) {
226
213
  * });
227
214
  */
228
215
  export function buildPrefetchFn(op) {
229
- const fnName = `prefetchUse${op.capitalizedMethodName}`;
216
+ const fnName = hookNames(op).prefetch;
230
217
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data)`;
231
- const optionsParam = `options?: Omit<FetchQueryOptions<Common.${op.capitalizedMethodName}DefaultResponse>, "queryKey" | "queryFn">`;
232
- const body = `queryClient.prefetchQuery({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions), queryFn: ${queryFn}, ...options })`;
233
- return {
234
- kind: "const",
235
- // The operation's JSDoc (description and @deprecated), as on the SDK function
236
- jsDoc: op.jsDoc,
237
- name: fnName,
238
- initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
239
- };
218
+ const optionsParam = `options?: Omit<FetchQueryOptions<Common.${hookNames(op).defaultResponse}>, "queryKey" | "queryFn">`;
219
+ const body = `queryClient.prefetchQuery({ queryKey: Common.${hookNames(op).keyFn}(clientOptions), queryFn: ${queryFn}, ...options })`;
220
+ return operationConst(op, fnName, `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`, dataModels(op));
240
221
  }
241
222
  /**
242
223
  * Build prefetchInfiniteQuery function for a paginatable operation.
@@ -251,10 +232,7 @@ export function buildPrefetchFn(op) {
251
232
  * });
252
233
  */
253
234
  export function buildPrefetchInfiniteQueryFn(op, ctx) {
254
- if (!op.isPaginatable) {
255
- return null;
256
- }
257
- const fnName = `prefetchUse${op.capitalizedMethodName}Infinite`;
235
+ const fnName = hookNames(op).prefetchInfinite;
258
236
  const queryFn = buildPagedQueryFn(op, ctx);
259
237
  const infiniteOptions = `initialPageParam: ${formatInitialPageParam(ctx, op)}, getNextPageParam: ${buildGetNextPageParamExpr(ctx, op)}`;
260
238
  // The pagination fields are re-added as optional overrides: `...options` is
@@ -266,14 +244,8 @@ export function buildPrefetchInfiniteQueryFn(op, ctx) {
266
244
  const instantiated = `FetchInfiniteQueryOptions<${pageType}>`;
267
245
  const overrides = `Partial<Pick<${instantiated}, "initialPageParam">> & { getNextPageParam?: GetNextPageParamFunction<unknown, ${pageType}> }`;
268
246
  const optionsParam = `options?: Omit<${instantiated}, "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam"> & ${overrides}`;
269
- const body = `queryClient.prefetchInfiniteQuery({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
270
- return {
271
- kind: "const",
272
- // The operation's JSDoc (description and @deprecated), as on the SDK function
273
- jsDoc: op.jsDoc,
274
- name: fnName,
275
- initializer: `(queryClient: QueryClient, ${buildInfiniteClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
276
- };
247
+ const body = `queryClient.prefetchInfiniteQuery({ queryKey: Common.${hookNames(op).infiniteKeyFn}(clientOptions), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
248
+ return operationConst(op, fnName, `(queryClient: QueryClient, ${buildInfiniteClientOptionsParam(op)}, ${optionsParam}) => ${body}`, pagedModels(op));
277
249
  }
278
250
  /**
279
251
  * Build ensureQueryData function.
@@ -286,15 +258,9 @@ export function buildPrefetchInfiniteQueryFn(op, ctx) {
286
258
  * });
287
259
  */
288
260
  export function buildEnsureQueryDataFn(op) {
289
- const fnName = `ensureUse${op.capitalizedMethodName}Data`;
261
+ const fnName = hookNames(op).ensureData;
290
262
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data)`;
291
- const optionsParam = `options?: Omit<EnsureQueryDataOptions<Common.${op.capitalizedMethodName}DefaultResponse>, "queryKey" | "queryFn">`;
292
- const body = `queryClient.ensureQueryData({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions), queryFn: ${queryFn}, ...options })`;
293
- return {
294
- kind: "const",
295
- // The operation's JSDoc (description and @deprecated), as on the SDK function
296
- jsDoc: op.jsDoc,
297
- name: fnName,
298
- initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
299
- };
263
+ const optionsParam = `options?: Omit<EnsureQueryDataOptions<Common.${hookNames(op).defaultResponse}>, "queryKey" | "queryFn">`;
264
+ const body = `queryClient.ensureQueryData({ queryKey: Common.${hookNames(op).keyFn}(clientOptions), queryFn: ${queryFn}, ...options })`;
265
+ return operationConst(op, fnName, `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`, dataModels(op));
300
266
  }
@@ -1,4 +1,5 @@
1
- import type { GenerationContext, OperationInfo } from "../types.mjs";
1
+ import type { GenerationContext } from "../types.mjs";
2
+ import { type HookOperation } from "./hookNames.mjs";
2
3
  import type { ConstStatement } from "./statement.mjs";
3
4
  /**
4
5
  * Build a queryOptions factory for a GET operation.
@@ -12,7 +13,7 @@ import type { ConstStatement } from "./statement.mjs";
12
13
  * queryFn: () => findPets({ ...clientOptions, throwOnError: true }).then(response => response.data),
13
14
  * });
14
15
  */
15
- export declare function buildQueryOptionsFn(op: OperationInfo): ConstStatement;
16
+ export declare function buildQueryOptionsFn(op: HookOperation): ConstStatement;
16
17
  /**
17
18
  * Build an infiniteQueryOptions factory for a paginatable GET operation.
18
19
  * Uses the dedicated infinite query key and page-less options type.
@@ -26,4 +27,4 @@ export declare function buildQueryOptionsFn(op: OperationInfo): ConstStatement;
26
27
  * ...options,
27
28
  * });
28
29
  */
29
- export declare function buildInfiniteQueryOptionsFn(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
30
+ export declare function buildInfiniteQueryOptionsFn(op: HookOperation, ctx: GenerationContext): ConstStatement;
@@ -1,4 +1,6 @@
1
- import { buildClientOptionsParam, buildGetNextPageParamExpr, buildInfiniteClientOptionsParam, buildPagedQueryFn, formatInitialPageParam, getPageType, QUERY_SDK_CALL_ARGS, } from "./buildQueryHooks.mjs";
1
+ import { buildClientOptionsParam, buildGetNextPageParamExpr, buildInfiniteClientOptionsParam, buildPagedQueryFn, formatInitialPageParam, getPageType, pagedModels, QUERY_SDK_CALL_ARGS, } from "./buildQueryHooks.mjs";
2
+ import { hookNames } from "./hookNames.mjs";
3
+ import { dataModels, operationConst } from "./operationNames.mjs";
2
4
  /**
3
5
  * Build a queryOptions factory for a GET operation.
4
6
  * The factory centralizes queryKey and queryFn so they can be reused with
@@ -12,17 +14,11 @@ import { buildClientOptionsParam, buildGetNextPageParamExpr, buildInfiniteClient
12
14
  * });
13
15
  */
14
16
  export function buildQueryOptionsFn(op) {
15
- const fnName = `${op.methodName}Options`;
17
+ const fnName = hookNames(op).options;
16
18
  const clientOptionsParam = buildClientOptionsParam(op);
17
19
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data)`;
18
- const body = `queryOptions({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn} })`;
19
- return {
20
- kind: "const",
21
- // The operation's JSDoc (description and @deprecated), as on the SDK function
22
- jsDoc: op.jsDoc,
23
- name: fnName,
24
- initializer: `(${clientOptionsParam}, queryKey?: Array<unknown>) => ${body}`,
25
- };
20
+ const body = `queryOptions({ queryKey: Common.${hookNames(op).keyFn}(clientOptions, queryKey), queryFn: ${queryFn} })`;
21
+ return operationConst(op, fnName, `(${clientOptionsParam}, queryKey?: Array<unknown>) => ${body}`, dataModels(op));
26
22
  }
27
23
  /**
28
24
  * Build an infiniteQueryOptions factory for a paginatable GET operation.
@@ -38,22 +34,13 @@ export function buildQueryOptionsFn(op) {
38
34
  * });
39
35
  */
40
36
  export function buildInfiniteQueryOptionsFn(op, ctx) {
41
- if (!op.isPaginatable) {
42
- return null;
43
- }
44
- const fnName = `${op.methodName}InfiniteOptions`;
37
+ const fnName = hookNames(op).infiniteOptions;
45
38
  const queryFn = buildPagedQueryFn(op, ctx);
46
39
  const infiniteOptions = `initialPageParam: ${formatInitialPageParam(ctx, op)}, getNextPageParam: ${buildGetNextPageParamExpr(ctx, op)}`;
47
40
  // Only the pagination fields are overridable here: the factory's return type
48
41
  // is what every downstream consumer infers from, and a wider options type
49
42
  // (select, placeholderData, ...) would make that inference ambiguous (#203).
50
43
  const optionsParam = `options?: Partial<Pick<UseInfiniteQueryOptions<${getPageType(op)}>, "initialPageParam" | "getNextPageParam">>`;
51
- const body = `infiniteQueryOptions({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
52
- return {
53
- kind: "const",
54
- // The operation's JSDoc (description and @deprecated), as on the SDK function
55
- jsDoc: op.jsDoc,
56
- name: fnName,
57
- initializer: `(${buildInfiniteClientOptionsParam(op)}, queryKey?: Array<unknown>, ${optionsParam}) => ${body}`,
58
- };
44
+ const body = `infiniteQueryOptions({ queryKey: Common.${hookNames(op).infiniteKeyFn}(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
45
+ return operationConst(op, fnName, `(${buildInfiniteClientOptionsParam(op)}, queryKey?: Array<unknown>, ${optionsParam}) => ${body}`, pagedModels(op));
59
46
  }
@@ -1,43 +1,30 @@
1
1
  import { OpenApiRqFiles } from "../constants.mjs";
2
- import { buildDefaultResponseType, buildInfiniteClientOptionsType, buildInfiniteQueryKeyConst, buildInfiniteQueryKeyFn, buildMutationKeyConst, buildMutationKeyFn, buildMutationResultType, buildQueryKeyConst, buildQueryKeyFn, buildQueryResultType, } from "./buildCommon.mjs";
2
+ import { buildDefaultResponseType, buildInfiniteClientOptionsType, buildInfiniteQueryKeyConst, buildInfiniteQueryKeyFn, buildKeyConst, buildMutationKeyFn, buildMutationResultType, buildQueryKeyFn, buildQueryResultType, } from "./buildCommon.mjs";
3
3
  import { buildUseMutationHook } from "./buildMutationHooks.mjs";
4
4
  import { buildEnsureQueryDataFn, buildPrefetchFn, buildPrefetchInfiniteQueryFn, buildUseInfiniteQueryHook, buildUseQueryHook, buildUseSuspenseInfiniteQueryHook, buildUseSuspenseQueryHook, } from "./buildQueryHooks.mjs";
5
5
  import { buildInfiniteQueryOptionsFn, buildQueryOptionsFn, } from "./buildQueryOptions.mjs";
6
- import { buildCommonFileImports, buildHookFileImports, buildQueryOptionsFileImports, printImports, relativeModule, } from "./imports.mjs";
6
+ import { settleHookNames, } from "./hookNames.mjs";
7
+ import { buildFileImports, printImports, relativeModule } from "./imports.mjs";
7
8
  import { printStatements, referencedNames, statementCode, } from "./statement.mjs";
8
- /**
9
- * Build one variable statement per operation, skipping the ones the builder
10
- * declines. A builder returns null when the operation is out of its scope —
11
- * every infinite-query builder returns null for non-paginatable operations,
12
- * which is how the paginatable subset gets selected.
13
- */
14
- function collectStatements(operations, build) {
15
- const statements = [];
16
- for (const op of operations) {
17
- const statement = build(op);
18
- if (statement) {
19
- statements.push(statement);
20
- }
21
- }
22
- return statements;
9
+ /** The distinct values of a list, in order of first appearance. */
10
+ function unique(values) {
11
+ return [...new Set(values)];
23
12
  }
24
13
  /**
25
14
  * The content of a generated file: the imports its statements need, then the
26
- * statements. Only the services of the operations the file covers and the
27
- * models its code mentions are imported.
15
+ * statements.
28
16
  */
29
- function createFile(ctx, buildImports, operations, statements) {
17
+ function createFile(ctx, statements) {
30
18
  if (statements.length === 0) {
31
19
  // Nothing to export. The bare import keeps the file a module.
32
20
  return `import "${relativeModule("../requests/sdk.gen", ctx)}";\n`;
33
21
  }
34
- const used = referencedNames(statements.map(statementCode).join("\n"));
35
- const imports = buildImports({
36
- ...ctx,
37
- modelNames: ctx.modelNames.filter((model) => used.has(model)),
38
- serviceNames: operations.map((op) => op.methodName),
22
+ const imports = buildFileImports(ctx, {
23
+ services: unique(statements.flatMap((statement) => statement.service ?? [])),
24
+ models: unique(statements.flatMap((statement) => statement.models ?? [])),
25
+ mentioned: referencedNames(statements.map(statementCode).join("\n")),
39
26
  });
40
- return `${printImports(imports, used)}\n${printStatements(statements)}`;
27
+ return `${printImports(imports)}\n${printStatements(statements)}`;
41
28
  }
42
29
  /**
43
30
  * The content of index.ts.
@@ -51,99 +38,85 @@ function indexFile(ctx) {
51
38
  .map((name) => `export * from "${relativeModule(`./${name}`, ctx)}";\n`)
52
39
  .join("");
53
40
  }
54
- function commonStatements(queries, mutations, ctx) {
55
- const statements = [];
56
- for (const op of queries) {
57
- statements.push(buildDefaultResponseType(op), buildQueryResultType(op), buildQueryKeyConst(op), buildQueryKeyFn(op));
58
- }
59
- // Dedicated infinite query types and keys for paginatable operations
60
- for (const op of queries.filter((query) => query.isPaginatable)) {
61
- statements.push(buildInfiniteClientOptionsType(op, ctx), buildInfiniteQueryKeyConst(op), buildInfiniteQueryKeyFn(op));
62
- }
63
- for (const op of mutations) {
64
- statements.push(buildMutationResultType(op), buildMutationKeyConst(op), buildMutationKeyFn(op));
65
- }
66
- return statements;
67
- }
68
41
  /**
69
- * Add the generated header comment to file content.
42
+ * The statements of every file but `index.ts`, in the order they are printed:
43
+ * for each operation of a kind, what each builder makes of it.
70
44
  */
71
- function addHeaderComment(content, version) {
72
- const comment = `// generated with @7nohe/openapi-react-query-codegen@${version} \n\n`;
73
- return comment + content;
74
- }
75
- /**
76
- * Generate the React Query files for the operations of a specification.
77
- */
78
- export function generateAllFiles(operations, ctx) {
45
+ function buildFiles(operations, ctx) {
79
46
  const queries = operations.filter((op) => op.httpMethod === "GET");
80
47
  const mutations = operations.filter((op) => ["POST", "PUT", "PATCH", "DELETE"].includes(op.httpMethod));
48
+ // The infinite variants: their own types and keys in `common.ts`.
81
49
  const paginated = queries.filter((op) => op.isPaginatable);
82
- const all = [...queries, ...mutations];
83
- const files = [
50
+ const each = (ops, ...builders) => ops.flatMap((op) => builders.map((build) => ({ op, statement: build(op, ctx) })));
51
+ return [
84
52
  [
85
53
  OpenApiRqFiles.common,
86
- buildCommonFileImports,
87
- all,
88
- commonStatements(queries, mutations, ctx),
54
+ [
55
+ ...each(queries, buildDefaultResponseType, buildQueryResultType, buildKeyConst, buildQueryKeyFn),
56
+ ...each(paginated, buildInfiniteClientOptionsType, buildInfiniteQueryKeyConst, buildInfiniteQueryKeyFn),
57
+ ...each(mutations, buildMutationResultType, buildKeyConst, buildMutationKeyFn),
58
+ ],
89
59
  ],
90
60
  [
91
61
  OpenApiRqFiles.queries,
92
- buildHookFileImports,
93
- all,
94
62
  [
95
- ...queries.map((op) => buildUseQueryHook(op, ctx)),
96
- ...mutations.map((op) => buildUseMutationHook(op, ctx)),
63
+ ...each(queries, buildUseQueryHook),
64
+ ...each(mutations, buildUseMutationHook),
97
65
  ],
98
66
  ],
99
67
  [
100
68
  OpenApiRqFiles.queryOptions,
101
- buildQueryOptionsFileImports,
102
- queries,
103
69
  [
104
- ...queries.map((op) => buildQueryOptionsFn(op)),
105
- ...collectStatements(queries, (op) => buildInfiniteQueryOptionsFn(op, ctx)),
70
+ ...each(queries, buildQueryOptionsFn),
71
+ ...each(paginated, buildInfiniteQueryOptionsFn),
106
72
  ],
107
73
  ],
108
74
  [
109
75
  OpenApiRqFiles.suspense,
110
- buildHookFileImports,
111
- queries,
112
76
  [
113
- ...queries.map((op) => buildUseSuspenseQueryHook(op, ctx)),
114
- ...collectStatements(queries, (op) => buildUseSuspenseInfiniteQueryHook(op, ctx)),
77
+ ...each(queries, buildUseSuspenseQueryHook),
78
+ ...each(paginated, buildUseSuspenseInfiniteQueryHook),
115
79
  ],
116
80
  ],
117
81
  [
118
82
  OpenApiRqFiles.infiniteQueries,
119
- buildHookFileImports,
120
- paginated,
121
- collectStatements(queries, (op) => buildUseInfiniteQueryHook(op, ctx)),
83
+ each(paginated, buildUseInfiniteQueryHook),
122
84
  ],
123
85
  [
124
86
  OpenApiRqFiles.prefetch,
125
- buildHookFileImports,
126
- queries,
127
87
  [
128
- ...queries.map((op) => buildPrefetchFn(op)),
129
- ...collectStatements(queries, (op) => buildPrefetchInfiniteQueryFn(op, ctx)),
88
+ ...each(queries, buildPrefetchFn),
89
+ ...each(paginated, buildPrefetchInfiniteQueryFn),
130
90
  ],
131
91
  ],
132
- [
133
- OpenApiRqFiles.ensureQueryData,
134
- buildHookFileImports,
135
- queries,
136
- queries.map((op) => buildEnsureQueryDataFn(op)),
137
- ],
92
+ [OpenApiRqFiles.ensureQueryData, each(queries, buildEnsureQueryDataFn)],
138
93
  ];
94
+ }
95
+ /**
96
+ * Add the generated header comment to file content.
97
+ */
98
+ function addHeaderComment(content, version) {
99
+ const comment = `// generated with @7nohe/openapi-react-query-codegen@${version} \n\n`;
100
+ return comment + content;
101
+ }
102
+ /**
103
+ * Generate the React Query files for the operations of a specification.
104
+ */
105
+ export function generateAllFiles(operations, ctx) {
106
+ let files = buildFiles(operations, ctx);
107
+ // Built again only when a name the hooks derive is already taken.
108
+ const names = settleHookNames(files);
109
+ if (names) {
110
+ files = buildFiles(operations.map((op) => ({ ...op, names: names.get(op) })), ctx);
111
+ }
139
112
  return [
140
113
  {
141
114
  name: `${OpenApiRqFiles.index}.ts`,
142
115
  content: addHeaderComment(indexFile(ctx), ctx.version),
143
116
  },
144
- ...files.map(([name, imports, operations, statements]) => ({
117
+ ...files.map(([name, declared]) => ({
145
118
  name: `${name}.ts`,
146
- content: addHeaderComment(createFile(ctx, imports, operations, statements), ctx.version),
119
+ content: addHeaderComment(createFile(ctx, declared.map(({ statement }) => statement)), ctx.version),
147
120
  })),
148
121
  ];
149
122
  }
@@ -0,0 +1,69 @@
1
+ import type { OperationInfo } from "../types.mjs";
2
+ import type { Statement } from "./statement.mjs";
3
+ /** What the hook files declare for one operation, each under its name. */
4
+ export interface HookNames {
5
+ /** `FindPetsDefaultResponse` */
6
+ defaultResponse: string;
7
+ /** `FindPetsQueryResult` */
8
+ queryResult: string;
9
+ /** `AddPetMutationResult` */
10
+ mutationResult: string;
11
+ /** `useFindPetsKey` */
12
+ key: string;
13
+ /** `UseFindPetsKeyFn` */
14
+ keyFn: string;
15
+ /** `FindPetsInfiniteClientOptions` */
16
+ infiniteClientOptions: string;
17
+ /** `useFindPetsInfiniteKey` */
18
+ infiniteKey: string;
19
+ /** `UseFindPetsInfiniteKeyFn` */
20
+ infiniteKeyFn: string;
21
+ /** `useFindPets`, for a query and for a mutation */
22
+ hook: string;
23
+ /** `useFindPetsSuspense` */
24
+ suspenseHook: string;
25
+ /** `useFindPetsInfinite` */
26
+ infiniteHook: string;
27
+ /** `useFindPetsSuspenseInfinite` */
28
+ suspenseInfiniteHook: string;
29
+ /** `findPetsOptions` */
30
+ options: string;
31
+ /** `findPetsInfiniteOptions` */
32
+ infiniteOptions: string;
33
+ /** `prefetchUseFindPets` */
34
+ prefetch: string;
35
+ /** `prefetchUseFindPetsInfinite` */
36
+ prefetchInfinite: string;
37
+ /** `ensureUseFindPetsData` */
38
+ ensureData: string;
39
+ }
40
+ /**
41
+ * An operation as the builders take it. `names` is set only when one of the
42
+ * names had to give way to something else in its file.
43
+ */
44
+ export type HookOperation = OperationInfo & {
45
+ names?: HookNames;
46
+ };
47
+ /** The names the hook files declare for an operation. */
48
+ export declare function hookNames(op: HookOperation): HookNames;
49
+ /** A statement of a generated file, and the operation it was built for. */
50
+ export type Declared = {
51
+ op: HookOperation;
52
+ statement: Statement;
53
+ };
54
+ /**
55
+ * Find the names that cannot stay as they are spelled, given the files built
56
+ * with those names, and give each a number.
57
+ *
58
+ * A name has to differ from what its file imports (an SDK function, a model, a
59
+ * fixed name such as `useQuery`) and from the other names declared in the
60
+ * file, or in any file `index.ts` re-exports next to it. The specification's
61
+ * names always stay: `getUserOptions` is the operation of that name, and the
62
+ * options of `getUser` become `getUserOptions2`. Between two derived names the
63
+ * later one gives way, and `common.ts` comes last, so that a hook keeps its
64
+ * name before a key does (`useGetApiKey` is the hook of `getApiKey`, not the
65
+ * key of `getApi`).
66
+ *
67
+ * Returns nothing when every name can stay, which is the usual case.
68
+ */
69
+ export declare function settleHookNames(files: ReadonlyArray<readonly [name: string, declared: Declared[]]>): Map<HookOperation, HookNames> | undefined;