@kubb/plugin-vue-query 5.0.0-alpha.9 → 5.0.0-beta.100

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 (39) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +38 -23
  3. package/dist/index.cjs +1651 -140
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +358 -6
  6. package/dist/index.js +1618 -138
  7. package/dist/index.js.map +1 -1
  8. package/package.json +48 -76
  9. package/dist/components-Yjoe78Y7.cjs +0 -1119
  10. package/dist/components-Yjoe78Y7.cjs.map +0 -1
  11. package/dist/components-_AMBl0g-.js +0 -1029
  12. package/dist/components-_AMBl0g-.js.map +0 -1
  13. package/dist/components.cjs +0 -9
  14. package/dist/components.d.ts +0 -242
  15. package/dist/components.js +0 -2
  16. package/dist/generators-CR34GjVu.js +0 -661
  17. package/dist/generators-CR34GjVu.js.map +0 -1
  18. package/dist/generators-DH8VkK1q.cjs +0 -678
  19. package/dist/generators-DH8VkK1q.cjs.map +0 -1
  20. package/dist/generators.cjs +0 -5
  21. package/dist/generators.d.ts +0 -511
  22. package/dist/generators.js +0 -2
  23. package/dist/types-CgDFUvfZ.d.ts +0 -211
  24. package/src/components/InfiniteQuery.tsx +0 -208
  25. package/src/components/InfiniteQueryOptions.tsx +0 -249
  26. package/src/components/Mutation.tsx +0 -185
  27. package/src/components/MutationKey.tsx +0 -1
  28. package/src/components/Query.tsx +0 -208
  29. package/src/components/QueryKey.tsx +0 -94
  30. package/src/components/QueryOptions.tsx +0 -185
  31. package/src/components/index.ts +0 -7
  32. package/src/generators/index.ts +0 -3
  33. package/src/generators/infiniteQueryGenerator.tsx +0 -213
  34. package/src/generators/mutationGenerator.tsx +0 -176
  35. package/src/generators/queryGenerator.tsx +0 -191
  36. package/src/index.ts +0 -2
  37. package/src/plugin.ts +0 -218
  38. package/src/types.ts +0 -176
  39. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.js CHANGED
@@ -1,157 +1,1637 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { c as camelCase, l as pascalCase, r as MutationKey, s as QueryKey } from "./components-_AMBl0g-.js";
3
- import { n as mutationGenerator, r as infiniteQueryGenerator, t as queryGenerator } from "./generators-CR34GjVu.js";
1
+ import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
2
+ import { Resolver, Url, ast, createResolver, defineGenerator, definePlugin } from "kubb/kit";
4
3
  import path from "node:path";
