@kubb/plugin-swr 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,851 +0,0 @@
1
- import { t as __name } from "./chunk-C0LytTxp.js";
2
- import { ast } from "@kubb/core";
3
- import { buildGroupParam, caseParams, createOperationParams, resolveGroupType, resolveParamType } from "@kubb/ast/utils";
4
- import { functionPrinter } from "@kubb/plugin-ts";
5
- import { File, Function, Type } from "@kubb/renderer-jsx";
6
- import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
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
- function getOperationLink(node, link) {
223
- if (!link) return null;
224
- if (typeof link === "function") return link(node) ?? null;
225
- if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
226
- return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
227
- }
228
- function getContentTypeInfo(node) {
229
- const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
230
- const isMultipleContentTypes = contentTypes.length > 1;
231
- return {
232
- contentTypes,
233
- isMultipleContentTypes,
234
- contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
235
- defaultContentType: contentTypes[0] ?? "application/json",
236
- hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
237
- };
238
- }
239
- function buildRequestConfigType(node, resolver) {
240
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
241
- const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
242
- return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
243
- }
244
- function buildOperationComments(node, options = {}) {
245
- const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
246
- const linkComment = getOperationLink(node, link);
247
- const filteredComments = (linkPosition === "beforeDeprecated" ? [
248
- node.description && `@description ${node.description}`,
249
- node.summary && `@summary ${node.summary}`,
250
- linkComment,
251
- node.deprecated && "@deprecated"
252
- ] : [
253
- node.description && `@description ${node.description}`,
254
- node.summary && `@summary ${node.summary}`,
255
- node.deprecated && "@deprecated",
256
- linkComment
257
- ]).filter((comment) => Boolean(comment));
258
- if (!splitLines) return filteredComments;
259
- return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
260
- }
261
- function getOperationParameters(node, options = {}) {
262
- const params = caseParams(node.parameters, options.paramsCasing);
263
- return {
264
- path: params.filter((param) => param.in === "path"),
265
- query: params.filter((param) => param.in === "query"),
266
- header: params.filter((param) => param.in === "header"),
267
- cookie: params.filter((param) => param.in === "cookie")
268
- };
269
- }
270
- function getStatusCodeNumber(statusCode) {
271
- const code = Number(statusCode);
272
- return Number.isNaN(code) ? null : code;
273
- }
274
- function isErrorStatusCode(statusCode) {
275
- const code = getStatusCodeNumber(statusCode);
276
- return code !== null && code >= 400;
277
- }
278
- function resolveErrorNames(node, resolver) {
279
- return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
280
- }
281
- function resolveStatusCodeNames(node, resolver) {
282
- return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
283
- }
284
- /**
285
- * Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
286
- * Each member is `{ status: N; data: StatusNType; statusText: string }`.
287
- */
288
- function buildStatusUnionType(node, resolver) {
289
- const members = node.responses.map((r) => {
290
- const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
291
- const statusCode = Number.parseInt(r.statusCode, 10);
292
- return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
293
- });
294
- if (members.length === 1) return members[0];
295
- return `(${members.join(" | ")})`;
296
- }
297
- const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
298
- function resolveOperationTypeNames(node, resolver, options = {}) {
299
- const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
300
- let byResolver = typeNamesByResolver.get(resolver);
301
- if (byResolver) {
302
- const cached = byResolver.get(cacheKey);
303
- if (cached) return cached;
304
- } else {
305
- byResolver = /* @__PURE__ */ new Map();
306
- typeNamesByResolver.set(resolver, byResolver);
307
- }
308
- const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
309
- const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
310
- const exclude = new Set(options.exclude ?? []);
311
- const paramNames = [
312
- ...path.map((param) => resolver.resolvePathParamsName(node, param)),
313
- ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
314
- ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
315
- ];
316
- const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
317
- const result = (options.order === "body-response-first" ? [
318
- ...bodyAndResponseNames,
319
- ...paramNames,
320
- ...responseStatusNames
321
- ] : [
322
- ...paramNames,
323
- ...bodyAndResponseNames,
324
- ...responseStatusNames
325
- ]).filter((name) => Boolean(name) && !exclude.has(name));
326
- byResolver.set(cacheKey, result);
327
- return result;
328
- }
329
- //#endregion
330
- //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
331
- const declarationPrinter$4 = functionPrinter({ mode: "declaration" });
332
- const mutationKeyTransformer = ({ node }) => {
333
- if (!node.path) return [];
334
- return [`{ url: '${Url.toPath(node.path)}' }`];
335
- };
336
- function MutationKey$1({ name, paramsCasing, node, transformer }) {
337
- const paramsNode = ast.factory.createFunctionParameters({ params: [] });
338
- const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
339
- const keys = (transformer ?? mutationKeyTransformer)({
340
- node,
341
- casing: paramsCasing
342
- });
343
- return /* @__PURE__ */ jsx(File.Source, {
344
- name,
345
- isExportable: true,
346
- isIndexable: true,
347
- children: /* @__PURE__ */ jsx(Function.Arrow, {
348
- name,
349
- export: true,
350
- params: paramsSignature,
351
- singleLine: true,
352
- children: `[${keys.join(", ")}] as const`
353
- })
354
- });
355
- }
356
- __name(MutationKey$1, "MutationKey");
357
- //#endregion
358
- //#region ../../internals/tanstack-query/src/utils.ts
359
- /**
360
- * Returns the `TypeLiteral` members of a destructured group parameter, or `null`
361
- * for a plain named parameter.
362
- */
363
- function groupMembers(param) {
364
- if (typeof param.name === "string") return null;
365
- return param.type && typeof param.type !== "string" && param.type.kind === "TypeLiteral" ? param.type.members : [];
366
- }
367
- /**
368
- * Builds the shared `(…params, config = {})` parameter list for a TanStack
369
- * query-options function. The trailing `config` parameter is typed as a partial
370
- * `RequestConfig` with an optional `client`. Framework plugins wrap the result
371
- * when needed, for example vue-query applies `MaybeRefOrGetter`.
372
- */
373
- function buildQueryOptionsParams(node, options) {
374
- const { paramsType, paramsCasing, pathParamsType, resolver } = options;
375
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
376
- return createOperationParams(node, {
377
- paramsType,
378
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
379
- paramsCasing,
380
- resolver,
381
- extraParams: [ast.factory.createFunctionParameter({
382
- name: "config",
383
- type: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }",
384
- default: "{}"
385
- })]
386
- });
387
- }
388
- /**
389
- * Returns `'zod'` when response-direction parsing is enabled.
390
- * The string shorthand `'zod'` also enables response parsing.
391
- */
392
- function resolveResponseParser(parser) {
393
- if (!parser) return null;
394
- if (parser === "zod") return "zod";
395
- return parser.response ?? null;
396
- }
397
- /**
398
- * Returns `'zod'` when request body parsing is enabled.
399
- * The string shorthand `'zod'` also enables request body parsing (existing behavior).
400
- */
401
- function resolveRequestParser(parser) {
402
- if (!parser) return null;
403
- if (parser === "zod") return "zod";
404
- return parser.request ?? null;
405
- }
406
- /**
407
- * Returns `'zod'` when query-params parsing is enabled.
408
- * Only the object form `{ request: 'zod' }` enables this. `parser: 'zod'` does not.
409
- */
410
- function resolveQueryParamsParser(parser) {
411
- if (!parser || parser === "zod") return null;
412
- return parser.request ?? null;
413
- }
414
- /**
415
- * Collects the Zod schema import names for an operation based on the active parser directions.
416
- *
417
- * - `parser: 'zod'`: response and request body names (backward-compatible behavior).
418
- * - `parser: { request: 'zod' }`: request body and query params names.
419
- * - `parser: { response: 'zod' }`: response name only.
420
- * - `parser: { request: 'zod', response: 'zod' }`: all three.
421
- *
422
- * Returns an empty array when no resolver is provided or `parser` is falsy.
423
- */
424
- function resolveZodSchemaNames(node, zodResolver, parser) {
425
- if (!zodResolver || !parser) return [];
426
- const { query: queryParams } = getOperationParameters(node);
427
- return [
428
- resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
429
- resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
430
- resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
431
- ].filter((n) => Boolean(n));
432
- }
433
- /**
434
- * Build QueryKey params: pathParams + data + queryParams (NO headers, NO config).
435
- */
436
- function buildQueryKeyParams(node, options) {
437
- const { pathParamsType, paramsCasing, resolver } = options;
438
- const casedParams = caseParams(node.parameters, paramsCasing);
439
- const pathParams = casedParams.filter((p) => p.in === "path");
440
- const queryParams = casedParams.filter((p) => p.in === "query");
441
- const queryGroupType = resolveGroupType({
442
- node,
443
- params: queryParams,
444
- group: "query",
445
- resolver
446
- });
447
- const bodyType = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
448
- const bodyRequired = node.requestBody?.required ?? false;
449
- const params = [];
450
- if (pathParams.length) {
451
- const pathChildren = pathParams.map((p) => ({
452
- name: p.name,
453
- type: resolveParamType({
454
- node,
455
- param: p,
456
- resolver
457
- }),
458
- optional: !p.required
459
- }));
460
- if (pathParamsType === "object") params.push(ast.factory.createFunctionParameter({
461
- properties: pathChildren,
462
- default: pathChildren.every((c) => c.optional) ? "{}" : void 0
463
- }));
464
- else params.push(...pathChildren.map((child) => ast.factory.createFunctionParameter(child)));
465
- }
466
- if (bodyType) params.push(ast.factory.createFunctionParameter({
467
- name: "data",
468
- type: bodyType,
469
- optional: !bodyRequired
470
- }));
471
- params.push(...buildGroupParam({
472
- name: "params",
473
- node,
474
- params: queryParams,
475
- groupType: queryGroupType,
476
- resolver,
477
- wrapType: (type) => type
478
- }));
479
- return ast.factory.createFunctionParameters({ params });
480
- }
481
- /**
482
- * Collect the names of the required params (no default) that drive the `enabled`
483
- * guard. These are exactly the params that should be made optional in the
484
- * generated signatures so callers can pass `undefined` to reach the disabled state.
485
- */
486
- function getEnabledParamNames(paramsNode) {
487
- const required = [];
488
- for (const param of paramsNode.params) {
489
- const members = groupMembers(param);
490
- if (members) {
491
- for (const member of members) if (!member.optional) required.push(member.name);
492
- } else if (typeof param.name === "string" && !param.optional && param.default === void 0) required.push(param.name);
493
- }
494
- return required;
495
- }
496
- /**
497
- * Return a copy of `paramsNode` with the named params marked optional.
498
- *
499
- * Used to align signatures with the `enabled` guard: the guard already disables
500
- * the query while a param is falsy, so the param should accept `undefined`. The
501
- * change is type-only — the `queryFn` keeps calling the client with a non-null
502
- * assertion (see `injectNonNullAssertions`), so the emitted runtime is unchanged.
503
- */
504
- function markParamsOptional(paramsNode, names) {
505
- if (names.length === 0) return paramsNode;
506
- const nameSet = new Set(names);
507
- const params = paramsNode.params.map((param) => {
508
- const members = groupMembers(param);
509
- if (members) {
510
- const next = members.map((member) => nameSet.has(member.name) ? {
511
- ...member,
512
- optional: true
513
- } : member);
514
- return {
515
- ...param,
516
- type: ast.factory.createTypeLiteral({ members: next })
517
- };
518
- }
519
- return typeof param.name === "string" && nameSet.has(param.name) ? ast.factory.createFunctionParameter({
520
- name: param.name,
521
- type: param.type,
522
- rest: param.rest,
523
- optional: true
524
- }) : param;
525
- });
526
- return ast.factory.createFunctionParameters({ params });
527
- }
528
- /**
529
- * Add a non-null assertion (`!`) to the named params inside a printed client-call
530
- * string. Bridges the type gap created by `markParamsOptional` while keeping the
531
- * runtime identical (the `!` is erased at compile time).
532
- *
533
- * Handles destructured shorthand groups (`{ petId }` → `{ petId: petId! }`) and
534
- * standalone identifiers (`params` → `params!`).
535
- */
536
- function injectNonNullAssertions(callStr, names) {
537
- if (names.length === 0) return callStr;
538
- const nameSet = new Set(names);
539
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
540
- if (inner.includes(":") || inner.includes("...")) return match;
541
- const keys = inner.split(",").map((k) => k.trim()).filter(Boolean);
542
- if (!keys.some((k) => nameSet.has(k))) return match;
543
- return `{ ${keys.map((k) => nameSet.has(k) ? `${k}: ${k}!` : k).join(", ")} }`;
544
- });
545
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => nameSet.has(name) ? `${name}!` : match);
546
- return result;
547
- }
548
- //#endregion
549
- //#region ../../internals/tanstack-query/src/components/QueryKey.tsx
550
- const declarationPrinter$3 = functionPrinter({ mode: "declaration" });
551
- const queryKeyTransformer = ({ node, casing }) => {
552
- if (!node.path) return [];
553
- const hasQueryParams = getOperationParameters(node).query.length > 0;
554
- const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
555
- return [
556
- Url.toObject(node.path, {
557
- type: "path",
558
- stringify: true,
559
- casing
560
- }),
561
- hasQueryParams ? "...(params ? [params] : [])" : null,
562
- hasRequestBody ? "...(data ? [data] : [])" : null
563
- ].filter(Boolean);
564
- };
565
- function QueryKey({ name, node, tsResolver, paramsCasing, pathParamsType, typeName, transformer }) {
566
- const baseParamsNode = buildQueryKeyParams(node, {
567
- pathParamsType,
568
- paramsCasing,
569
- resolver: tsResolver
570
- });
571
- const paramsNode = markParamsOptional(baseParamsNode, getEnabledParamNames(baseParamsNode));
572
- const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
573
- const keys = (transformer ?? queryKeyTransformer)({
574
- node,
575
- casing: paramsCasing
576
- });
577
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
578
- name,
579
- isExportable: true,
580
- isIndexable: true,
581
- children: /* @__PURE__ */ jsx(Function.Arrow, {
582
- name,
583
- export: true,
584
- params: paramsSignature,
585
- singleLine: true,
586
- children: `[${keys.join(", ")}] as const`
587
- })
588
- }), /* @__PURE__ */ jsx(File.Source, {
589
- name: typeName,
590
- isTypeOnly: true,
591
- children: /* @__PURE__ */ jsx(Type, {
592
- name: typeName,
593
- children: `ReturnType<typeof ${name}>`
594
- })
595
- })] });
596
- }
597
- //#endregion
598
- //#region src/components/Mutation.tsx
599
- const declarationPrinter$2 = functionPrinter({ mode: "declaration" });
600
- const callPrinter$2 = functionPrinter({ mode: "call" });
601
- const keysPrinter = functionPrinter({ mode: "call" });
602
- function createMutationArgParams(node, options) {
603
- return createOperationParams(node, {
604
- paramsType: "inline",
605
- pathParamsType: "inline",
606
- paramsCasing: options.paramsCasing,
607
- resolver: options.resolver
608
- });
609
- }
610
- function buildMutationParamsNode(node, options) {
611
- const { dataReturnType, mutationKeyTypeName, mutationArgTypeName, resolver } = options;
612
- const responseName = resolver.resolveResponseName(node);
613
- const errorNames = resolveErrorNames(node, resolver);
614
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
615
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
616
- return ast.factory.createFunctionParameters({ params: [ast.factory.createFunctionParameter({
617
- name: "options",
618
- type: `{
619
- mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${mutationArgTypeName}> & { throwOnError?: boolean },
620
- client?: ${buildRequestConfigType(node, resolver)},
621
- shouldFetch?: boolean,
622
- }`,
623
- default: "{}"
624
- })] });
625
- }
626
- function Mutation({ name, clientName, mutationKeyName, mutationKeyTypeName, mutationArgTypeName, paramsCasing, paramsType, pathParamsType, dataReturnType, node, tsResolver }) {
627
- const responseName = tsResolver.resolveResponseName(node);
628
- const errorNames = resolveErrorNames(node, tsResolver);
629
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
630
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
631
- const mutationArgParamsNode = createMutationArgParams(node, {
632
- paramsCasing,
633
- resolver: tsResolver
634
- });
635
- const hasMutationParams = mutationArgParamsNode.params.length > 0;
636
- const argTypeBody = hasMutationParams ? declarationPrinter$2.print(mutationArgParamsNode) ?? "" : "";
637
- const argKeysStr = hasMutationParams ? keysPrinter.print(mutationArgParamsNode) ?? "" : "";
638
- const generics = [
639
- TData,
640
- TError,
641
- `${mutationKeyTypeName} | null`,
642
- mutationArgTypeName
643
- ];
644
- const paramsNode = buildMutationParamsNode(node, {
645
- paramsCasing,
646
- dataReturnType,
647
- mutationKeyTypeName,
648
- mutationArgTypeName,
649
- resolver: tsResolver
650
- });
651
- const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
652
- const clientCallParamsNode = createOperationParams(node, {
653
- paramsType,
654
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
655
- paramsCasing,
656
- resolver: tsResolver,
657
- extraParams: [ast.factory.createFunctionParameter({
658
- name: "config",
659
- type: buildRequestConfigType(node, tsResolver),
660
- default: "{}"
661
- })]
662
- });
663
- const clientCallStr = callPrinter$2.print(clientCallParamsNode) ?? "";
664
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
665
- name: mutationArgTypeName,
666
- isExportable: true,
667
- isIndexable: true,
668
- isTypeOnly: true,
669
- children: /* @__PURE__ */ jsx(Type, {
670
- name: mutationArgTypeName,
671
- export: true,
672
- children: hasMutationParams ? `{ ${argTypeBody} }` : "never"
673
- })
674
- }), /* @__PURE__ */ jsx(File.Source, {
675
- name,
676
- isExportable: true,
677
- isIndexable: true,
678
- children: /* @__PURE__ */ jsx(Function, {
679
- name,
680
- export: true,
681
- params: paramsSignature,
682
- JSDoc: { comments: buildOperationComments(node) },
683
- children: `
684
- const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
685
- const mutationKey = ${mutationKeyName}()
686
-
687
- return useSWRMutation<${generics.join(", ")}>(
688
- shouldFetch ? mutationKey : null,
689
- async (_url${hasMutationParams ? `, { arg: { ${argKeysStr} } }` : ""}) => {
690
- return ${clientName}(${clientCallStr})
691
- },
692
- mutationOptions
693
- )
694
- `
695
- })
696
- })] });
697
- }
698
- //#endregion
699
- //#region src/components/MutationKey.tsx
700
- function MutationKey({ name, typeName, node, paramsCasing, pathParamsType, transformer }) {
701
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(MutationKey$1, {
702
- name,
703
- node,
704
- paramsCasing,
705
- pathParamsType,
706
- transformer
707
- }), /* @__PURE__ */ jsx(File.Source, {
708
- name: typeName,
709
- isExportable: true,
710
- isIndexable: true,
711
- isTypeOnly: true,
712
- children: /* @__PURE__ */ jsx(Type, {
713
- export: true,
714
- name: typeName,
715
- children: `ReturnType<typeof ${name}>`
716
- })
717
- })] });
718
- }
719
- //#endregion
720
- //#region src/components/QueryOptions.tsx
721
- const declarationPrinter$1 = functionPrinter({ mode: "declaration" });
722
- const callPrinter$1 = functionPrinter({ mode: "call" });
723
- function getQueryOptionsParams(node, options) {
724
- return buildQueryOptionsParams(node, options);
725
- }
726
- function QueryOptions({ name, clientName, node, tsResolver, paramsCasing, paramsType, pathParamsType }) {
727
- const enabledNames = getEnabledParamNames(buildQueryKeyParams(node, {
728
- pathParamsType,
729
- paramsCasing,
730
- resolver: tsResolver
731
- }));
732
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
733
- paramsType,
734
- paramsCasing,
735
- pathParamsType,
736
- resolver: tsResolver
737
- }), enabledNames);
738
- const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
739
- const clientCallStr = injectNonNullAssertions(callPrinter$1.print(paramsNode) ?? "", enabledNames);
740
- return /* @__PURE__ */ jsx(File.Source, {
741
- name,
742
- isExportable: true,
743
- isIndexable: true,
744
- children: /* @__PURE__ */ jsx(Function, {
745
- name,
746
- export: true,
747
- params: paramsSignature,
748
- children: `
749
- return {
750
- fetcher: async () => {
751
- return ${clientName}(${clientCallStr})
752
- },
753
- }
754
- `
755
- })
756
- });
757
- }
758
- //#endregion
759
- //#region src/components/Query.tsx
760
- const declarationPrinter = functionPrinter({ mode: "declaration" });
761
- const callPrinter = functionPrinter({ mode: "call" });
762
- function buildQueryParamsNode(node, options) {
763
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
764
- const responseName = resolver.resolveResponseName(node);
765
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
766
- const errorNames = resolveErrorNames(node, resolver);
767
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
768
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
769
- const optionsParam = ast.factory.createFunctionParameter({
770
- name: "options",
771
- type: `{
772
- query?: SWRConfiguration<${[TData, TError].join(", ")}>,
773
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"},
774
- shouldFetch?: boolean,
775
- immutable?: boolean
776
- }`,
777
- default: "{}"
778
- });
779
- return createOperationParams(node, {
780
- paramsType,
781
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
782
- paramsCasing,
783
- resolver,
784
- extraParams: [optionsParam]
785
- });
786
- }
787
- function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
788
- const responseName = tsResolver.resolveResponseName(node);
789
- const errorNames = resolveErrorNames(node, tsResolver);
790
- const generics = [
791
- dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver),
792
- `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`,
793
- `${queryKeyTypeName} | null`
794
- ];
795
- const queryKeyParamsNode = buildQueryKeyParams(node, {
796
- pathParamsType,
797
- paramsCasing,
798
- resolver: tsResolver
799
- });
800
- const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
801
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
802
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
803
- paramsType,
804
- paramsCasing,
805
- pathParamsType,
806
- resolver: tsResolver
807
- });
808
- const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
809
- const paramsNode = markParamsOptional(buildQueryParamsNode(node, {
810
- paramsType,
811
- paramsCasing,
812
- pathParamsType,
813
- dataReturnType,
814
- resolver: tsResolver
815
- }), enabledNames);
816
- const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
817
- const shouldFetchExpr = enabledNames.length ? `shouldFetch && !!(${enabledNames.join(" && ")})` : "shouldFetch";
818
- return /* @__PURE__ */ jsx(File.Source, {
819
- name,
820
- isExportable: true,
821
- isIndexable: true,
822
- children: /* @__PURE__ */ jsx(Function, {
823
- name,
824
- export: true,
825
- params: paramsSignature,
826
- JSDoc: { comments: buildOperationComments(node) },
827
- children: `
828
- const { query: queryOptions, client: config = {}, shouldFetch = true, immutable } = options ?? {}
829
-
830
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
831
-
832
- return useSWR<${generics.join(", ")}>(
833
- ${shouldFetchExpr} ? queryKey : null,
834
- {
835
- ...${queryOptionsName}(${queryOptionsParamsCall}),
836
- ...(immutable ? {
837
- revalidateIfStale: false,
838
- revalidateOnFocus: false,
839
- revalidateOnReconnect: false
840
- } : { }),
841
- ...queryOptions,
842
- }
843
- )
844
- `
845
- })
846
- });
847
- }
848
- //#endregion
849
- export { QueryKey as a, mutationKeyTransformer as c, Mutation as i, resolveOperationTypeNames as l, QueryOptions as n, queryKeyTransformer as o, MutationKey as r, resolveZodSchemaNames as s, Query as t, camelCase as u };
850
-
851
- //# sourceMappingURL=components-mWBRE6E4.js.map