@kubb/plugin-vue-query 5.0.0-beta.64 → 5.0.0-beta.73

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.
@@ -1,1238 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __name = (target, value) => __defProp(target, "name", {
5
- value,
6
- configurable: true
7
- });
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __getProtoOf = Object.getPrototypeOf;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
- key = keys[i];
15
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
- //#endregion
27
- let _kubb_core = require("@kubb/core");
28
- let _kubb_ast_utils = require("@kubb/ast/utils");
29
- let _kubb_plugin_ts = require("@kubb/plugin-ts");
30
- let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
31
- let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
32
- //#region ../../internals/utils/src/casing.ts
33
- /**
34
- * Shared implementation for camelCase and PascalCase conversion.
35
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
36
- * and capitalizes each word according to `pascal`.
37
- *
38
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
39
- */
40
- function toCamelOrPascal(text, pascal) {
41
- 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) => {
42
- if (word.length > 1 && word === word.toUpperCase()) return word;
43
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
44
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
45
- }
46
- /**
47
- * Converts `text` to camelCase.
48
- *
49
- * @example Word boundaries
50
- * `camelCase('hello-world') // 'helloWorld'`
51
- *
52
- * @example With a prefix
53
- * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
54
- */
55
- function camelCase(text, { prefix = "", suffix = "" } = {}) {
56
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
57
- }
58
- //#endregion
59
- //#region ../../internals/utils/src/reserved.ts
60
- /**
61
- * JavaScript and Java reserved words.
62
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
63
- */
64
- const reservedWords = new Set([
65
- "abstract",
66
- "arguments",
67
- "boolean",
68
- "break",
69
- "byte",
70
- "case",
71
- "catch",
72
- "char",
73
- "class",
74
- "const",
75
- "continue",
76
- "debugger",
77
- "default",
78
- "delete",
79
- "do",
80
- "double",
81
- "else",
82
- "enum",
83
- "eval",
84
- "export",
85
- "extends",
86
- "false",
87
- "final",
88
- "finally",
89
- "float",
90
- "for",
91
- "function",
92
- "goto",
93
- "if",
94
- "implements",
95
- "import",
96
- "in",
97
- "instanceof",
98
- "int",
99
- "interface",
100
- "let",
101
- "long",
102
- "native",
103
- "new",
104
- "null",
105
- "package",
106
- "private",
107
- "protected",
108
- "public",
109
- "return",
110
- "short",
111
- "static",
112
- "super",
113
- "switch",
114
- "synchronized",
115
- "this",
116
- "throw",
117
- "throws",
118
- "transient",
119
- "true",
120
- "try",
121
- "typeof",
122
- "var",
123
- "void",
124
- "volatile",
125
- "while",
126
- "with",
127
- "yield",
128
- "Array",
129
- "Date",
130
- "hasOwnProperty",
131
- "Infinity",
132
- "isFinite",
133
- "isNaN",
134
- "isPrototypeOf",
135
- "length",
136
- "Math",
137
- "name",
138
- "NaN",
139
- "Number",
140
- "Object",
141
- "prototype",
142
- "String",
143
- "toString",
144
- "undefined",
145
- "valueOf"
146
- ]);
147
- /**
148
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
149
- *
150
- * @example
151
- * ```ts
152
- * isValidVarName('status') // true
153
- * isValidVarName('class') // false (reserved word)
154
- * isValidVarName('42foo') // false (starts with digit)
155
- * ```
156
- */
157
- function isValidVarName(name) {
158
- if (!name || reservedWords.has(name)) return false;
159
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
160
- }
161
- //#endregion
162
- //#region ../../internals/utils/src/url.ts
163
- function transformParam(raw, casing) {
164
- const param = isValidVarName(raw) ? raw : camelCase(raw);
165
- return casing === "camelcase" ? camelCase(param) : param;
166
- }
167
- function toParamsObject(path, { replacer, casing } = {}) {
168
- const params = {};
169
- for (const match of path.matchAll(/\{([^}]+)\}/g)) {
170
- const param = transformParam(match[1], casing);
171
- const key = replacer ? replacer(param) : param;
172
- params[key] = key;
173
- }
174
- return Object.keys(params).length > 0 ? params : null;
175
- }
176
- /**
177
- * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.
178
- */
179
- var Url = class Url {
180
- /**
181
- * Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.
182
- *
183
- * @example
184
- * Url.canParse('https://petstore.swagger.io/v2') // true
185
- * Url.canParse('/pet/{petId}') // false
186
- */
187
- static canParse(url, base) {
188
- return URL.canParse(url, base);
189
- }
190
- /**
191
- * Converts an OpenAPI/Swagger path to Express-style colon syntax.
192
- *
193
- * @example
194
- * Url.toPath('/pet/{petId}') // '/pet/:petId'
195
- */
196
- static toPath(path) {
197
- return path.replace(/\{([^}]+)\}/g, ":$1");
198
- }
199
- /**
200
- * Converts an OpenAPI/Swagger path to a TypeScript template literal string.
201
- * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,
202
- * and `casing` controls parameter identifier casing.
203
- *
204
- * @example
205
- * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'
206
- *
207
- * @example
208
- * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'
209
- */
210
- static toTemplateString(path, { prefix, replacer, casing } = {}) {
211
- const result = path.split(/\{([^}]+)\}/).map((part, i) => {
212
- if (i % 2 === 0) return part;
213
- const param = transformParam(part, casing);
214
- return `\${${replacer ? replacer(param) : param}}`;
215
- }).join("");
216
- return `\`${prefix ?? ""}${result}\``;
217
- }
218
- /**
219
- * Returns the path and its extracted params as a structured `URLObject`, or as a stringified
220
- * expression when `stringify` is set.
221
- *
222
- * @example
223
- * Url.toObject('/pet/{petId}')
224
- * // { url: '/pet/:petId', params: { petId: 'petId' } }
225
- */
226
- static toObject(path, { type = "path", replacer, stringify, casing } = {}) {
227
- const object = {
228
- url: type === "path" ? Url.toPath(path) : Url.toTemplateString(path, {
229
- replacer,
230
- casing
231
- }),
232
- params: toParamsObject(path, {
233
- replacer,
234
- casing
235
- })
236
- };
237
- if (stringify) {
238
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
239
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
240
- return `{ url: '${object.url}' }`;
241
- }
242
- return object;
243
- }
244
- };
245
- //#endregion
246
- //#region ../../internals/shared/src/operation.ts
247
- /**
248
- * Builds the `ResolverFileParams` every operation generator passes to
249
- * `resolver.resolveFile`: a file named `name`, tagged by the operation's first
250
- * tag (or `'default'`), at the operation's path. Centralizes the entry object
251
- * that was repeated at dozens of call sites across the client and query plugins.
252
- *
253
- * @example
254
- * ```ts
255
- * resolver.resolveFile(operationFileEntry(node, node.operationId), { root, output, group })
256
- * ```
257
- */
258
- function operationFileEntry(node, name, extname = ".ts") {
259
- return {
260
- name,
261
- extname,
262
- tag: node.tags[0] ?? "default",
263
- path: node.path
264
- };
265
- }
266
- function getOperationLink(node, link) {
267
- if (!link) return null;
268
- if (typeof link === "function") return link(node) ?? null;
269
- if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
270
- return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
271
- }
272
- function getContentTypeInfo(node) {
273
- const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
274
- const isMultipleContentTypes = contentTypes.length > 1;
275
- return {
276
- contentTypes,
277
- isMultipleContentTypes,
278
- contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
279
- defaultContentType: contentTypes[0] ?? "application/json",
280
- hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
281
- };
282
- }
283
- function buildRequestConfigType(node, resolver) {
284
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
285
- const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
286
- return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
287
- }
288
- function buildOperationComments(node, options = {}) {
289
- const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
290
- const linkComment = getOperationLink(node, link);
291
- const filteredComments = (linkPosition === "beforeDeprecated" ? [
292
- node.description && `@description ${node.description}`,
293
- node.summary && `@summary ${node.summary}`,
294
- linkComment,
295
- node.deprecated && "@deprecated"
296
- ] : [
297
- node.description && `@description ${node.description}`,
298
- node.summary && `@summary ${node.summary}`,
299
- node.deprecated && "@deprecated",
300
- linkComment
301
- ]).filter((comment) => Boolean(comment));
302
- if (!splitLines) return filteredComments;
303
- return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
304
- }
305
- function getOperationParameters(node, options = {}) {
306
- const params = (0, _kubb_ast_utils.caseParams)(node.parameters, options.paramsCasing);
307
- return {
308
- path: params.filter((param) => param.in === "path"),
309
- query: params.filter((param) => param.in === "query"),
310
- header: params.filter((param) => param.in === "header"),
311
- cookie: params.filter((param) => param.in === "cookie")
312
- };
313
- }
314
- function getStatusCodeNumber(statusCode) {
315
- const code = Number(statusCode);
316
- return Number.isNaN(code) ? null : code;
317
- }
318
- function isSuccessStatusCode(statusCode) {
319
- const code = getStatusCodeNumber(statusCode);
320
- return code !== null && code >= 200 && code < 300;
321
- }
322
- function isErrorStatusCode(statusCode) {
323
- const code = getStatusCodeNumber(statusCode);
324
- return code !== null && code >= 400;
325
- }
326
- function resolveErrorNames(node, resolver) {
327
- return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
328
- }
329
- function resolveSuccessNames(node, resolver) {
330
- return node.responses.filter((response) => isSuccessStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
331
- }
332
- function resolveStatusCodeNames(node, resolver) {
333
- return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
334
- }
335
- /**
336
- * Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
337
- * Each member is `{ status: N; data: StatusNType; statusText: string }`.
338
- */
339
- function buildStatusUnionType(node, resolver) {
340
- const members = node.responses.map((r) => {
341
- const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
342
- const statusCode = Number.parseInt(r.statusCode, 10);
343
- return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
344
- });
345
- if (members.length === 1) return members[0];
346
- return `(${members.join(" | ")})`;
347
- }
348
- const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
349
- function resolveOperationTypeNames(node, resolver, options = {}) {
350
- const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
351
- let byResolver = typeNamesByResolver.get(resolver);
352
- if (byResolver) {
353
- const cached = byResolver.get(cacheKey);
354
- if (cached) return cached;
355
- } else {
356
- byResolver = /* @__PURE__ */ new Map();
357
- typeNamesByResolver.set(resolver, byResolver);
358
- }
359
- const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
360
- const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
361
- const exclude = new Set(options.exclude ?? []);
362
- const paramNames = [
363
- ...path.map((param) => resolver.resolvePathParamsName(node, param)),
364
- ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
365
- ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
366
- ];
367
- const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
368
- const result = (options.order === "body-response-first" ? [
369
- ...bodyAndResponseNames,
370
- ...paramNames,
371
- ...responseStatusNames
372
- ] : [
373
- ...paramNames,
374
- ...bodyAndResponseNames,
375
- ...responseStatusNames
376
- ]).filter((name) => Boolean(name) && !exclude.has(name));
377
- byResolver.set(cacheKey, result);
378
- return result;
379
- }
380
- //#endregion
381
- //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
382
- const declarationPrinter$7 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
383
- const mutationKeyTransformer = ({ node }) => {
384
- if (!node.path) return [];
385
- return [`{ url: '${Url.toPath(node.path)}' }`];
386
- };
387
- function MutationKey({ name, paramsCasing, node, transformer }) {
388
- const paramsNode = _kubb_core.ast.factory.createFunctionParameters({ params: [] });
389
- const paramsSignature = declarationPrinter$7.print(paramsNode) ?? "";
390
- const keys = (transformer ?? mutationKeyTransformer)({
391
- node,
392
- casing: paramsCasing
393
- });
394
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
395
- name,
396
- isExportable: true,
397
- isIndexable: true,
398
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
399
- name,
400
- export: true,
401
- params: paramsSignature,
402
- singleLine: true,
403
- children: `[${keys.join(", ")}] as const`
404
- })
405
- });
406
- }
407
- //#endregion
408
- //#region ../../internals/tanstack-query/src/utils.ts
409
- /**
410
- * Returns the `TypeLiteral` members of a destructured group parameter, or `null`
411
- * for a plain named parameter.
412
- */
413
- function groupMembers(param) {
414
- if (typeof param.name === "string") return null;
415
- return param.type && typeof param.type !== "string" && param.type.kind === "TypeLiteral" ? param.type.members : [];
416
- }
417
- /**
418
- * Builds the shared `(…params, config = {})` parameter list for a TanStack
419
- * query-options function. The trailing `config` parameter is typed as a partial
420
- * `RequestConfig` with an optional `client`. Framework plugins wrap the result
421
- * when needed, for example vue-query applies `MaybeRefOrGetter`.
422
- */
423
- function buildQueryOptionsParams(node, options) {
424
- const { paramsType, paramsCasing, pathParamsType, resolver } = options;
425
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
426
- return (0, _kubb_ast_utils.createOperationParams)(node, {
427
- paramsType,
428
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
429
- paramsCasing,
430
- resolver,
431
- extraParams: [_kubb_core.ast.factory.createFunctionParameter({
432
- name: "config",
433
- type: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }",
434
- default: "{}"
435
- })]
436
- });
437
- }
438
- /**
439
- * Returns `'zod'` when response-direction parsing is enabled.
440
- * The string shorthand `'zod'` also enables response parsing.
441
- */
442
- function resolveResponseParser(parser) {
443
- if (!parser) return null;
444
- if (parser === "zod") return "zod";
445
- return parser.response ?? null;
446
- }
447
- /**
448
- * Returns `'zod'` when request body parsing is enabled.
449
- * The string shorthand `'zod'` also enables request body parsing (existing behavior).
450
- */
451
- function resolveRequestParser(parser) {
452
- if (!parser) return null;
453
- if (parser === "zod") return "zod";
454
- return parser.request ?? null;
455
- }
456
- /**
457
- * Returns `'zod'` when query-params parsing is enabled.
458
- * Only the object form `{ request: 'zod' }` enables this. `parser: 'zod'` does not.
459
- */
460
- function resolveQueryParamsParser(parser) {
461
- if (!parser || parser === "zod") return null;
462
- return parser.request ?? null;
463
- }
464
- /**
465
- * Collects the Zod schema import names for an operation based on the active parser directions.
466
- *
467
- * - `parser: 'zod'`: response and request body names (backward-compatible behavior).
468
- * - `parser: { request: 'zod' }`: request body and query params names.
469
- * - `parser: { response: 'zod' }`: response name only.
470
- * - `parser: { request: 'zod', response: 'zod' }`: all three.
471
- *
472
- * Returns an empty array when no resolver is provided or `parser` is falsy.
473
- */
474
- function resolveZodSchemaNames(node, zodResolver, parser) {
475
- if (!zodResolver || !parser) return [];
476
- const { query: queryParams } = getOperationParameters(node);
477
- return [
478
- resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
479
- resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
480
- resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
481
- ].filter((n) => Boolean(n));
482
- }
483
- /**
484
- * Build QueryKey params: pathParams + data + queryParams (NO headers, NO config).
485
- */
486
- function buildQueryKeyParams(node, options) {
487
- const { pathParamsType, paramsCasing, resolver } = options;
488
- const casedParams = (0, _kubb_ast_utils.caseParams)(node.parameters, paramsCasing);
489
- const pathParams = casedParams.filter((p) => p.in === "path");
490
- const queryParams = casedParams.filter((p) => p.in === "query");
491
- const queryGroupType = (0, _kubb_ast_utils.resolveGroupType)({
492
- node,
493
- params: queryParams,
494
- group: "query",
495
- resolver
496
- });
497
- const bodyType = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
498
- const bodyRequired = node.requestBody?.required ?? false;
499
- const params = [];
500
- if (pathParams.length) {
501
- const pathChildren = pathParams.map((p) => ({
502
- name: p.name,
503
- type: (0, _kubb_ast_utils.resolveParamType)({
504
- node,
505
- param: p,
506
- resolver
507
- }),
508
- optional: !p.required
509
- }));
510
- if (pathParamsType === "object") params.push(_kubb_core.ast.factory.createFunctionParameter({
511
- properties: pathChildren,
512
- default: pathChildren.every((c) => c.optional) ? "{}" : void 0
513
- }));
514
- else params.push(...pathChildren.map((child) => _kubb_core.ast.factory.createFunctionParameter(child)));
515
- }
516
- if (bodyType) params.push(_kubb_core.ast.factory.createFunctionParameter({
517
- name: "data",
518
- type: bodyType,
519
- optional: !bodyRequired
520
- }));
521
- params.push(...(0, _kubb_ast_utils.buildGroupParam)({
522
- name: "params",
523
- node,
524
- params: queryParams,
525
- groupType: queryGroupType,
526
- resolver,
527
- wrapType: (type) => type
528
- }));
529
- return _kubb_core.ast.factory.createFunctionParameters({ params });
530
- }
531
- /**
532
- * Collect the names of the required params (no default) that drive the `enabled`
533
- * guard. These are exactly the params that should be made optional in the
534
- * generated signatures so callers can pass `undefined` to reach the disabled state.
535
- */
536
- function getEnabledParamNames(paramsNode) {
537
- const required = [];
538
- for (const param of paramsNode.params) {
539
- const members = groupMembers(param);
540
- if (members) {
541
- for (const member of members) if (!member.optional) required.push(member.name);
542
- } else if (typeof param.name === "string" && !param.optional && param.default === void 0) required.push(param.name);
543
- }
544
- return required;
545
- }
546
- /**
547
- * Return a copy of `paramsNode` with the named params marked optional.
548
- *
549
- * Used to align signatures with the `enabled` guard: the guard already disables
550
- * the query while a param is falsy, so the param should accept `undefined`. The
551
- * change is type-only — the `queryFn` keeps calling the client with a non-null
552
- * assertion (see `injectNonNullAssertions`), so the emitted runtime is unchanged.
553
- */
554
- function markParamsOptional(paramsNode, names) {
555
- if (names.length === 0) return paramsNode;
556
- const nameSet = new Set(names);
557
- const params = paramsNode.params.map((param) => {
558
- const members = groupMembers(param);
559
- if (members) {
560
- const next = members.map((member) => nameSet.has(member.name) ? {
561
- ...member,
562
- optional: true
563
- } : member);
564
- return {
565
- ...param,
566
- type: _kubb_core.ast.factory.createTypeLiteral({ members: next })
567
- };
568
- }
569
- return typeof param.name === "string" && nameSet.has(param.name) ? _kubb_core.ast.factory.createFunctionParameter({
570
- name: param.name,
571
- type: param.type,
572
- rest: param.rest,
573
- optional: true
574
- }) : param;
575
- });
576
- return _kubb_core.ast.factory.createFunctionParameters({ params });
577
- }
578
- (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
579
- const queryKeyTransformer = ({ node, casing }) => {
580
- if (!node.path) return [];
581
- const hasQueryParams = getOperationParameters(node).query.length > 0;
582
- const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
583
- return [
584
- Url.toObject(node.path, {
585
- type: "path",
586
- stringify: true,
587
- casing
588
- }),
589
- hasQueryParams ? "...(params ? [params] : [])" : null,
590
- hasRequestBody ? "...(data ? [data] : [])" : null
591
- ].filter(Boolean);
592
- };
593
- //#endregion
594
- //#region src/utils.ts
595
- /**
596
- * Wraps each parameter type in `MaybeRefOrGetter<…>` so a vue-query signature
597
- * accepts refs or getters. Group members are wrapped individually; `skip` opts a
598
- * plain parameter out by name.
599
- */
600
- function wrapWithMaybeRefOrGetter(paramsNode, skip) {
601
- const wrappedParams = paramsNode.params.map((param) => {
602
- if (typeof param.name !== "string") {
603
- const type = param.type;
604
- if (type && typeof type !== "string" && type.kind === "TypeLiteral") return {
605
- ...param,
606
- type: _kubb_core.ast.factory.createTypeLiteral({ members: type.members.map((member) => ({
607
- ...member,
608
- type: `MaybeRefOrGetter<${(0, _kubb_plugin_ts.renderType)(member.type)}>`
609
- })) })
610
- };
611
- return param;
612
- }
613
- if (skip?.(param.name)) return param;
614
- return {
615
- ...param,
616
- type: param.type ? `MaybeRefOrGetter<${(0, _kubb_plugin_ts.renderType)(param.type)}>` : param.type
617
- };
618
- });
619
- return _kubb_core.ast.factory.createFunctionParameters({ params: wrappedParams });
620
- }
621
- //#endregion
622
- //#region src/components/QueryKey.tsx
623
- const declarationPrinter$5 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
624
- function buildQueryKeyParamsNode(node, options) {
625
- return wrapWithMaybeRefOrGetter(buildQueryKeyParams(node, options));
626
- }
627
- function QueryKey({ name, node, tsResolver, paramsCasing, pathParamsType, typeName, transformer }) {
628
- const baseParamsNode = buildQueryKeyParamsNode(node, {
629
- pathParamsType,
630
- paramsCasing,
631
- resolver: tsResolver
632
- });
633
- const paramsNode = markParamsOptional(baseParamsNode, getEnabledParamNames(baseParamsNode));
634
- const paramsSignature = declarationPrinter$5.print(paramsNode) ?? "";
635
- const keys = (transformer ?? queryKeyTransformer)({
636
- node,
637
- casing: paramsCasing
638
- });
639
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
640
- name,
641
- isExportable: true,
642
- isIndexable: true,
643
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function.Arrow, {
644
- name,
645
- export: true,
646
- params: paramsSignature,
647
- singleLine: true,
648
- children: `[${keys.join(", ")}] as const`
649
- })
650
- }), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
651
- name: typeName,
652
- isExportable: true,
653
- isIndexable: true,
654
- isTypeOnly: true,
655
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
656
- name: typeName,
657
- export: true,
658
- children: `ReturnType<typeof ${name}>`
659
- })
660
- })] });
661
- }
662
- //#endregion
663
- //#region src/components/QueryOptions.tsx
664
- const declarationPrinter$4 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
665
- const callPrinter$4 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
666
- function getQueryOptionsParams(node, options) {
667
- return wrapWithMaybeRefOrGetter(buildQueryOptionsParams(node, options), (name) => name === "config");
668
- }
669
- function QueryOptions({ name, clientName, dataReturnType, node, tsResolver, paramsCasing, paramsType, pathParamsType, queryKeyName }) {
670
- const successNames = resolveSuccessNames(node, tsResolver);
671
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
672
- const errorNames = resolveErrorNames(node, tsResolver);
673
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
674
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
675
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
676
- pathParamsType,
677
- paramsCasing,
678
- resolver: tsResolver
679
- });
680
- const queryKeyParamsCall = callPrinter$4.print(queryKeyParamsNode) ?? "";
681
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
682
- const enabledText = enabledNames.length ? `enabled: () => ${enabledNames.map((n) => `!!toValue(${n})`).join(" && ")},` : "";
683
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
684
- paramsType,
685
- paramsCasing,
686
- pathParamsType,
687
- resolver: tsResolver
688
- }), enabledNames);
689
- const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
690
- const clientCallStr = (callPrinter$4.print(paramsNode) ?? "").replace(/\bconfig\b(?=[^,]*$)/, "{ ...config, signal: config.signal ?? signal }");
691
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
692
- name,
693
- isExportable: true,
694
- isIndexable: true,
695
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
696
- name,
697
- export: true,
698
- params: paramsSignature,
699
- children: `
700
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
701
- return queryOptions<${TData}, ${TError}, ${TData}>({${enabledText ? `\n ${enabledText}` : ""}
702
- queryKey,
703
- queryFn: async ({ signal }) => {
704
- return ${clientName}(${addToValueCalls$1(clientCallStr, enabledNames)})
705
- },
706
- })
707
- `
708
- })
709
- });
710
- }
711
- /**
712
- * Wraps parameter names with `toValue()` in the client call string,
713
- * except for 'config'-related params (which are already plain objects).
714
- *
715
- * Handles both inline params (`petId, config`) and object shorthand
716
- * params (`{ petId }, config`) by expanding to `{ petId: toValue(petId) }`.
717
- */
718
- function addToValueCalls$1(callStr, enabledNames = []) {
719
- const optional = new Set(enabledNames);
720
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
721
- if (inner.includes(":") || inner.includes("...")) return match;
722
- return `{ ${inner.split(",").map((k) => k.trim()).filter(Boolean).map((k) => `${k}: toValue(${optional.has(k) ? `${k}!` : k})`).join(", ")} }`;
723
- });
724
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => {
725
- if (name === "config" || name === "signal" || name === "undefined") return match;
726
- if (match.includes("toValue(")) return match;
727
- return `toValue(${optional.has(name) ? `${name}!` : name})`;
728
- });
729
- return result;
730
- }
731
- __name(addToValueCalls$1, "addToValueCalls");
732
- //#endregion
733
- //#region src/components/InfiniteQuery.tsx
734
- const declarationPrinter$3 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
735
- const callPrinter$3 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
736
- function buildInfiniteQueryParamsNode(node, options) {
737
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
738
- const successNames = resolveSuccessNames(node, resolver);
739
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
740
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
741
- const errorNames = resolveErrorNames(node, resolver);
742
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
743
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
744
- const optionsParam = _kubb_core.ast.factory.createFunctionParameter({
745
- name: "options",
746
- type: `{
747
- query?: Partial<UseInfiniteQueryOptions<${[
748
- TData,
749
- TError,
750
- "TQueryData",
751
- "TQueryKey",
752
- "TQueryData"
753
- ].join(", ")}>> & { client?: QueryClient },
754
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"}
755
- }`,
756
- default: "{}"
757
- });
758
- return wrapWithMaybeRefOrGetter((0, _kubb_ast_utils.createOperationParams)(node, {
759
- paramsType,
760
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
761
- paramsCasing,
762
- resolver,
763
- extraParams: [optionsParam]
764
- }), (name) => name === "options");
765
- }
766
- function InfiniteQuery({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
767
- const successNames = resolveSuccessNames(node, tsResolver);
768
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
769
- const errorNames = resolveErrorNames(node, tsResolver);
770
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
771
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
772
- const returnType = `UseInfiniteQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
773
- const generics = [
774
- `TData = InfiniteData<${TData}>`,
775
- `TQueryData = ${TData}`,
776
- `TQueryKey extends QueryKey = ${queryKeyTypeName}`
777
- ];
778
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
779
- pathParamsType,
780
- paramsCasing,
781
- resolver: tsResolver
782
- });
783
- const queryKeyParamsCall = callPrinter$3.print(queryKeyParamsNode) ?? "";
784
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
785
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
786
- paramsType,
787
- paramsCasing,
788
- pathParamsType,
789
- resolver: tsResolver
790
- });
791
- const queryOptionsParamsCall = callPrinter$3.print(queryOptionsParamsNode) ?? "";
792
- const paramsNode = markParamsOptional(buildInfiniteQueryParamsNode(node, {
793
- paramsType,
794
- paramsCasing,
795
- pathParamsType,
796
- dataReturnType,
797
- resolver: tsResolver
798
- }), enabledNames);
799
- const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
800
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
801
- name,
802
- isExportable: true,
803
- isIndexable: true,
804
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
805
- name,
806
- export: true,
807
- generics: generics.join(", "),
808
- params: paramsSignature,
809
- JSDoc: { comments: buildOperationComments(node) },
810
- children: `
811
- const { query: queryConfig = {}, client: config = {} } = options ?? {}
812
- const { client: queryClient, ...resolvedOptions } = queryConfig
813
- const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
814
-
815
- const query = useInfiniteQuery({
816
- ...${queryOptionsName}(${queryOptionsParamsCall}),
817
- ...resolvedOptions,
818
- queryKey
819
- } as unknown as UseInfiniteQueryOptions<${TData}, ${TError}, ${TData}, TQueryKey, ${TData}>, toValue(queryClient)) as ${returnType}
820
-
821
- query.queryKey = queryKey as TQueryKey
822
-
823
- return query
824
- `
825
- })
826
- });
827
- }
828
- //#endregion
829
- //#region src/components/InfiniteQueryOptions.tsx
830
- const declarationPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
831
- const callPrinter$2 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
832
- function InfiniteQueryOptions({ name, clientName, initialPageParam, cursorParam, nextParam, previousParam, node, tsResolver, paramsCasing, paramsType, dataReturnType, pathParamsType, queryParam, queryKeyName }) {
833
- const successNames = resolveSuccessNames(node, tsResolver);
834
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
835
- const queryFnDataType = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
836
- const errorNames = resolveErrorNames(node, tsResolver);
837
- const errorType = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
838
- const isInitialPageParamDefined = initialPageParam !== void 0 && initialPageParam !== null;
839
- const fallbackPageParamType = typeof initialPageParam === "number" ? "number" : typeof initialPageParam === "string" ? initialPageParam.includes(" as ") ? (() => {
840
- const parts = initialPageParam.split(" as ");
841
- return parts[parts.length - 1] ?? "unknown";
842
- })() : "string" : typeof initialPageParam === "boolean" ? "boolean" : "unknown";
843
- const rawQueryParams = getOperationParameters(node).query;
844
- const queryParamsTypeName = rawQueryParams.length > 0 ? (() => {
845
- const groupName = tsResolver.resolveQueryParamsName(node, rawQueryParams[0]);
846
- return groupName !== tsResolver.resolveParamName(node, rawQueryParams[0]) ? groupName : null;
847
- })() : null;
848
- const queryParamType = queryParam && queryParamsTypeName ? `${queryParamsTypeName}['${queryParam}']` : null;
849
- const pageParamType = queryParamType ? isInitialPageParamDefined ? `NonNullable<${queryParamType}>` : queryParamType : fallbackPageParamType;
850
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
851
- pathParamsType,
852
- paramsCasing,
853
- resolver: tsResolver
854
- });
855
- const queryKeyParamsCall = callPrinter$2.print(queryKeyParamsNode) ?? "";
856
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
857
- const enabledText = enabledNames.length ? `enabled: () => ${enabledNames.map((n) => `!!toValue(${n})`).join(" && ")},` : "";
858
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
859
- paramsType,
860
- paramsCasing,
861
- pathParamsType,
862
- resolver: tsResolver
863
- }), enabledNames);
864
- const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
865
- const clientCallStr = (callPrinter$2.print(paramsNode) ?? "").replace(/\bconfig\b(?=[^,]*$)/, "{ ...config, signal: config.signal ?? signal }");
866
- const hasNewParams = nextParam != null || previousParam != null;
867
- const [getNextPageParamExpr, getPreviousPageParamExpr] = (() => {
868
- if (hasNewParams) {
869
- const nextAccessor = nextParam ? (0, _kubb_ast_utils.getNestedAccessor)(nextParam, "lastPage") : null;
870
- const prevAccessor = previousParam ? (0, _kubb_ast_utils.getNestedAccessor)(previousParam, "firstPage") : null;
871
- return [nextAccessor ? `getNextPageParam: (lastPage) => ${nextAccessor}` : null, prevAccessor ? `getPreviousPageParam: (firstPage) => ${prevAccessor}` : null];
872
- }
873
- if (cursorParam) return [`getNextPageParam: (lastPage) => lastPage['${cursorParam}']`, `getPreviousPageParam: (firstPage) => firstPage['${cursorParam}']`];
874
- return [dataReturnType === "full" ? "getNextPageParam: (lastPage, _allPages, lastPageParam) => Array.isArray(lastPage.data) && lastPage.data.length === 0 ? undefined : lastPageParam + 1" : "getNextPageParam: (lastPage, _allPages, lastPageParam) => Array.isArray(lastPage) && lastPage.length === 0 ? undefined : lastPageParam + 1", "getPreviousPageParam: (_firstPage, _allPages, firstPageParam) => firstPageParam <= 1 ? undefined : firstPageParam - 1"];
875
- })();
876
- const queryOptionsArr = [
877
- `initialPageParam: ${typeof initialPageParam === "string" ? JSON.stringify(initialPageParam) : initialPageParam}`,
878
- getNextPageParamExpr,
879
- getPreviousPageParamExpr
880
- ].filter(Boolean);
881
- const infiniteOverrideParams = queryParam && queryParamsTypeName ? `params = {
882
- ...(params ?? {}),
883
- ['${queryParam}']: pageParam as unknown as ${queryParamsTypeName}['${queryParam}'],
884
- } as ${queryParamsTypeName}` : "";
885
- if (infiniteOverrideParams) return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
886
- name,
887
- isExportable: true,
888
- isIndexable: true,
889
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
890
- name,
891
- export: true,
892
- params: paramsSignature,
893
- children: `
894
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
895
- return infiniteQueryOptions<${queryFnDataType}, ${errorType}, InfiniteData<${queryFnDataType}>, QueryKey, ${pageParamType}>({${enabledText ? `\n ${enabledText}` : ""}
896
- queryKey,
897
- queryFn: async ({ signal, pageParam }) => {
898
- ${infiniteOverrideParams}
899
- return ${clientName}(${addToValueCalls(clientCallStr, enabledNames)})
900
- },
901
- ${queryOptionsArr.join(",\n ")}
902
- })
903
- `
904
- })
905
- });
906
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
907
- name,
908
- isExportable: true,
909
- isIndexable: true,
910
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
911
- name,
912
- export: true,
913
- params: paramsSignature,
914
- children: `
915
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
916
- return infiniteQueryOptions<${queryFnDataType}, ${errorType}, InfiniteData<${queryFnDataType}>, QueryKey, ${pageParamType}>({${enabledText ? `\n ${enabledText}` : ""}
917
- queryKey,
918
- queryFn: async ({ signal }) => {
919
- return ${clientName}(${addToValueCalls(clientCallStr, enabledNames)})
920
- },
921
- ${queryOptionsArr.join(",\n ")}
922
- })
923
- `
924
- })
925
- });
926
- }
927
- function addToValueCalls(callStr, enabledNames = []) {
928
- const optional = new Set(enabledNames);
929
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
930
- if (inner.includes(":") || inner.includes("...")) return match;
931
- return `{ ${inner.split(",").map((k) => k.trim()).filter(Boolean).map((k) => `${k}: toValue(${optional.has(k) ? `${k}!` : k})`).join(", ")} }`;
932
- });
933
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => {
934
- if (name === "config" || name === "signal" || name === "undefined") return match;
935
- if (match.includes("toValue(")) return match;
936
- return `toValue(${optional.has(name) ? `${name}!` : name})`;
937
- });
938
- return result;
939
- }
940
- //#endregion
941
- //#region src/components/Mutation.tsx
942
- const declarationPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
943
- const callPrinter$1 = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
944
- const keysPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
945
- function createMutationArgParams(node, options) {
946
- return (0, _kubb_ast_utils.createOperationParams)(node, {
947
- paramsType: "inline",
948
- pathParamsType: "inline",
949
- paramsCasing: options.paramsCasing,
950
- resolver: options.resolver
951
- });
952
- }
953
- function buildMutationParamsNode(node, options) {
954
- const { paramsCasing, dataReturnType, resolver } = options;
955
- const successNames = resolveSuccessNames(node, resolver);
956
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
957
- const errorNames = resolveErrorNames(node, resolver);
958
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
959
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
960
- const wrappedParamsNode = wrapWithMaybeRefOrGetter(createMutationArgParams(node, {
961
- paramsCasing,
962
- resolver
963
- }));
964
- const TRequestWrapped = wrappedParamsNode.params.length > 0 ? declarationPrinter$1.print(wrappedParamsNode) ?? "" : "";
965
- return _kubb_core.ast.factory.createFunctionParameters({ params: [_kubb_core.ast.factory.createFunctionParameter({
966
- name: "options",
967
- type: `{
968
- mutation?: MutationObserverOptions<${[
969
- TData,
970
- TError,
971
- TRequestWrapped ? `{${TRequestWrapped}}` : "undefined",
972
- "TContext"
973
- ].join(", ")}> & { client?: QueryClient },
974
- client?: ${buildRequestConfigType(node, resolver)},
975
- }`,
976
- default: "{}"
977
- })] });
978
- }
979
- function Mutation({ name, clientName, paramsCasing, paramsType, pathParamsType, dataReturnType, node, tsResolver, mutationKeyName }) {
980
- const successNames = resolveSuccessNames(node, tsResolver);
981
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
982
- const errorNames = resolveErrorNames(node, tsResolver);
983
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
984
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
985
- const mutationArgParamsNode = createMutationArgParams(node, {
986
- paramsCasing,
987
- resolver: tsResolver
988
- });
989
- const hasMutationParams = mutationArgParamsNode.params.length > 0;
990
- const TRequest = hasMutationParams ? declarationPrinter$1.print(mutationArgParamsNode) ?? "" : "";
991
- const argKeysStr = hasMutationParams ? keysPrinter.print(mutationArgParamsNode) ?? "" : "";
992
- const generics = [
993
- TData,
994
- TError,
995
- TRequest ? `{${TRequest}}` : "undefined",
996
- "TContext"
997
- ].join(", ");
998
- const mutationKeyParamsNode = _kubb_core.ast.factory.createFunctionParameters({ params: [] });
999
- const mutationKeyParamsCall = callPrinter$1.print(mutationKeyParamsNode) ?? "";
1000
- const clientCallParamsNode = (0, _kubb_ast_utils.createOperationParams)(node, {
1001
- paramsType,
1002
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
1003
- paramsCasing,
1004
- resolver: tsResolver,
1005
- extraParams: [_kubb_core.ast.factory.createFunctionParameter({
1006
- name: "config",
1007
- type: buildRequestConfigType(node, tsResolver),
1008
- default: "{}"
1009
- })]
1010
- });
1011
- const clientCallStr = callPrinter$1.print(clientCallParamsNode) ?? "";
1012
- const paramsNode = buildMutationParamsNode(node, {
1013
- paramsCasing,
1014
- dataReturnType,
1015
- resolver: tsResolver
1016
- });
1017
- const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
1018
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
1019
- name,
1020
- isExportable: true,
1021
- isIndexable: true,
1022
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
1023
- name,
1024
- export: true,
1025
- params: paramsSignature,
1026
- JSDoc: { comments: buildOperationComments(node) },
1027
- generics: ["TContext"],
1028
- children: `
1029
- const { mutation = {}, client: config = {} } = options ?? {}
1030
- const { client: queryClient, ...mutationOptions } = mutation;
1031
- const mutationKey = mutationOptions?.mutationKey ?? ${mutationKeyName}(${mutationKeyParamsCall})
1032
-
1033
- return useMutation<${generics}>({
1034
- mutationFn: async(${hasMutationParams ? `{ ${argKeysStr} }` : ""}) => {
1035
- return ${clientName}(${clientCallStr})
1036
- },
1037
- mutationKey,
1038
- ...mutationOptions
1039
- }, queryClient)
1040
- `
1041
- })
1042
- });
1043
- }
1044
- //#endregion
1045
- //#region src/components/Query.tsx
1046
- const declarationPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "declaration" });
1047
- const callPrinter = (0, _kubb_plugin_ts.functionPrinter)({ mode: "call" });
1048
- function buildQueryParamsNode(node, options) {
1049
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
1050
- const successNames = resolveSuccessNames(node, resolver);
1051
- const responseName = successNames.length > 0 ? successNames.join(" | ") : resolver.resolveResponseName(node);
1052
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
1053
- const errorNames = resolveErrorNames(node, resolver);
1054
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
1055
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1056
- const optionsParam = _kubb_core.ast.factory.createFunctionParameter({
1057
- name: "options",
1058
- type: `{
1059
- query?: Partial<UseQueryOptions<${[
1060
- TData,
1061
- TError,
1062
- "TData",
1063
- "TQueryData",
1064
- "TQueryKey"
1065
- ].join(", ")}>> & { client?: QueryClient },
1066
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"}
1067
- }`,
1068
- default: "{}"
1069
- });
1070
- return wrapWithMaybeRefOrGetter((0, _kubb_ast_utils.createOperationParams)(node, {
1071
- paramsType,
1072
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
1073
- paramsCasing,
1074
- resolver,
1075
- extraParams: [optionsParam]
1076
- }), (name) => name === "options");
1077
- }
1078
- function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
1079
- const successNames = resolveSuccessNames(node, tsResolver);
1080
- const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
1081
- const errorNames = resolveErrorNames(node, tsResolver);
1082
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
1083
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
1084
- const returnType = `UseQueryReturnType<${["TData", TError].join(", ")}> & { queryKey: TQueryKey }`;
1085
- const generics = [
1086
- `TData = ${TData}`,
1087
- `TQueryData = ${TData}`,
1088
- `TQueryKey extends QueryKey = ${queryKeyTypeName}`
1089
- ];
1090
- const queryKeyParamsNode = buildQueryKeyParamsNode(node, {
1091
- pathParamsType,
1092
- paramsCasing,
1093
- resolver: tsResolver
1094
- });
1095
- const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
1096
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
1097
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
1098
- paramsType,
1099
- paramsCasing,
1100
- pathParamsType,
1101
- resolver: tsResolver
1102
- });
1103
- const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
1104
- const paramsNode = markParamsOptional(buildQueryParamsNode(node, {
1105
- paramsType,
1106
- paramsCasing,
1107
- pathParamsType,
1108
- dataReturnType,
1109
- resolver: tsResolver
1110
- }), enabledNames);
1111
- const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
1112
- return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
1113
- name,
1114
- isExportable: true,
1115
- isIndexable: true,
1116
- children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
1117
- name,
1118
- export: true,
1119
- generics: generics.join(", "),
1120
- params: paramsSignature,
1121
- JSDoc: { comments: buildOperationComments(node) },
1122
- children: `
1123
- const { query: queryConfig = {}, client: config = {} } = options ?? {}
1124
- const { client: queryClient, ...resolvedOptions } = queryConfig
1125
- const queryKey = (resolvedOptions && 'queryKey' in resolvedOptions ? toValue(resolvedOptions.queryKey) : undefined) ?? ${queryKeyName}(${queryKeyParamsCall})
1126
-
1127
- const query = useQuery({
1128
- ...${queryOptionsName}(${queryOptionsParamsCall}),
1129
- ...resolvedOptions,
1130
- queryKey
1131
- } as unknown as UseQueryOptions<${TData}, ${TError}, TData, ${TData}, TQueryKey>, toValue(queryClient)) as ${returnType}
1132
-
1133
- query.queryKey = queryKey as TQueryKey
1134
-
1135
- return query
1136
- `
1137
- })
1138
- });
1139
- }
1140
- //#endregion
1141
- Object.defineProperty(exports, "InfiniteQuery", {
1142
- enumerable: true,
1143
- get: function() {
1144
- return InfiniteQuery;
1145
- }
1146
- });
1147
- Object.defineProperty(exports, "InfiniteQueryOptions", {
1148
- enumerable: true,
1149
- get: function() {
1150
- return InfiniteQueryOptions;
1151
- }
1152
- });
1153
- Object.defineProperty(exports, "Mutation", {
1154
- enumerable: true,
1155
- get: function() {
1156
- return Mutation;
1157
- }
1158
- });
1159
- Object.defineProperty(exports, "MutationKey", {
1160
- enumerable: true,
1161
- get: function() {
1162
- return MutationKey;
1163
- }
1164
- });
1165
- Object.defineProperty(exports, "Query", {
1166
- enumerable: true,
1167
- get: function() {
1168
- return Query;
1169
- }
1170
- });
1171
- Object.defineProperty(exports, "QueryKey", {
1172
- enumerable: true,
1173
- get: function() {
1174
- return QueryKey;
1175
- }
1176
- });
1177
- Object.defineProperty(exports, "QueryOptions", {
1178
- enumerable: true,
1179
- get: function() {
1180
- return QueryOptions;
1181
- }
1182
- });
1183
- Object.defineProperty(exports, "__name", {
1184
- enumerable: true,
1185
- get: function() {
1186
- return __name;
1187
- }
1188
- });
1189
- Object.defineProperty(exports, "__toESM", {
1190
- enumerable: true,
1191
- get: function() {
1192
- return __toESM;
1193
- }
1194
- });
1195
- Object.defineProperty(exports, "camelCase", {
1196
- enumerable: true,
1197
- get: function() {
1198
- return camelCase;
1199
- }
1200
- });
1201
- Object.defineProperty(exports, "getOperationParameters", {
1202
- enumerable: true,
1203
- get: function() {
1204
- return getOperationParameters;
1205
- }
1206
- });
1207
- Object.defineProperty(exports, "mutationKeyTransformer", {
1208
- enumerable: true,
1209
- get: function() {
1210
- return mutationKeyTransformer;
1211
- }
1212
- });
1213
- Object.defineProperty(exports, "operationFileEntry", {
1214
- enumerable: true,
1215
- get: function() {
1216
- return operationFileEntry;
1217
- }
1218
- });
1219
- Object.defineProperty(exports, "queryKeyTransformer", {
1220
- enumerable: true,
1221
- get: function() {
1222
- return queryKeyTransformer;
1223
- }
1224
- });
1225
- Object.defineProperty(exports, "resolveOperationTypeNames", {
1226
- enumerable: true,
1227
- get: function() {
1228
- return resolveOperationTypeNames;
1229
- }
1230
- });
1231
- Object.defineProperty(exports, "resolveZodSchemaNames", {
1232
- enumerable: true,
1233
- get: function() {
1234
- return resolveZodSchemaNames;
1235
- }
1236
- });
1237
-
1238
- //# sourceMappingURL=components-CfU59l8V.cjs.map