5
- import { createPlugin, getBarrelFiles, getMode } from "@kubb/core";
6
- import { pluginClientName } from "@kubb/plugin-client";
7
- import { source } from "@kubb/plugin-client/templates/clients/axios.source";
8
- import { source as source$1 } from "@kubb/plugin-client/templates/clients/fetch.source";
9
- import { source as source$2 } from "@kubb/plugin-client/templates/config.source";
10
- import { OperationGenerator, pluginOasName } from "@kubb/plugin-oas";
11
- import { pluginTsName } from "@kubb/plugin-ts";
12
- import { pluginZodName } from "@kubb/plugin-zod";
4
+ import { createFunctionParameter, createFunctionParameters, createObjectBindingPattern, createTypeLiteral, functionPrinter, pluginTsName } from "@kubb/plugin-ts";
5
+ import { File, Function, Type, jsxRenderer } from "kubb/jsx";
6
+ import { Fragment, jsx, jsxs } from "kubb/jsx/jsx-runtime";
7
+ //#region ../../internals/shared/src/params.ts
8
+ /**
9
+ * Drops parameters that share the same name, keeping the first.
10
+ *
11
+ * A malformed spec can declare the same parameter name twice within one `in` location. Both would
12
+ * resolve to the same output property, so emitting both would yield an object type with a duplicate
13
+ * member, which TypeScript rejects. This is a defensive guard against that case, not a casing guard:
14
+ * parameter names flow through unchanged, so no two distinct names ever collide here anymore.
15
+ */
16
+ function dedupeParams(params) {
17
+ const seen = /* @__PURE__ */ new Set();
18
+ return params.filter((param) => {
19
+ if (seen.has(param.name)) return false;
20
+ seen.add(param.name);
21
+ return true;
22
+ });
23
+ }
24
+ //#endregion
25
+ //#region ../../internals/shared/src/operation.ts
26
+ /**
27
+ * Builds the `ResolverFileParams` every operation generator passes to
28
+ * `resolver.file`: a file named `name`, tagged by the operation's first
29
+ * tag (or `'default'`), at the operation's path. Centralizes the entry object
30
+ * that was repeated at dozens of call sites across the client and query plugins.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
35
+ * ```
36
+ */
37
+ function operationFileEntry(node, name, extname = ".ts") {
38
+ return {
39
+ name,
40
+ extname,
41
+ tag: node.tags[0] ?? "default",
42
+ path: node.path
43
+ };
44
+ }
45
+ function getOperationLink(node, link) {
46
+ if (!link) return null;
47
+ if (typeof link === "function") return link(node) ?? null;
48
+ return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
49
+ }
50
+ /**
51
+ * Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several
52
+ * are present and the union, default, and form-data flags the client uses to pick one.
53
+ */
54
+ function buildContentTypeInfo(contentTypes) {
55
+ const isMultipleContentTypes = contentTypes.length > 1;
56
+ return {
57
+ contentTypes,
58
+ isMultipleContentTypes,
59
+ contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
60
+ defaultContentType: contentTypes[0] ?? "application/json",
61
+ hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
62
+ };
63
+ }
64
+ function getContentTypeInfo(node) {
65
+ return buildContentTypeInfo(node.requestBody?.content?.map((e) => e.contentType) ?? []);
66
+ }
67
+ /**
68
+ * The request-body counterpart for the primary success response: the content types it documents and
69
+ * whether several are present, so the client can let a caller pick which one to accept.
70
+ */
71
+ function getResponseContentTypeInfo(node) {
72
+ return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? []);
73
+ }
74
+ function buildRequestConfigType(node) {
75
+ const request = getContentTypeInfo(node);
76
+ const response = getResponseContentTypeInfo(node);
77
+ const configType = `Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>`;
78
+ const members = [request.isMultipleContentTypes ? `request?: ${request.contentTypeUnion}` : null, response.isMultipleContentTypes ? `response?: ${response.contentTypeUnion}` : null].filter(Boolean);
79
+ return members.length ? `${configType} & { contentType?: { ${members.join("; ")} } }` : configType;
80
+ }
81
+ /**
82
+ * Builds the `client?:` option type shared by the generated query hooks (`useQuery`,
83
+ * `useInfiniteQuery`, `useSWR`, ...). Unlike {@link buildRequestConfigType}, it never adds a
84
+ * `contentType?:` member: query hooks wrap GET operations, which carry no request body to select a
85
+ * content type for.
86
+ */
87
+ function buildClientOptionType() {
88
+ return `Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>`;
89
+ }
90
+ /**
91
+ * Which of the grouped request options an operation carries.
92
+ */
93
+ function getRequestGroups(node) {
94
+ const { path, query, header } = getOperationParameters(node);
95
+ return {
96
+ path: path.length > 0,
97
+ query: query.length > 0,
98
+ body: Boolean(node.requestBody?.content?.[0]?.schema),
99
+ headers: header.length > 0
100
+ };
101
+ }
102
+ /**
103
+ * Resolves which grouped request options an operation carries together with whether each group
104
+ * holds a required member. The grouped parameter stays optional only when nothing inside it is
105
+ * required, matching the generated `RequestConfig` type.
106
+ */
107
+ function getRequestGroupOptionality(node) {
108
+ const groups = getRequestGroups(node);
109
+ const { path, query, header } = getOperationParameters(node);
110
+ const hasRequiredPath = path.some((param) => param.required);
111
+ const hasRequiredQuery = query.some((param) => param.required);
112
+ const hasRequiredHeader = header.some((param) => param.required);
113
+ return {
114
+ groups,
115
+ hasRequiredPath,
116
+ hasRequiredQuery,
117
+ hasRequiredHeader,
118
+ isOptional: !hasRequiredPath && !hasRequiredQuery && !hasRequiredHeader && !groups.body
119
+ };
120
+ }
121
+ function buildOperationComments(node, options = {}) {
122
+ const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
123
+ const linkComment = getOperationLink(node, link);
124
+ const filteredComments = (linkPosition === "beforeDeprecated" ? [
125
+ node.description && `@description ${node.description}`,
126
+ node.summary && `@summary ${node.summary}`,
127
+ linkComment,
128
+ node.deprecated && "@deprecated"
129
+ ] : [
130
+ node.description && `@description ${node.description}`,
131
+ node.summary && `@summary ${node.summary}`,
132
+ node.deprecated && "@deprecated",
133
+ linkComment
134
+ ]).filter((comment) => Boolean(comment));
135
+ if (!splitLines) return filteredComments;
136
+ return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
137
+ }
138
+ function getOperationParameters(node) {
139
+ return {
140
+ path: dedupeParams(node.parameters.filter((param) => param.in === "path")),
141
+ query: dedupeParams(node.parameters.filter((param) => param.in === "query")),
142
+ header: dedupeParams(node.parameters.filter((param) => param.in === "header")),
143
+ cookie: dedupeParams(node.parameters.filter((param) => param.in === "cookie"))
144
+ };
145
+ }
146
+ function getStatusCodeNumber(statusCode) {
147
+ const code = Number(statusCode);
148
+ return Number.isNaN(code) ? null : code;
149
+ }
150
+ function isSuccessStatusCode(statusCode) {
151
+ const code = getStatusCodeNumber(statusCode);
152
+ return code !== null && code >= 200 && code < 300;
153
+ }
154
+ function isErrorStatusCode(statusCode) {
155
+ const code = getStatusCodeNumber(statusCode);
156
+ return code !== null && code >= 400;
157
+ }
158
+ function getSuccessResponses(responses) {
159
+ return responses.filter((response) => isSuccessStatusCode(response.statusCode));
160
+ }
161
+ function getOperationSuccessResponses(node) {
162
+ return getSuccessResponses(node.responses);
163
+ }
164
+ function getPrimarySuccessResponse(node) {
165
+ return getOperationSuccessResponses(node)[0] ?? null;
166
+ }
167
+ function resolveErrorNames(node, resolver) {
168
+ return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.response.status(node, response.statusCode));
169
+ }
170
+ function resolveSuccessNames(node, resolver) {
171
+ return node.responses.filter((response) => isSuccessStatusCode(response.statusCode)).map((response) => resolver.response.status(node, response.statusCode));
172
+ }
173
+ function resolveStatusCodeNames(node, resolver) {
174
+ return node.responses.map((response) => resolver.response.status(node, response.statusCode));
175
+ }
176
+ const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
177
+ function resolveOperationTypeNames(node, resolver, options = {}) {
178
+ const cacheKey = `${node.operationId}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${options.includeParams === false ? "noparams" : ""}\0${(options.exclude ?? []).join(",")}`;
179
+ let byResolver = typeNamesByResolver.get(resolver);
180
+ if (byResolver) {
181
+ const cached = byResolver.get(cacheKey);
182
+ if (cached) return cached;
183
+ } else {
184
+ byResolver = /* @__PURE__ */ new Map();
185
+ typeNamesByResolver.set(resolver, byResolver);
186
+ }
187
+ const { path, query, header } = getOperationParameters(node);
188
+ const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
189
+ const exclude = new Set(options.exclude ?? []);
190
+ const paramNames = options.includeParams === false ? [] : [
191
+ ...path.map((param) => resolver.param.path(node, param)),
192
+ ...query.map((param) => resolver.param.query(node, param)),
193
+ ...header.map((param) => resolver.param.headers(node, param))
194
+ ];
195
+ const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.response.body(node) : null, resolver.response.response(node)];
196
+ const result = (options.order === "body-response-first" ? [
197
+ ...bodyAndResponseNames,
198
+ ...paramNames,
199
+ ...responseStatusNames
200
+ ] : [
201
+ ...paramNames,
202
+ ...bodyAndResponseNames,
203
+ ...responseStatusNames
204
+ ]).filter((name) => Boolean(name) && !exclude.has(name));
205
+ byResolver.set(cacheKey, result);
206
+ return result;
207
+ }
208
+ //#endregion
209
+ //#region ../../internals/utils/src/casing.ts
210
+ /**
211
+ * Shared implementation for camelCase and PascalCase conversion.
212
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
213
+ * and capitalizes each word according to `pascal`.
214
+ *
215
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
216
+ */
217
+ function toCamelOrPascal(text, pascal) {
218
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
219
+ if (word.length > 1 && word === word.toUpperCase()) return word;
220
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
221
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
222
+ }
223
+ /**
224
+ * Converts `text` to camelCase.
225
+ *
226
+ * @example Word boundaries
227
+ * `camelCase('hello-world') // 'helloWorld'`
228
+ *
229
+ * @example With a prefix
230
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
231
+ */
232
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
233
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
234
+ }
235
+ /**
236
+ * Uppercases only the first character of `text`, leaving the rest untouched.
237
+ * Unlike {@link pascalCase} it never re-splits word boundaries or strips characters.
238
+ *
239
+ * @example
240
+ * `capitalize('getPetById') // 'GetPetById'`
241
+ */
242
+ function capitalize(text) {
243
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
244
+ }
245
+ //#endregion
246
+ //#region ../../internals/utils/src/strings.ts
247
+ /**
248
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
249
+ * `accessor`. Returns `null` for an empty path.
250
+ *
251
+ * @example
252
+ * ```ts
253
+ * getNestedAccessor('pagination.next.id', 'lastPage')
254
+ * // "lastPage?.['pagination']?.['next']?.['id']"
255
+ * ```
256
+ */
257
+ function getNestedAccessor(param, accessor) {
258
+ const parts = Array.isArray(param) ? param : param.split(".");
259
+ if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
260
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
261
+ }
262
+ //#endregion
263
+ //#region ../../internals/shared/src/group.ts
264
+ /**
265
+ * Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
266
+ * shared default naming so every plugin groups output consistently:
267
+ *
268
+ * - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
269
+ * - other groups use the camelCased group (`pet store` → `petStore`).
270
+ *
271
+ * A user-provided `group.name` always wins over the default namer, so callers stay in
272
+ * control of their output folders. Returns `null` when grouping is disabled, matching the
273
+ * per-plugin convention.
274
+ *
275
+ * @param group - The user-supplied group option, or `undefined` to disable grouping.
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * createGroupConfig(group) // shared across every plugin
280
+ * ```
281
+ */
282
+ function createGroupConfig(group) {
283
+ if (!group) return null;
284
+ const defaultName = (ctx) => {
285
+ if (group.type === "path") return `${ctx.group.split("/")[1]}`;
286
+ return camelCase(ctx.group);
287
+ };
288
+ return {
289
+ ...group,
290
+ name: group.name ? group.name : defaultName
291
+ };
292
+ }
293
+ //#endregion
294
+ //#region ../../internals/tanstack-query/src/utils.ts
295
+ /**
296
+ * The grouped request options, ordered for both the destructured signature and the
297
+ * call passed to the underlying client.
298
+ */
299
+ const requestGroupOrder = [
300
+ "path",
301
+ "query",
302
+ "body",
303
+ "headers"
304
+ ];
305
+ /**
306
+ * Widens a request-group member type so a generated TanStack hook accepts either the value or a
307
+ * deferred value. Both plugins apply this through the `memberTypeWrapper` of `buildGroupedRequestParam`;
308
+ * they only differ in how the deferred form is later resolved.
309
+ *
310
+ * `maybeRefOrGetter` is used by vue-query, which keeps the ref/getter live and unwraps it lazily with
311
+ * `toValue` because vue-query keys are reactive. `maybeValueOrGetter` is used by react-query, which
312
+ * resolves the getter once at the hook boundary and forwards a plain value because React Query hashes
313
+ * keys structurally and cannot hold a function.
314
+ */
315
+ function maybeRefOrGetter(type) {
316
+ return `MaybeRefOrGetter<${type}>`;
317
+ }
318
+ /**
319
+ * Builds the grouped `{ path, query, body, headers }` parameter that mirrors the client
320
+ * function signature. Only the groups the operation carries are emitted, typed from the
321
+ * operation's `Options`. `keys` narrows the emitted groups, used by the query key which
322
+ * never carries `headers`.
323
+ *
324
+ * By default the whole group is typed as the single `Options` reference. When
325
+ * `memberTypeWrapper` is set, each group is emitted as its own member typed from the matching
326
+ * `Options['<group>']` slice and wrapped, used by vue-query to apply
327
+ * `MaybeRefOrGetter` per group.
328
+ */
329
+ function buildGroupedRequestParam(node, options) {
330
+ const { resolver, keys = requestGroupOrder, memberTypeWrapper } = options;
331
+ const { groups, hasRequiredPath, hasRequiredQuery, hasRequiredHeader } = getRequestGroupOptionality(node);
332
+ const names = keys.filter((key) => groups[key]);
333
+ if (names.length === 0) return null;
334
+ const requiredByGroup = {
335
+ path: hasRequiredPath,
336
+ query: hasRequiredQuery,
337
+ body: groups.body,
338
+ headers: hasRequiredHeader
339
+ };
340
+ const isOptional = names.every((name) => !requiredByGroup[name]);
341
+ const optionsName = resolver.response.options(node);
342
+ const omittedKeys = requestGroupOrder.filter((key) => !keys.includes(key));
343
+ const optionsType = omittedKeys.length > 0 ? `Omit<${optionsName}, ${omittedKeys.map((key) => `'${key}'`).join(" | ")}>` : optionsName;
344
+ if (memberTypeWrapper) {
345
+ const members = names.map((name) => ({
346
+ name,
347
+ type: memberTypeWrapper(`${optionsType}['${name}']`),
348
+ optional: !requiredByGroup[name]
349
+ }));
350
+ return createFunctionParameter({
351
+ name: createObjectBindingPattern({ elements: names.map((name) => ({ name })) }),
352
+ type: createTypeLiteral({ members }),
353
+ optional: false,
354
+ ...isOptional ? { default: "{}" } : {}
355
+ });
356
+ }
357
+ return createFunctionParameter({
358
+ name: createObjectBindingPattern({ elements: names.map((name) => ({ name })) }),
359
+ type: optionsType,
360
+ optional: false,
361
+ ...isOptional ? { default: "{}" } : {}
362
+ });
363
+ }
364
+ /**
365
+ * Builds the shared `({ path, query, body, headers }, config = {})` parameter list for a
366
+ * TanStack query-options function. The leading parameter mirrors the client signature, and the
367
+ * trailing `config` is a partial `RequestConfig` minus the grouped data-shape keys, which are passed
368
+ * explicitly. Framework plugins wrap the result when needed, for example vue-query applies `MaybeRefOrGetter`.
369
+ */
370
+ function buildQueryOptionsParams(node, options) {
371
+ const { resolver, memberTypeWrapper } = options;
372
+ return createFunctionParameters({ params: [buildGroupedRequestParam(node, {
373
+ resolver,
374
+ memberTypeWrapper
375
+ }), createFunctionParameter({
376
+ name: "config",
377
+ type: `Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>`,
378
+ default: "{}"
379
+ })].filter((param) => param !== null) });
380
+ }
381
+ /**
382
+ * Builds the call to a client `<op>` function inside a query/mutation hook body. The function takes
383
+ * a single grouped options object, so the operation's request groups are passed as
384
+ * shorthand alongside the spread `config`, with `throwOnError: true` pinned last so a caller's config
385
+ * can't flip the query's error semantics. Queries thread the TanStack `signal`; mutations omit it.
386
+ *
387
+ * When `unwrapName` is set, each request group is passed as an explicit member unwrapped through it,
388
+ * used by vue-query to resolve refs and getters with `toValue(...)` at call time.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * buildClientCall(node, { clientName: 'getPetById', signal: true })
393
+ * // getPetById({ path, ...config, signal: config.signal ?? signal, throwOnError: true })
394
+ * ```
395
+ */
396
+ function buildClientCall(node, options) {
397
+ const { clientName, signal = false, unwrapName } = options;
398
+ const { groups } = getRequestGroupOptionality(node);
399
+ return `${clientName}({ ${[
400
+ "...config",
401
+ ...requestGroupOrder.filter((key) => groups[key]).map((name) => unwrapName ? `${name}: ${unwrapName(name)}` : name),
402
+ signal ? "signal: config.signal ?? signal" : null,
403
+ "throwOnError: true"
404
+ ].filter((part) => part !== null).join(", ")} })`;
405
+ }
406
+ /**
407
+ * Builds the `TData` / `TError` type expressions shared by every generated hook, joining the resolved
408
+ * success responses into `TData` and wrapping the error responses in `ResponseErrorConfig<...>`.
409
+ */
410
+ function buildResponseTypes(node, resolver) {
411
+ const successNames = resolveSuccessNames(node, resolver);
412
+ const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.response.response(node);
413
+ const errorNames = resolveErrorNames(node, resolver);
414
+ return {
415
+ TData: responseName,
416
+ TError: `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`
417
+ };
418
+ }
419
+ function resolveFallbackPageParamType(initialPageParam) {
420
+ if (typeof initialPageParam === "number") return "number";
421
+ if (typeof initialPageParam === "boolean") return "boolean";
422
+ if (typeof initialPageParam !== "string") return "unknown";
423
+ if (!initialPageParam.includes(" as ")) return "string";
424
+ return initialPageParam.split(" as ").at(-1) ?? "unknown";
425
+ }
426
+ /**
427
+ * Resolves the `TPageParam` generic for the infinite-query hooks. Prefers the type read from the
428
+ * configured `queryParam` on the operation's query object, and falls back to the type inferred from
429
+ * `initialPageParam` when that parameter type is unavailable. Also returns the query params type name
430
+ * so callers can reuse it when rewriting the paginated request.
431
+ */
432
+ function resolvePageParamType(node, { resolver, initialPageParam, queryParam }) {
433
+ const firstQueryParam = getOperationParameters(node).query[0];
434
+ const groupName = firstQueryParam ? resolver.param.query(node, firstQueryParam) : null;
435
+ const queryParamsTypeName = groupName !== (firstQueryParam ? resolver.param.name(node, firstQueryParam) : null) ? groupName : null;
436
+ const queryParamType = queryParam && queryParamsTypeName ? `${queryParamsTypeName}['${queryParam}']` : null;
437
+ if (!queryParamType) return {
438
+ queryParamsTypeName,
439
+ pageParamType: resolveFallbackPageParamType(initialPageParam)
440
+ };
441
+ return {
442
+ queryParamsTypeName,
443
+ pageParamType: initialPageParam !== void 0 && initialPageParam !== null ? `NonNullable<${queryParamType}>` : queryParamType
444
+ };
445
+ }
446
+ /**
447
+ * Applies the shared query defaults during plugin setup: `false` disables query generation, and an
448
+ * object merges over `methods: ['GET']` and the plugin's runtime `importPath`.
449
+ */
450
+ function resolveQueryConfig(query, options) {
451
+ if (query === false) return false;
452
+ return {
453
+ importPath: options.importPath,
454
+ methods: ["GET"],
455
+ ...query
456
+ };
457
+ }
458
+ /**
459
+ * Applies the shared mutation defaults during plugin setup: `false` disables mutation generation,
460
+ * and an object merges over `methods: ['POST', 'PUT', 'PATCH', 'DELETE']` and the plugin's runtime
461
+ * `importPath`.
462
+ */
463
+ function resolveMutationConfig(mutation, options) {
464
+ if (mutation === false) return false;
465
+ return {
466
+ importPath: options.importPath,
467
+ methods: [
468
+ "POST",
469
+ "PUT",
470
+ "PATCH",
471
+ "DELETE"
472
+ ],
473
+ ...mutation
474
+ };
475
+ }
476
+ /**
477
+ * Applies the shared infinite-query defaults during plugin setup: a falsy value disables infinite
478
+ * queries, and an object merges over `queryParam: 'id'` and `initialPageParam: 0` with the cursor
479
+ * paths cleared.
480
+ */
481
+ function resolveInfiniteConfig(infinite) {
482
+ if (!infinite) return false;
483
+ return {
484
+ queryParam: "id",
485
+ initialPageParam: 0,
486
+ cursorParam: null,
487
+ nextParam: null,
488
+ previousParam: null,
489
+ ...infinite
490
+ };
491
+ }
492
+ //#endregion
493
+ //#region ../../internals/tanstack-query/src/components/InfiniteQueryOptions.tsx
494
+ const declarationPrinter$7 = functionPrinter({ mode: "declaration" });
495
+ const callPrinter$4 = functionPrinter({ mode: "call" });
496
+ function InfiniteQueryOptions$1({ name, clientName, initialPageParam, cursorParam, nextParam, previousParam, node, tsResolver, queryParam, queryKeyName, queryKeyType = "typeof queryKey", memberTypeWrapper, unwrapName }) {
497
+ const { TData: queryFnDataType, TError: errorType } = buildResponseTypes(node, tsResolver);
498
+ const { queryParamsTypeName, pageParamType } = resolvePageParamType(node, {
499
+ resolver: tsResolver,
500
+ initialPageParam,
501
+ queryParam
502
+ });
503
+ const groupedKeyParam = buildGroupedRequestParam(node, {
504
+ resolver: tsResolver,
505
+ keys: [
506
+ "path",
507
+ "query",
508
+ "body"
509
+ ],
510
+ memberTypeWrapper
511
+ });
512
+ const queryKeyParamsNode = createFunctionParameters({ params: groupedKeyParam ? [groupedKeyParam] : [] });
513
+ const queryKeyParamsCall = callPrinter$4.print(queryKeyParamsNode) ?? "";
514
+ const paramsNode = buildQueryOptionsParams(node, {
515
+ resolver: tsResolver,
516
+ memberTypeWrapper
517
+ });
518
+ const paramsSignature = declarationPrinter$7.print(paramsNode) ?? "";
519
+ const queryFnBody = `const { data } = await ${buildClientCall(node, {
520
+ clientName,
521
+ signal: true,
522
+ unwrapName
523
+ })}
524
+ return data`;
525
+ const hasNewParams = nextParam != null || previousParam != null;
526
+ const [getNextPageParamExpr, getPreviousPageParamExpr] = (() => {
527
+ if (hasNewParams) {
528
+ const nextAccessor = nextParam ? getNestedAccessor(nextParam, "lastPage") : null;
529
+ const prevAccessor = previousParam ? getNestedAccessor(previousParam, "firstPage") : null;
530
+ return [nextAccessor ? `getNextPageParam: (lastPage) => ${nextAccessor}` : null, prevAccessor ? `getPreviousPageParam: (firstPage) => ${prevAccessor}` : null];
531
+ }
532
+ if (cursorParam) return [`getNextPageParam: (lastPage) => lastPage['${cursorParam}']`, `getPreviousPageParam: (firstPage) => firstPage['${cursorParam}']`];
533
+ return ["getNextPageParam: (lastPage, _allPages, lastPageParam) => Array.isArray(lastPage) && lastPage.length === 0 ? undefined : lastPageParam + 1", "getPreviousPageParam: (_firstPage, _allPages, firstPageParam) => firstPageParam <= 1 ? undefined : firstPageParam - 1"];
534
+ })();
535
+ const queryOptionsArr = [
536
+ `initialPageParam: ${typeof initialPageParam === "string" ? JSON.stringify(initialPageParam) : initialPageParam}`,
537
+ getNextPageParamExpr,
538
+ getPreviousPageParamExpr
539
+ ].filter(Boolean);
540
+ const infiniteOverrideParams = queryParam && queryParamsTypeName ? `query = {
541
+ ...(query ?? {}),
542
+ ['${queryParam}']: pageParam as unknown as ${queryParamsTypeName}['${queryParam}'],
543
+ } as ${queryParamsTypeName}` : "";
544
+ const queryFnArgs = infiniteOverrideParams ? "{ signal, pageParam }" : "{ signal }";
545
+ const queryFnStatements = infiniteOverrideParams ? `${infiniteOverrideParams}\n ${queryFnBody}` : queryFnBody;
546
+ return /* @__PURE__ */ jsx(File.Source, {
547
+ name,
548
+ isExportable: true,
549
+ isIndexable: true,
550
+ children: /* @__PURE__ */ jsx(Function, {
551
+ name,
552
+ export: true,
553
+ params: paramsSignature,
554
+ children: `
555
+ const queryKey = ${queryKeyName}(${queryKeyParamsCall})
556
+ return infiniteQueryOptions<${queryFnDataType}, ${errorType}, InfiniteData<${queryFnDataType}>, ${queryKeyType}, ${pageParamType}>({
557
+ queryKey,
558
+ queryFn: async (${queryFnArgs}) => {
559
+ ${queryFnStatements}
560
+ },
561
+ ${queryOptionsArr.join(",\n ")}
562
+ })
563
+ `
564
+ })
565
+ });
566
+ }
567
+ __name(InfiniteQueryOptions$1, "InfiniteQueryOptions");
568
+ //#endregion
569
+ //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
570
+ const declarationPrinter$6 = functionPrinter({ mode: "declaration" });
571
+ const mutationKeyTransformer = ({ node }) => {
572
+ if (!node.path) return [];
573
+ return [`{ url: '${Url.toPath(node.path)}' }`];
574
+ };
575
+ function MutationKey({ name, node, transformer }) {
576
+ const paramsNode = createFunctionParameters({ params: [] });
577
+ const paramsSignature = declarationPrinter$6.print(paramsNode) ?? "";
578
+ const keys = (transformer ?? mutationKeyTransformer)({
579
+ node,
580
+ casing: "camelcase"
581
+ });
582
+ return /* @__PURE__ */ jsx(File.Source, {
583
+ name,
584
+ isExportable: true,
585
+ isIndexable: true,
586
+ children: /* @__PURE__ */ jsx(Function.Arrow, {
587
+ name,
588
+ export: true,
589
+ params: paramsSignature,
590
+ singleLine: true,
591
+ children: `[${keys.join(", ")}] as const`
592
+ })
593
+ });
594
+ }
595
+ //#endregion
596
+ //#region ../../internals/tanstack-query/src/resolver.ts
597
+ /**
598
+ * Builds the shared query namespace for a variant. Spread the result into
599
+ * `createResolver` once per variant the plugin supports.
600
+ *
601
+ * @example
602
+ * ```ts
603
+ * createResolver<PluginReactQuery>({
604
+ * query: createQueryResolver(),
605
+ * suspenseQuery: createQueryResolver('Suspense'),
606
+ * })
607
+ * ```
608
+ */
609
+ function createQueryResolver(variant = "") {
610
+ return {
611
+ name(node) {
612
+ return `use${capitalize(this.name(node.operationId))}${variant}`;
613
+ },
614
+ optionsName(node) {
615
+ return `${this.name(node.operationId)}${variant}QueryOptions`;
616
+ },
617
+ keyName(node) {
618
+ return `${this.name(node.operationId)}${variant}QueryKey`;
619
+ },
620
+ keyTypeName(node) {
621
+ return `${capitalize(this.name(node.operationId))}${variant}QueryKey`;
622
+ },
623
+ clientName(node) {
624
+ return `${this.name(node.operationId)}${variant}`;
625
+ }
626
+ };
627
+ }
628
+ /**
629
+ * Builds the shared mutation namespace. Spread the result into
630
+ * `createResolver` and add plugin-specific methods (`optionsName`,
631
+ * `typeName`, `argTypeName`) next to it.
632
+ *
633
+ * @example
634
+ * ```ts
635
+ * createResolver<PluginSwr>({ mutation: { ...createMutationResolver(), argTypeName(node) {...} } })
636
+ * ```
637
+ */
638
+ function createMutationResolver() {
639
+ return {
640
+ name(node) {
641
+ return `use${capitalize(this.name(node.operationId))}`;
642
+ },
643
+ keyName(node) {
644
+ return `${this.name(node.operationId)}MutationKey`;
645
+ }
646
+ };
647
+ }
648
+ functionPrinter({ mode: "declaration" });
649
+ const queryKeyTransformer = ({ node }) => {
650
+ if (!node.path) return [];
651
+ const hasPathParams = getOperationParameters(node).path.length > 0;
652
+ const hasQueryParams = getOperationParameters(node).query.length > 0;
653
+ const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
654
+ return [
655
+ hasPathParams ? `{ url: '${Url.toPath(node.path)}', params: path }` : `{ url: '${Url.toPath(node.path)}' }`,
656
+ hasQueryParams ? "...(query ? [query] : [])" : null,
657
+ hasRequestBody ? "...(body ? [body] : [])" : null
658
+ ].filter(Boolean);
659
+ };
660
+ //#endregion
661
+ //#region ../../internals/client/src/resolveClient.ts
662
+ /**
663
+ * Resolves which client plugin a consumer (react-query, vue-query, swr, mcp) should call for an
664
+ * operation, shared so the selection rules and diagnostics stay in one place.
665
+ *
666
+ * Every client runtime lives in a dedicated client plugin, so a consumer always calls a registered
667
+ * contract client plugin (plugin-fetch or plugin-axios) and never emits its own inline client:
668
+ *
669
+ * - `contract` — a registered contract client plugin owns the `<op>` functions and the consumer
670
+ * imports and calls them.
671
+ * - `error` — no client plugin is registered, several are registered without a selector, or the
672
+ * requested one is missing.
673
+ *
674
+ * The `client` string selects explicitly (`'fetch'` / `'axios'`); when it is unset a lone registered
675
+ * contract client plugin is picked up automatically.
676
+ */
677
+ const pluginFetchName = "plugin-fetch";
678
+ const pluginAxiosName = "plugin-axios";
679
+ const selectorToPlugin = {
680
+ fetch: pluginFetchName,
681
+ axios: pluginAxiosName
682
+ };
683
+ const contractPlugins = [pluginFetchName, pluginAxiosName];
684
+ /**
685
+ * Applies the `client` resolution rules. See the module comment for the strategy shape.
686
+ *
687
+ * @example
688
+ * ```ts
689
+ * resolveClient({ client: 'fetch', pluginNames: ['plugin-ts', 'plugin-fetch'] })
690
+ * // { kind: 'contract', pluginName: 'plugin-fetch' }
691
+ * ```
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * resolveClient({ client: undefined, pluginNames: ['plugin-ts'] })
696
+ * // { kind: 'error', message: 'No client plugin is registered…' }
697
+ * ```
698
+ */
699
+ function resolveClient(options) {
700
+ const { client, pluginNames } = options;
701
+ const has = (name) => pluginNames.includes(name);
702
+ if (client === "fetch" || client === "axios") {
703
+ const pluginName = selectorToPlugin[client];
704
+ if (!has(pluginName)) return {
705
+ kind: "error",
706
+ message: `\`client: '${client}'\` is set but \`@kubb/plugin-${client}\` is not registered in \`plugins\`. Add it, or drop \`client\` to use a different client plugin.`
707
+ };
708
+ return {
709
+ kind: "contract",
710
+ pluginName
711
+ };
712
+ }
713
+ const registered = contractPlugins.filter(has);
714
+ if (registered.length === 1) return {
715
+ kind: "contract",
716
+ pluginName: registered[0]
717
+ };
718
+ if (registered.length > 1) return {
719
+ kind: "error",
720
+ message: `Multiple client plugins are registered (${registered.map((name) => `\`@kubb/${name}\``).join(", ")}). Set \`client: 'fetch' | 'axios'\` to choose which client the hooks call, or register a single client plugin.`
721
+ };
722
+ return {
723
+ kind: "error",
724
+ message: "No client plugin is registered. Add `@kubb/plugin-axios` or `@kubb/plugin-fetch` to `plugins` so the generated code has an HTTP client to call."
725
+ };
726
+ }
727
+ /**
728
+ * Resolves the contract client during a consumer plugin's setup hook. Extracts the plugin names
729
+ * from the raw `plugins` config, applies {@link resolveClient}, and throws the diagnostic on a
730
+ * misconfiguration so every consumer fails fast with the same message.
731
+ */
732
+ function resolveContractClient(options) {
733
+ const { client, plugins = [] } = options;
734
+ const resolved = resolveClient({
735
+ client,
736
+ pluginNames: plugins.map((plugin) => plugin.name).filter((name) => Boolean(name))
737
+ });
738
+ if (resolved.kind === "error") throw new Error(resolved.message);
739
+ return resolved;
740
+ }
741
+ //#endregion
742
+ //#region ../../internals/client/src/resolveClientOperation.ts
743
+ /**
744
+ * Resolves the contract client `<op>` a consumer (query hook, MCP handler) imports, by looking up
745
+ * the registered contract client plugin's resolver and output. Works for any contract client plugin
746
+ * (plugin-fetch or plugin-axios). Returns `null` when no contract plugin is in play (the inline
747
+ * path). The plugin injects `.kubb/client.ts` at the global output root, the same path consumers
748
+ * read `RequestConfig` / `ResponseErrorConfig` from.
749
+ */
750
+ function resolveClientOperation(options) {
751
+ const { clientPlugin, driver, node, root, output } = options;
752
+ if (!clientPlugin) return null;
753
+ const resolver = driver.getResolver(clientPlugin.pluginName);
754
+ const plugin = driver.getPlugin(clientPlugin.pluginName);
755
+ const file = resolver.file({
756
+ ...operationFileEntry(node, node.operationId),
757
+ root,
758
+ output: plugin?.options?.output ?? output,
759
+ group: plugin?.options?.group ?? void 0
760
+ });
761
+ return {
762
+ name: resolver.name(node.operationId),
763
+ path: file.path,
764
+ clientPath: path.resolve(root, ".kubb/client.ts")
765
+ };
766
+ }
767
+ //#endregion
768
+ //#region src/utils.ts
769
+ /**
770
+ * Builds the call to a contract client `<op>` function inside a vue-query composable body. The
771
+ * function takes a single grouped options object, so `config` is spread first, then the operation's
772
+ * request groups are unwrapped with `toValue()`, then the abort `signal` for queries, with
773
+ * `throwOnError: true` pinned last so a caller's config can't flip the query's error semantics.
774
+ * Mutations omit the `signal`.
775
+ */
776
+ function buildVueClientCall(node, options) {
777
+ return buildClientCall(node, {
778
+ ...options,
779
+ unwrapName: (name) => `toValue(${name})`
780
+ });
781
+ }
782
+ //#endregion
783
+ //#region src/components/QueryKey.tsx
784
+ const declarationPrinter$4 = functionPrinter({ mode: "declaration" });
785
+ function buildQueryKeyParamsNode(node, options) {
786
+ const groupedParam = buildGroupedRequestParam(node, {
787
+ resolver: options.resolver,
788
+ keys: [
789
+ "path",
790
+ "query",
791
+ "body"
792
+ ],
793
+ memberTypeWrapper: maybeRefOrGetter
794
+ });
795
+ return createFunctionParameters({ params: groupedParam ? [groupedParam] : [] });
796
+ }
797
+ function QueryKey({ name, node, tsResolver, typeName, transformer }) {
798
+ const paramsNode = buildQueryKeyParamsNode(node, { resolver: tsResolver });
799
+ const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
800
+ const keys = (transformer ?? queryKeyTransformer)({
801
+ node,
802
+ casing: "camelcase"
803
+ });
804
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
805
+ name,
806
+ isExportable: true,
807
+ isIndexable: true,
808
+ children: /* @__PURE__ */ jsx(Function.Arrow, {
809
+ name,
810
+ export: true,
811
+ params: paramsSignature,
812
+ singleLine: true,
813
+ children: `[${keys.join(", ")}] as const`
814
+ })
815
+ }), /* @__PURE__ */ jsx(File.Source, {
816
+ name: typeName,
817
+ isExportable: true,
818
+ isIndexable: true,
819
+ isTypeOnly: true,
820
+ children: /* @__PURE__ */ jsx(Type, {
821
+ name: typeName,
822
+ export: true,
823
+ children: `ReturnType<typeof ${name}>`
824
+ })
825
+ })] });
826
+ }
827
+ //#endregion
828
+ //#region src/components/QueryOptions.tsx
829
+ const declarationPrinter$3 = functionPrinter({ mode: "declaration" });
830
+ const callPrinter$3 = functionPrinter({ mode: "call" });
831
+ function getQueryOptionsParams(node, options) {
832
+ return buildQueryOptionsParams(node, {
833
+ resolver: options.resolver,
834
+ memberTypeWrapper: maybeRefOrGetter
835
+ });
836
+ }
837
+ function QueryOptions({ name, clientName, node, tsResolver, queryKeyName }) {
838
+ const { TData, TError } = buildResponseTypes(node, tsResolver);
839
+ const queryKeyParamsNode = buildQueryKeyParamsNode(node, { resolver: tsResolver });
840
+ const queryKeyParamsCall = callPrinter$3.print(queryKeyParamsNode) ?? "";
841
+ const paramsNode = getQueryOptionsParams(node, { resolver: tsResolver });
842
+ const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
843
+ const queryFnBody = `const { data } = await ${buildVueClientCall(node, {
844
+ clientName,
845
+ signal: true
846
+ })}
847
+ return data`;
848
+ return /* @__PURE__ */ jsx(File.Source, {
849
+ name,
850
+ isExportable: true,
851
+ isIndexable: true,
852
+ children: /* @__PURE__ */ jsx(Function, {
853
+ name,
854
+ export: true,
855
+ params: paramsSignature,
856
+ children: `
857
+ const queryKey = ${queryKeyName}(${queryKeyParamsCall})
858
+ return queryOptions<${TData}, ${TError}, ${TData}>({
859
+ queryKey,
860
+ queryFn: async ({ signal }) => {
861
+ ${queryFnBody}
862
+ },
863
+ })
864
+ `
865
+ })
866
+ });
867
+ }
868
+ //#endregion
869
+ //#region src/components/InfiniteQuery.tsx
870
+ const declarationPrinter$2 = functionPrinter({ mode: "declaration" });
871
+ const callPrinter$2 = functionPrinter({ mode: "call" });
872
+ function buildInfiniteQueryParamsNode(node, options) {
873
+ const { resolver } = options;
874
+ const { TData, TError } = buildResponseTypes(node, resolver);
875
+ const optionsParam = createFunctionParameter({
876
+ name: "options",
877
+ type: `{
878
+ query?: Partial<UseInfiniteQueryOptions<${[
879
+ TData,
880
+ TError,
881
+ "TQueryData",
882
+ "TQueryKey",
883
+ "TQueryData"
884
+ ].join(", ")}>> & { client?: QueryClient },
885
+ client?: ${buildClientOptionType()}
886
+ }`,
887
+ default: "{}"
888
+ });
889
+ return createFunctionParameters({ params: [buildGroupedRequestParam(node, {
890
+ resolver,
891
+ memberTypeWrapper: maybeRefOrGetter
892
+ }), optionsParam].filter((param) => param !== null) });
893
+ }
894
+ function InfiniteQuery({ name, queryKeyTypeName, queryOptionsName, queryKeyName, node, tsResolver }) {
895
+ const { TData, TError } = buildResponseTypes(node, tsResolver);
896
+ const returnType = `UseInfiniteQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
897
+ const generics = [
898
+ `TData = InfiniteData<${TData}>`,
899
+ `TQueryData = ${TData}`,
900
+ `TQueryKey extends QueryKey = ${queryKeyTypeName}`
901
+ ];
902
+ const queryKeyParamsNode = buildQueryKeyParamsNode(node, { resolver: tsResolver });
903
+ const queryKeyParamsCall = callPrinter$2.print(queryKeyParamsNode) ?? "";
904
+ const queryOptionsParamsNode = getQueryOptionsParams(node, { resolver: tsResolver });
905
+ const queryOptionsParamsCall = callPrinter$2.print(queryOptionsParamsNode) ?? "";
906
+ const paramsNode = buildInfiniteQueryParamsNode(node, { resolver: tsResolver });
907
+ const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
908
+ return /* @__PURE__ */ jsx(File.Source, {
909
+ name,
910
+ isExportable: true,
911
+ isIndexable: true,
912
+ children: /* @__PURE__ */ jsx(Function, {
913
+ name,
914
+ export: true,
915
+ generics: generics.join(", "),
916
+ params: paramsSignature,
917
+ JSDoc: { comments: buildOperationComments(node) },
918
+ children: `
919
+ const { query: queryConfig = {}, client: config = {} } = options ?? {}
920
+ const { client: queryClient, ...resolvedOptions } = queryConfig
921
+ const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
922
+
923
+ const queryResult = useInfiniteQuery({
924
+ ...${queryOptionsName}(${queryOptionsParamsCall}),
925
+ ...resolvedOptions,
926
+ queryKey
927
+ } as unknown as UseInfiniteQueryOptions<${TData}, ${TError}, ${TData}, TQueryKey, ${TData}>, toValue(queryClient)) as ${returnType}
928
+
929
+ queryResult.queryKey = queryKey as TQueryKey
930
+
931
+ return queryResult
932
+ `
933
+ })
934
+ });
935
+ }
936
+ //#endregion
937
+ //#region src/components/InfiniteQueryOptions.tsx
938
+ /**
939
+ * The vue-query flavor of the shared `infiniteQueryOptions` component: request groups accept
940
+ * `MaybeRefOrGetter` values, are unwrapped with `toValue(...)` in the client call, and the emitted
941
+ * `TQueryKey` generic is the imported `QueryKey` type instead of `typeof queryKey`.
942
+ */
943
+ function InfiniteQueryOptions(props) {
944
+ return /* @__PURE__ */ jsx(InfiniteQueryOptions$1, {
945
+ ...props,
946
+ queryKeyType: "QueryKey",
947
+ memberTypeWrapper: maybeRefOrGetter,
948
+ unwrapName: (name) => `toValue(${name})`
949
+ });
950
+ }
951
+ //#endregion
952
+ //#region src/components/Mutation.tsx
953
+ const declarationPrinter$1 = functionPrinter({ mode: "declaration" });
954
+ const callPrinter$1 = functionPrinter({ mode: "call" });
955
+ function resolveMutationRequestType(node, resolver) {
956
+ return buildGroupedRequestParam(node, { resolver }) ? resolver.response.options(node) : "undefined";
957
+ }
958
+ function buildMutationParamsNode(node, options) {
959
+ const { resolver } = options;
960
+ const { TData, TError } = buildResponseTypes(node, resolver);
961
+ return createFunctionParameters({ params: [createFunctionParameter({
962
+ name: "options",
963
+ type: `{
964
+ mutation?: MutationObserverOptions<${[
965
+ TData,
966
+ TError,
967
+ resolveMutationRequestType(node, resolver),
968
+ "TContext"
969
+ ].join(", ")}> & { client?: QueryClient },
970
+ client?: ${buildRequestConfigType(node)},
971
+ }`,
972
+ default: "{}"
973
+ })] });
974
+ }
975
+ function Mutation({ name, clientName, node, tsResolver, mutationKeyName }) {
976
+ const { TData, TError } = buildResponseTypes(node, tsResolver);
977
+ const groupedParam = buildGroupedRequestParam(node, { resolver: tsResolver });
978
+ const hasMutationParams = groupedParam !== null;
979
+ const groupedParamsNode = createFunctionParameters({ params: groupedParam ? [groupedParam] : [] });
980
+ const argBindingStr = hasMutationParams ? callPrinter$1.print(groupedParamsNode) ?? "" : "";
981
+ const mutationFnBody = `const { data } = await ${buildVueClientCall(node, {
982
+ clientName,
983
+ signal: false
984
+ })}
985
+ return data`;
986
+ const generics = [
987
+ TData,
988
+ TError,
989
+ resolveMutationRequestType(node, tsResolver),
990
+ "TContext"
991
+ ].join(", ");
992
+ const paramsNode = buildMutationParamsNode(node, { resolver: tsResolver });
993
+ const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
994
+ return /* @__PURE__ */ jsx(File.Source, {
995
+ name,
996
+ isExportable: true,
997
+ isIndexable: true,
998
+ children: /* @__PURE__ */ jsx(Function, {
999
+ name,
1000
+ export: true,
1001
+ params: paramsSignature,
1002
+ JSDoc: { comments: buildOperationComments(node) },
1003
+ generics: ["TContext"],
1004
+ children: `
1005
+ const { mutation = {}, client: config = {} } = options ?? {}
1006
+ const { client: queryClient, ...mutationOptions } = mutation;
1007
+ const mutationKey = mutationOptions?.mutationKey ?? ${mutationKeyName}()
1008
+
1009
+ return useMutation<${generics}>({
1010
+ mutationFn: async(${argBindingStr}) => {
1011
+ ${mutationFnBody}
1012
+ },
1013
+ mutationKey,
1014
+ ...mutationOptions
1015
+ }, queryClient)
1016
+ `
1017
+ })
1018
+ });
1019
+ }
1020
+ //#endregion
1021
+ //#region src/components/Query.tsx
1022
+ const declarationPrinter = functionPrinter({ mode: "declaration" });
1023
+ const callPrinter = functionPrinter({ mode: "call" });
1024
+ function buildQueryParamsNode(node, options) {
1025
+ const { resolver } = options;
1026
+ const { TData, TError } = buildResponseTypes(node, resolver);
1027
+ const optionsParam = createFunctionParameter({
1028
+ name: "options",
1029
+ type: `{
1030
+ query?: Partial<UseQueryOptions<${[
1031
+ TData,
1032
+ TError,
1033
+ "TData",
1034
+ "TQueryData",
1035
+ "TQueryKey"
1036
+ ].join(", ")}>> & { client?: QueryClient },
1037
+ client?: ${buildClientOptionType()}
1038
+ }`,
1039
+ default: "{}"
1040
+ });
1041
+ return createFunctionParameters({ params: [buildGroupedRequestParam(node, {
1042
+ resolver,
1043
+ memberTypeWrapper: maybeRefOrGetter
1044
+ }), optionsParam].filter((param) => param !== null) });
1045
+ }
1046
+ function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, node, tsResolver }) {
1047
+ const { TData, TError } = buildResponseTypes(node, tsResolver);
1048
+ const returnType = `UseQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
1049
+ const generics = [
1050
+ `TData = ${TData}`,
1051
+ `TQueryData = ${TData}`,
1052
+ `TQueryKey extends QueryKey = ${queryKeyTypeName}`
1053
+ ];
1054
+ const queryKeyParamsNode = buildQueryKeyParamsNode(node, { resolver: tsResolver });
1055
+ const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
1056
+ const queryOptionsParamsNode = getQueryOptionsParams(node, { resolver: tsResolver });
1057
+ const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
1058
+ const paramsNode = buildQueryParamsNode(node, { resolver: tsResolver });
1059
+ const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
1060
+ return /* @__PURE__ */ jsx(File.Source, {
1061
+ name,
1062
+ isExportable: true,
1063
+ isIndexable: true,
1064
+ children: /* @__PURE__ */ jsx(Function, {
1065
+ name,
1066
+ export: true,
1067
+ generics: generics.join(", "),
1068
+ params: paramsSignature,
1069
+ JSDoc: { comments: buildOperationComments(node) },
1070
+ children: `
1071
+ const { query: queryConfig = {}, client: config = {} } = options ?? {}
1072
+ const { client: queryClient, ...resolvedOptions } = queryConfig
1073
+ const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
1074
+
1075
+ const queryResult = useQuery({
1076
+ ...${queryOptionsName}(${queryOptionsParamsCall}),
1077
+ ...resolvedOptions,
1078
+ queryKey
1079
+ } as unknown as UseQueryOptions<${TData}, ${TError}, TData, ${TData}, TQueryKey>, toValue(queryClient)) as ${returnType}
1080
+
1081
+ queryResult.queryKey = queryKey as TQueryKey
1082
+
1083
+ return queryResult
1084
+ `
1085
+ })
1086
+ });
1087
+ }
1088
+ //#endregion
1089
+ //#region src/generators/infiniteQueryGenerator.tsx
1090
+ /**
1091
+ * Built-in generator for `useInfiniteQuery` composables. Enabled when
1092
+ * `pluginVueQuery({ infinite: { ... }, hooks: true })`. Emits one
1093
+ * `useFooInfiniteQuery` composable per query operation, wiring the
1094
+ * configured cursor path into TanStack Query's cursor-based pagination.
1095
+ */
1096
+ const infiniteQueryGenerator = defineGenerator({
1097
+ name: "vue-query-infinite",
1098
+ renderer: jsxRenderer,
1099
+ operation(node, ctx) {
1100
+ if (!ast.isHttpOperationNode(node)) return null;
1101
+ const { config, driver, resolver, root } = ctx;
1102
+ const { output, query, mutation, infinite, client, group, hooks } = ctx.options;
1103
+ const pluginTs = driver.getPlugin(pluginTsName);
1104
+ if (!pluginTs) return null;
1105
+ const tsResolver = driver.getResolver(pluginTsName);
1106
+ const isQuery = query === false || !!query && query.methods.some((method) => node.method.toLowerCase() === method.toLowerCase());
1107
+ const queryMethods = new Set(query ? query.methods : []);
1108
+ const isMutation = mutation !== false && !isQuery && (mutation ? mutation.methods : []).some((method) => !queryMethods.has(method) && node.method.toLowerCase() === method.toLowerCase());
1109
+ const infiniteOptions = infinite && typeof infinite === "object" ? infinite : null;
1110
+ if (!isQuery || isMutation || !infiniteOptions || !hooks) return null;
1111
+ const normalizeKey = (key) => key.replace(/\?$/, "");
1112
+ const queryParamKeys = getOperationParameters(node).query.map((p) => p.name);
1113
+ if (!(infiniteOptions.queryParam ? queryParamKeys.some((k) => normalizeKey(k) === infiniteOptions.queryParam) : false)) return null;
1114
+ const importPath = query ? query.importPath : "@tanstack/vue-query";
1115
+ const contractOp = resolveClientOperation({
1116
+ clientPlugin: { pluginName: client.pluginName },
1117
+ driver,
1118
+ node,
1119
+ root,
1120
+ output
1121
+ });
1122
+ if (!contractOp) return null;
1123
+ const queryName = resolver.infiniteQuery.name(node);
1124
+ const queryOptionsName = resolver.infiniteQuery.optionsName(node);
1125
+ const queryKeyName = resolver.infiniteQuery.keyName(node);
1126
+ const queryKeyTypeName = resolver.infiniteQuery.keyTypeName(node);
1127
+ const meta = {
1128
+ file: resolver.file({
1129
+ ...operationFileEntry(node, queryName),
1130
+ root,
1131
+ output,
1132
+ group: group ?? void 0
1133
+ }),
1134
+ fileTs: tsResolver.file({
1135
+ ...operationFileEntry(node, node.operationId),
1136
+ root,
1137
+ output: pluginTs.options?.output ?? output,
1138
+ group: pluginTs.options?.group ?? void 0
1139
+ })
1140
+ };
1141
+ const rawQueryParams = getOperationParameters(node).query;
1142
+ const queryParamsTypeName = rawQueryParams.length > 0 && tsResolver.param.query(node, rawQueryParams[0]) !== tsResolver.param.name(node, rawQueryParams[0]) ? tsResolver.param.query(node, rawQueryParams[0]) : null;
1143
+ const importedTypeNames = [
1144
+ tsResolver.response.options(node),
1145
+ queryParamsTypeName,
1146
+ ...resolveOperationTypeNames(node, tsResolver, {
1147
+ exclude: [queryKeyTypeName],
1148
+ order: "body-response-first",
1149
+ includeParams: false
1150
+ })
1151
+ ].filter((name) => Boolean(name));
1152
+ const calledClientName = contractOp.name;
1153
+ return /* @__PURE__ */ jsxs(File, {
1154
+ baseName: meta.file.baseName,
1155
+ path: meta.file.path,
1156
+ meta: meta.file.meta,
1157
+ banner: resolver.default.banner(ctx.meta, {
1158
+ output,
1159
+ config,
1160
+ file: {
1161
+ path: meta.file.path,
1162
+ baseName: meta.file.baseName
1163
+ }
1164
+ }),
1165
+ footer: resolver.default.footer(ctx.meta, {
1166
+ output,
1167
+ config,
1168
+ file: {
1169
+ path: meta.file.path,
1170
+ baseName: meta.file.baseName
1171
+ }
1172
+ }),
1173
+ children: [
1174
+ /* @__PURE__ */ jsx(File.Import, {
1175
+ name: [contractOp.name],
1176
+ root: meta.file.path,
1177
+ path: contractOp.path
1178
+ }),
1179
+ /* @__PURE__ */ jsx(File.Import, {
1180
+ name: ["RequestConfig", "ResponseErrorConfig"],
1181
+ root: meta.file.path,
1182
+ path: contractOp.clientPath,
1183
+ isTypeOnly: true
1184
+ }),
1185
+ /* @__PURE__ */ jsx(File.Import, {
1186
+ name: ["toValue"],
1187
+ path: "vue"
1188
+ }),
1189
+ /* @__PURE__ */ jsx(File.Import, {
1190
+ name: ["MaybeRefOrGetter"],
1191
+ path: "vue",
1192
+ isTypeOnly: true
1193
+ }),
1194
+ meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
1195
+ name: Array.from(new Set(importedTypeNames)),
1196
+ root: meta.file.path,
1197
+ path: meta.fileTs.path,
1198
+ isTypeOnly: true
1199
+ }),
1200
+ /* @__PURE__ */ jsx(QueryKey, {
1201
+ name: queryKeyName,
1202
+ typeName: queryKeyTypeName,
1203
+ node,
1204
+ tsResolver,
1205
+ transformer: ctx.options.queryKey
1206
+ }),
1207
+ /* @__PURE__ */ jsx(File.Import, {
1208
+ name: ["InfiniteData"],
1209
+ isTypeOnly: true,
1210
+ path: importPath
1211
+ }),
1212
+ /* @__PURE__ */ jsx(File.Import, {
1213
+ name: ["infiniteQueryOptions"],
1214
+ path: importPath
1215
+ }),
1216
+ /* @__PURE__ */ jsx(InfiniteQueryOptions, {
1217
+ name: queryOptionsName,
1218
+ clientName: calledClientName,
1219
+ queryKeyName,
1220
+ node,
1221
+ tsResolver,
1222
+ cursorParam: infiniteOptions.cursorParam,
1223
+ nextParam: infiniteOptions.nextParam,
1224
+ previousParam: infiniteOptions.previousParam,
1225
+ initialPageParam: infiniteOptions.initialPageParam,
1226
+ queryParam: infiniteOptions.queryParam
1227
+ }),
1228
+ /* @__PURE__ */ jsx(File.Import, {
1229
+ name: ["useInfiniteQuery"],
1230
+ path: importPath
1231
+ }),
1232
+ /* @__PURE__ */ jsx(File.Import, {
1233
+ name: [
1234
+ "QueryKey",
1235
+ "QueryClient",
1236
+ "UseInfiniteQueryOptions",
1237
+ "UseInfiniteQueryReturnType"
1238
+ ],
1239
+ path: importPath,
1240
+ isTypeOnly: true
1241
+ }),
1242
+ /* @__PURE__ */ jsx(InfiniteQuery, {
1243
+ name: queryName,
1244
+ queryOptionsName,
1245
+ queryKeyName,
1246
+ queryKeyTypeName,
1247
+ node,
1248
+ tsResolver,
1249
+ initialPageParam: infiniteOptions.initialPageParam,
1250
+ queryParam: infiniteOptions.queryParam
1251
+ })
1252
+ ]
1253
+ });
1254
+ }
1255
+ });
1256
+ //#endregion
1257
+ //#region src/generators/mutationGenerator.tsx
1258
+ /**
1259
+ * Built-in generator for `useMutation` composables. Emits one
1260
+ * `useFooMutation` composable per POST/PUT/DELETE operation (configurable
1261
+ * via `mutation.methods`) plus the matching `fooMutationKey` helper.
1262
+ */
1263
+ const mutationGenerator = defineGenerator({
1264
+ name: "vue-query-mutation",
1265
+ renderer: jsxRenderer,
1266
+ operation(node, ctx) {
1267
+ if (!ast.isHttpOperationNode(node)) return null;
1268
+ const { config, driver, resolver, root } = ctx;
1269
+ const { output, query, mutation, client, group, hooks } = ctx.options;
1270
+ const pluginTs = driver.getPlugin(pluginTsName);
1271
+ if (!pluginTs) return null;
1272
+ const tsResolver = driver.getResolver(pluginTsName);
1273
+ const isQuery = query === false || !!query && query.methods.some((method) => node.method.toLowerCase() === method.toLowerCase());
1274
+ const queryMethods = new Set(query ? query.methods : []);
1275
+ if (!(mutation !== false && !isQuery && (mutation ? mutation.methods : []).some((method) => !queryMethods.has(method) && node.method.toLowerCase() === method.toLowerCase()))) return null;
1276
+ const importPath = mutation ? mutation.importPath : "@tanstack/vue-query";
1277
+ const contractOp = resolveClientOperation({
1278
+ clientPlugin: { pluginName: client.pluginName },
1279
+ driver,
1280
+ node,
1281
+ root,
1282
+ output
1283
+ });
1284
+ if (!contractOp) return null;
1285
+ const mutationHookName = resolver.mutation.name(node);
1286
+ const mutationTypeName = resolver.mutation.typeName(node);
1287
+ const mutationKeyName = resolver.mutation.keyName(node);
1288
+ const meta = {
1289
+ file: resolver.file({
1290
+ ...operationFileEntry(node, mutationHookName),
1291
+ root,
1292
+ output,
1293
+ group: group ?? void 0
1294
+ }),
1295
+ fileTs: tsResolver.file({
1296
+ ...operationFileEntry(node, node.operationId),
1297
+ root,
1298
+ output: pluginTs.options?.output ?? output,
1299
+ group: pluginTs.options?.group ?? void 0
1300
+ })
1301
+ };
1302
+ const importedTypeNames = [tsResolver.response.options(node), ...resolveOperationTypeNames(node, tsResolver, {
1303
+ order: "body-response-first",
1304
+ includeParams: false
1305
+ })].filter((name) => Boolean(name));
1306
+ const calledClientName = contractOp.name;
1307
+ const groups = getRequestGroups(node);
1308
+ const hasRequestGroups = groups.path || groups.query || groups.body || groups.headers;
1309
+ return /* @__PURE__ */ jsxs(File, {
1310
+ baseName: meta.file.baseName,
1311
+ path: meta.file.path,
1312
+ meta: meta.file.meta,
1313
+ banner: resolver.default.banner(ctx.meta, {
1314
+ output,
1315
+ config,
1316
+ file: {
1317
+ path: meta.file.path,
1318
+ baseName: meta.file.baseName
1319
+ }
1320
+ }),
1321
+ footer: resolver.default.footer(ctx.meta, {
1322
+ output,
1323
+ config,
1324
+ file: {
1325
+ path: meta.file.path,
1326
+ baseName: meta.file.baseName
1327
+ }
1328
+ }),
1329
+ children: [
1330
+ /* @__PURE__ */ jsx(File.Import, {
1331
+ name: [contractOp.name],
1332
+ root: meta.file.path,
1333
+ path: contractOp.path
1334
+ }),
1335
+ /* @__PURE__ */ jsx(File.Import, {
1336
+ name: ["RequestConfig", "ResponseErrorConfig"],
1337
+ root: meta.file.path,
1338
+ path: contractOp.clientPath,
1339
+ isTypeOnly: true
1340
+ }),
1341
+ hasRequestGroups && /* @__PURE__ */ jsx(File.Import, {
1342
+ name: ["toValue"],
1343
+ path: "vue"
1344
+ }),
1345
+ /* @__PURE__ */ jsx(File.Import, {
1346
+ name: ["MaybeRefOrGetter"],
1347
+ path: "vue",
1348
+ isTypeOnly: true
1349
+ }),
1350
+ meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
1351
+ name: Array.from(new Set(importedTypeNames)),
1352
+ root: meta.file.path,
1353
+ path: meta.fileTs.path,
1354
+ isTypeOnly: true
1355
+ }),
1356
+ /* @__PURE__ */ jsx(MutationKey, {
1357
+ name: mutationKeyName,
1358
+ node,
1359
+ transformer: ctx.options.mutationKey
1360
+ }),
1361
+ mutation && hooks && /* @__PURE__ */ jsxs(Fragment, { children: [
1362
+ /* @__PURE__ */ jsx(File.Import, {
1363
+ name: ["useMutation"],
1364
+ path: importPath
1365
+ }),
1366
+ /* @__PURE__ */ jsx(File.Import, {
1367
+ name: ["MutationObserverOptions", "QueryClient"],
1368
+ path: importPath,
1369
+ isTypeOnly: true
1370
+ }),
1371
+ /* @__PURE__ */ jsx(Mutation, {
1372
+ name: mutationHookName,
1373
+ clientName: calledClientName,
1374
+ typeName: mutationTypeName,
1375
+ node,
1376
+ tsResolver,
1377
+ mutationKeyName
1378
+ })
1379
+ ] })
1380
+ ]
1381
+ });
1382
+ }
1383
+ });
1384
+ //#endregion
1385
+ //#region src/generators/queryGenerator.tsx
1386
+ /**
1387
+ * Built-in generator for `useQuery` composables. Emits one `useFooQuery`
1388
+ * composable per GET operation (configurable via `query.methods`) plus the
1389
+ * matching `fooQueryKey` / `fooQueryOptions` helpers.
1390
+ */
1391
+ const queryGenerator = defineGenerator({
1392
+ name: "vue-query",
1393
+ renderer: jsxRenderer,
1394
+ operation(node, ctx) {
1395
+ if (!ast.isHttpOperationNode(node)) return null;
1396
+ const { config, driver, resolver, root } = ctx;
1397
+ const { output, query, mutation, client, group, hooks } = ctx.options;
1398
+ const pluginTs = driver.getPlugin(pluginTsName);
1399
+ if (!pluginTs) return null;
1400
+ const tsResolver = driver.getResolver(pluginTsName);
1401
+ const isQuery = query === false || !!query && query.methods.some((method) => node.method.toLowerCase() === method.toLowerCase());
1402
+ const queryMethods = new Set(query ? query.methods : []);
1403
+ const isMutation = mutation !== false && !isQuery && (mutation ? mutation.methods : []).some((method) => !queryMethods.has(method) && node.method.toLowerCase() === method.toLowerCase());
1404
+ if (!isQuery || isMutation) return null;
1405
+ const importPath = query ? query.importPath : "@tanstack/vue-query";
1406
+ const contractOp = resolveClientOperation({
1407
+ clientPlugin: { pluginName: client.pluginName },
1408
+ driver,
1409
+ node,
1410
+ root,
1411
+ output
1412
+ });
1413
+ if (!contractOp) return null;
1414
+ const queryName = resolver.query.name(node);
1415
+ const queryOptionsName = resolver.query.optionsName(node);
1416
+ const queryKeyName = resolver.query.keyName(node);
1417
+ const queryKeyTypeName = resolver.query.keyTypeName(node);
1418
+ const meta = {
1419
+ file: resolver.file({
1420
+ ...operationFileEntry(node, queryName),
1421
+ root,
1422
+ output,
1423
+ group: group ?? void 0
1424
+ }),
1425
+ fileTs: tsResolver.file({
1426
+ ...operationFileEntry(node, node.operationId),
1427
+ root,
1428
+ output: pluginTs.options?.output ?? output,
1429
+ group: pluginTs.options?.group ?? void 0
1430
+ })
1431
+ };
1432
+ const importedTypeNames = [tsResolver.response.options(node), ...resolveOperationTypeNames(node, tsResolver, {
1433
+ exclude: [queryKeyTypeName],
1434
+ order: "body-response-first",
1435
+ includeParams: false
1436
+ })].filter((name) => Boolean(name));
1437
+ const calledClientName = contractOp.name;
1438
+ return /* @__PURE__ */ jsxs(File, {
1439
+ baseName: meta.file.baseName,
1440
+ path: meta.file.path,
1441
+ meta: meta.file.meta,
1442
+ banner: resolver.default.banner(ctx.meta, {
1443
+ output,
1444
+ config,
1445
+ file: {
1446
+ path: meta.file.path,
1447
+ baseName: meta.file.baseName
1448
+ }
1449
+ }),
1450
+ footer: resolver.default.footer(ctx.meta, {
1451
+ output,
1452
+ config,
1453
+ file: {
1454
+ path: meta.file.path,
1455
+ baseName: meta.file.baseName
1456
+ }
1457
+ }),
1458
+ children: [
1459
+ /* @__PURE__ */ jsx(File.Import, {
1460
+ name: [contractOp.name],
1461
+ root: meta.file.path,
1462
+ path: contractOp.path
1463
+ }),
1464
+ /* @__PURE__ */ jsx(File.Import, {
1465
+ name: ["RequestConfig", "ResponseErrorConfig"],
1466
+ root: meta.file.path,
1467
+ path: contractOp.clientPath,
1468
+ isTypeOnly: true
1469
+ }),
1470
+ /* @__PURE__ */ jsx(File.Import, {
1471
+ name: ["toValue"],
1472
+ path: "vue"
1473
+ }),
1474
+ /* @__PURE__ */ jsx(File.Import, {
1475
+ name: ["MaybeRefOrGetter"],
1476
+ path: "vue",
1477
+ isTypeOnly: true
1478
+ }),
1479
+ meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
1480
+ name: Array.from(new Set(importedTypeNames)),
1481
+ root: meta.file.path,
1482
+ path: meta.fileTs.path,
1483
+ isTypeOnly: true
1484
+ }),
1485
+ /* @__PURE__ */ jsx(QueryKey, {
1486
+ name: queryKeyName,
1487
+ typeName: queryKeyTypeName,
1488
+ node,
1489
+ tsResolver,
1490
+ transformer: ctx.options.queryKey
1491
+ }),
1492
+ /* @__PURE__ */ jsx(File.Import, {
1493
+ name: ["queryOptions"],
1494
+ path: importPath
1495
+ }),
1496
+ /* @__PURE__ */ jsx(QueryOptions, {
1497
+ name: queryOptionsName,
1498
+ clientName: calledClientName,
1499
+ queryKeyName,
1500
+ node,
1501
+ tsResolver
1502
+ }),
1503
+ query && hooks && /* @__PURE__ */ jsxs(Fragment, { children: [
1504
+ /* @__PURE__ */ jsx(File.Import, {
1505
+ name: ["useQuery"],
1506
+ path: importPath
1507
+ }),
1508
+ /* @__PURE__ */ jsx(File.Import, {
1509
+ name: [
1510
+ "QueryKey",
1511
+ "QueryClient",
1512
+ "UseQueryOptions",
1513
+ "UseQueryReturnType"
1514
+ ],
1515
+ path: importPath,
1516
+ isTypeOnly: true
1517
+ }),
1518
+ /* @__PURE__ */ jsx(Query, {
1519
+ name: queryName,
1520
+ queryOptionsName,
1521
+ queryKeyName,
1522
+ queryKeyTypeName,
1523
+ node,
1524
+ tsResolver
1525
+ })
1526
+ ] })
1527
+ ]
1528
+ });
1529
+ }
1530
+ });
1531
+ //#endregion
1532
+ //#region src/resolvers/resolverVueQuery.ts
1533
+ /**
1534
+ * Default resolver used by `@kubb/plugin-vue-query`. Decides the names and
1535
+ * file paths for every generated TanStack Query composable (`useFoo`,
1536
+ * `useFooInfinite`) and its companion helpers.
1537
+ *
1538
+ * The `default` helpers are supplied by `createResolver`. Functions and files use camelCase;
1539
+ * composables get the `use` prefix. Operation-specific naming is grouped under the `query`,
1540
+ * `infiniteQuery`, and `mutation` namespaces.
1541
+ *
1542
+ * @example Resolve composable and helper names
1543
+ * ```ts
1544
+ * import { resolverVueQuery } from '@kubb/plugin-vue-query'
1545
+ *
1546
+ * resolverVueQuery.query.name(operationNode) // 'useGetPetById'
1547
+ * resolverVueQuery.query.keyName(operationNode) // 'getPetByIdQueryKey'
1548
+ * resolverVueQuery.query.optionsName(operationNode) // 'getPetByIdQueryOptions'
1549
+ * ```
1550
+ */
1551
+ const resolverVueQuery = createResolver({
1552
+ pluginName: "plugin-vue-query",
1553
+ query: createQueryResolver(),
1554
+ infiniteQuery: createQueryResolver("Infinite"),
1555
+ mutation: {
1556
+ ...createMutationResolver(),
1557
+ typeName(node) {
1558
+ return capitalize(this.name(node.operationId));
1559
+ }
1560
+ }
1561
+ });
1562
+ //#endregion
13
1563
  //#region src/plugin.ts
