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