1564
+ /**
1565
+ * Canonical plugin name for `@kubb/plugin-vue-query`. Used for driver lookups
1566
+ * and cross-plugin dependency references.
1567
+ */
14
1568
  const pluginVueQueryName = "plugin-vue-query";
15
- const pluginVueQuery = createPlugin((options) => {
1569
+ /**
1570
+ * Generates one TanStack Query composable per OpenAPI operation for Vue's
1571
+ * Composition API. Queries become `useFoo` (and optionally
1572
+ * `useFooInfinite`). Mutations become `useFoo` as well. Each composable
1573
+ * is fully typed end to end.
1574
+ *
1575
+ * @example
1576
+ * ```ts
1577
+ * import { defineConfig } from 'kubb/config'
1578
+ * import { pluginTs } from '@kubb/plugin-ts'
1579
+ * import { pluginVueQuery } from '@kubb/plugin-vue-query'
1580
+ *
1581
+ * export default defineConfig({
1582
+ * input: './petStore.yaml',
1583
+ * output: { path: './src/gen' },
1584
+ * plugins: [
1585
+ * pluginTs(),
1586
+ * pluginVueQuery({
1587
+ * output: { path: './hooks' },
1588
+ * }),
1589
+ * ],
1590
+ * })
1591
+ * ```
1592
+ */
1593
+ const pluginVueQuery = definePlugin((options) => {
16
1594
  const { output = {
17
1595
  path: "hooks",
18
- barrelType: "named"
19
- }, group, exclude = [], include, override = [], parser = "client", infinite, transformers = {}, paramsType = "inline", pathParamsType = paramsType === "object" ? "object" : options.pathParamsType || "inline", mutation = {}, query = {}, paramsCasing, mutationKey = MutationKey.getTransformer, queryKey = QueryKey.getTransformer, generators = [
1596
+ barrel: { type: "named" }
1597
+ }, group, exclude = [], include, override = [], infinite = false, mutation = {}, query = {}, mutationKey = mutationKeyTransformer, queryKey = queryKeyTransformer, hooks = false, client, resolver: userResolver, macros: userMacros } = options;
1598
+ const selectedGenerators = [
20
1599
  queryGenerator,
21
1600
  infiniteQueryGenerator,
22
1601
  mutationGenerator
23
- ].filter(Boolean), contentType, client } = options;
24
- const clientName = client?.client ?? "axios";
25
- const clientImportPath = client?.importPath ?? (!client?.bundle ? `@kubb/plugin-client/clients/${clientName}` : void 0);
1602
+ ];
1603
+ const groupConfig = createGroupConfig(group);
26
1604
  return {
27
1605
  name: pluginVueQueryName,
28
- options: {
29
- output,
30
- client: {
31
- bundle: client?.bundle,
32
- baseURL: client?.baseURL,
33
- client: clientName,
34
- clientType: client?.clientType ?? "function",
35
- dataReturnType: client?.dataReturnType ?? "data",
36
- pathParamsType,
37
- importPath: clientImportPath,
38
- paramsCasing
39
- },
40
- infinite: infinite ? {
41
- queryParam: "id",
42
- initialPageParam: 0,
43
- cursorParam: void 0,
44
- nextParam: void 0,
45
- previousParam: void 0,
46
- ...infinite
47
- } : false,
48
- queryKey,
49
- query: query === false ? false : {
50
- methods: ["get"],
51
- importPath: "@tanstack/vue-query",
52
- ...query
53
- },
54
- mutationKey,
55
- mutation: mutation === false ? false : {
56
- methods: [
57
- "post",
58
- "put",
59
- "patch",
60
- "delete"
61
- ],
62
- importPath: "@tanstack/vue-query",
63
- ...mutation
64
- },
65
- paramsType,
66
- pathParamsType,
67
- parser,
68
- paramsCasing,
69
- group
70
- },
71
- pre: [
72
- pluginOasName,
73
- pluginTsName,
74
- parser === "zod" ? pluginZodName : void 0
75
- ].filter(Boolean),
76
- resolvePath(baseName, pathMode, options) {
77
- const root = path.resolve(this.config.root, this.config.output.path);
78
- if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single")
79
- /**
80
- * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
81
- * Other plugins then need to call addOrAppend instead of just add from the fileManager class
82
- */
83
- return path.resolve(root, output.path);
84
- if (group && (options?.group?.path || options?.group?.tag)) {
85
- const groupName = group?.name ? group.name : (ctx) => {
86
- if (group?.type === "path") return `${ctx.group.split("/")[1]}`;
87
- return `${camelCase(ctx.group)}Controller`;
88
- };
89
- return path.resolve(root, output.path, groupName({ group: group.type === "path" ? options.group.path : options.group.tag }), baseName);
90
- }
91
- return path.resolve(root, output.path, baseName);
92
- },
93
- resolveName(name, type) {
94
- let resolvedName = camelCase(name);
95
- if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
96
- if (type === "type") resolvedName = pascalCase(name);
97
- if (type) return transformers?.name?.(resolvedName, type) || resolvedName;
98
- return resolvedName;
99
- },
100
- async install() {
101
- const root = path.resolve(this.config.root, this.config.output.path);
102
- const mode = getMode(path.resolve(root, output.path));
103
- const oas = await this.getOas();
104
- const baseURL = await this.getBaseURL();
105
- if (baseURL) this.plugin.options.client.baseURL = baseURL;
106
- const hasClientPlugin = !!this.driver.getPluginByName(pluginClientName);
107
- if (this.plugin.options.client.bundle && !hasClientPlugin && !this.plugin.options.client.importPath) await this.upsertFile({
108
- baseName: "fetch.ts",
109
- path: path.resolve(root, ".kubb/fetch.ts"),
110
- sources: [{
111
- name: "fetch",
112
- value: this.plugin.options.client.client === "fetch" ? source$1 : source,
113
- isExportable: true,
114
- isIndexable: true
115
- }],
116
- imports: [],
117
- exports: []
118
- });
119
- if (!hasClientPlugin) await this.addFile({
120
- baseName: "config.ts",
121
- path: path.resolve(root, ".kubb/config.ts"),
122
- sources: [{
123
- name: "config",
124
- value: source$2,
125
- isExportable: false,
126
- isIndexable: false
127
- }],
128
- imports: [],
129
- exports: []
130
- });
131
- const files = await new OperationGenerator(this.plugin.options, {
132
- fabric: this.fabric,
133
- oas,
134
- driver: this.driver,
135
- events: this.events,
136
- plugin: this.plugin,
137
- contentType,
1606
+ options,
1607
+ dependencies: [pluginTsName],
1608
+ hooks: { "kubb:plugin:setup"(ctx) {
1609
+ const resolver = userResolver ? Resolver.merge(resolverVueQuery, userResolver) : resolverVueQuery;
1610
+ ctx.setOptions({
1611
+ output,
1612
+ client: resolveContractClient({
1613
+ client,
1614
+ plugins: ctx.config.plugins
1615
+ }),
1616
+ queryKey,
1617
+ query: resolveQueryConfig(query, { importPath: "@tanstack/vue-query" }),
1618
+ mutationKey,
1619
+ mutation: resolveMutationConfig(mutation, { importPath: "@tanstack/vue-query" }),
1620
+ infinite: resolveInfiniteConfig(infinite),
1621
+ hooks,
1622
+ group: groupConfig,
138
1623
  exclude,
139
1624
  include,
140
1625
  override,
141
- mode
142
- }).build(...generators);
143
- await this.upsertFile(...files);
144
- const barrelFiles = await getBarrelFiles(this.fabric.files, {
145
- type: output.barrelType ?? "named",
146
- root,
147
- output,
148
- meta: { pluginName: this.plugin.name }
1626
+ resolver
149
1627
  });
150
- await this.upsertFile(...barrelFiles);
151
- }
1628
+ ctx.setResolver(resolver);
1629
+ if (userMacros?.length) ctx.setMacros(userMacros);
1630
+ ctx.addGenerator(...selectedGenerators);
1631
+ } }
152
1632
  };
153
1633
  });
154
1634
  //#endregion
155
- export { pluginVueQuery, pluginVueQueryName };
1635
+ export { pluginVueQuery as default, pluginVueQuery, pluginVueQueryName, resolverVueQuery };
156
1636
 
157
1637
  //# sourceMappingURL=index.js.map