@kubb/plugin-swr 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.
@@ -1,912 +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
- //#region ../../internals/utils/src/casing.ts
7
- /**
8
- * Shared implementation for camelCase and PascalCase conversion.
9
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
10
- * and capitalizes each word according to `pascal`.
11
- *
12
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
13
- */
14
- function toCamelOrPascal(text, pascal) {
15
- 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) => {
16
- if (word.length > 1 && word === word.toUpperCase()) return word;
17
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
18
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
19
- }
20
- /**
21
- * Converts `text` to camelCase.
22
- *
23
- * @example Word boundaries
24
- * `camelCase('hello-world') // 'helloWorld'`
25
- *
26
- * @example With a prefix
27
- * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
28
- */
29
- function camelCase(text, { prefix = "", suffix = "" } = {}) {
30
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
31
- }
32
- //#endregion
33
- //#region ../../internals/utils/src/reserved.ts
34
- /**
35
- * JavaScript and Java reserved words.
36
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
37
- */
38
- const reservedWords = new Set([
39
- "abstract",
40
- "arguments",
41
- "boolean",
42
- "break",
43
- "byte",
44
- "case",
45
- "catch",
46
- "char",
47
- "class",
48
- "const",
49
- "continue",
50
- "debugger",
51
- "default",
52
- "delete",
53
- "do",
54
- "double",
55
- "else",
56
- "enum",
57
- "eval",
58
- "export",
59
- "extends",
60
- "false",
61
- "final",
62
- "finally",
63
- "float",
64
- "for",
65
- "function",
66
- "goto",
67
- "if",
68
- "implements",
69
- "import",
70
- "in",
71
- "instanceof",
72
- "int",
73
- "interface",
74
- "let",
75
- "long",
76
- "native",
77
- "new",
78
- "null",
79
- "package",
80
- "private",
81
- "protected",
82
- "public",
83
- "return",
84
- "short",
85
- "static",
86
- "super",
87
- "switch",
88
- "synchronized",
89
- "this",
90
- "throw",
91
- "throws",
92
- "transient",
93
- "true",
94
- "try",
95
- "typeof",
96
- "var",
97
- "void",
98
- "volatile",
99
- "while",
100
- "with",
101
- "yield",
102
- "Array",
103
- "Date",
104
- "hasOwnProperty",
105
- "Infinity",
106
- "isFinite",
107
- "isNaN",
108
- "isPrototypeOf",
109
- "length",
110
- "Math",
111
- "name",
112
- "NaN",
113
- "Number",
114
- "Object",
115
- "prototype",
116
- "String",
117
- "toString",
118
- "undefined",
119
- "valueOf"
120
- ]);
121
- /**
122
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
123
- *
124
- * @example
125
- * ```ts
126
- * isValidVarName('status') // true
127
- * isValidVarName('class') // false (reserved word)
128
- * isValidVarName('42foo') // false (starts with digit)
129
- * ```
130
- */
131
- function isValidVarName(name) {
132
- if (!name || reservedWords.has(name)) return false;
133
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
134
- }
135
- //#endregion
136
- //#region ../../internals/utils/src/url.ts
137
- function transformParam(raw, casing) {
138
- const param = isValidVarName(raw) ? raw : camelCase(raw);
139
- return casing === "camelcase" ? camelCase(param) : param;
140
- }
141
- function toParamsObject(path, { replacer, casing } = {}) {
142
- const params = {};
143
- for (const match of path.matchAll(/\{([^}]+)\}/g)) {
144
- const param = transformParam(match[1], casing);
145
- const key = replacer ? replacer(param) : param;
146
- params[key] = key;
147
- }
148
- return Object.keys(params).length > 0 ? params : null;
149
- }
150
- /**
151
- * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.
152
- */
153
- var Url = class Url {
154
- /**
155
- * Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.
156
- *
157
- * @example
158
- * Url.canParse('https://petstore.swagger.io/v2') // true
159
- * Url.canParse('/pet/{petId}') // false
160
- */
161
- static canParse(url, base) {
162
- return URL.canParse(url, base);
163
- }
164
- /**
165
- * Converts an OpenAPI/Swagger path to Express-style colon syntax.
166
- *
167
- * @example
168
- * Url.toPath('/pet/{petId}') // '/pet/:petId'
169
- */
170
- static toPath(path) {
171
- return path.replace(/\{([^}]+)\}/g, ":$1");
172
- }
173
- /**
174
- * Converts an OpenAPI/Swagger path to a TypeScript template literal string.
175
- * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,
176
- * and `casing` controls parameter identifier casing.
177
- *
178
- * @example
179
- * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'
180
- *
181
- * @example
182
- * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'
183
- */
184
- static toTemplateString(path, { prefix, replacer, casing } = {}) {
185
- const result = path.split(/\{([^}]+)\}/).map((part, i) => {
186
- if (i % 2 === 0) return part;
187
- const param = transformParam(part, casing);
188
- return `\${${replacer ? replacer(param) : param}}`;
189
- }).join("");
190
- return `\`${prefix ?? ""}${result}\``;
191
- }
192
- /**
193
- * Returns the path and its extracted params as a structured `URLObject`, or as a stringified
194
- * expression when `stringify` is set.
195
- *
196
- * @example
197
- * Url.toObject('/pet/{petId}')
198
- * // { url: '/pet/:petId', params: { petId: 'petId' } }
199
- */
200
- static toObject(path, { type = "path", replacer, stringify, casing } = {}) {
201
- const object = {
202
- url: type === "path" ? Url.toPath(path) : Url.toTemplateString(path, {
203
- replacer,
204
- casing
205
- }),
206
- params: toParamsObject(path, {
207
- replacer,
208
- casing
209
- })
210
- };
211
- if (stringify) {
212
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
213
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
214
- return `{ url: '${object.url}' }`;
215
- }
216
- return object;
217
- }
218
- };
219
- //#endregion
220
- //#region ../../internals/shared/src/operation.ts
221
- function getOperationLink(node, link) {
222
- if (!link) return null;
223
- if (typeof link === "function") return link(node) ?? null;
224
- if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
225
- return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
226
- }
227
- function getContentTypeInfo(node) {
228
- const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
229
- const isMultipleContentTypes = contentTypes.length > 1;
230
- return {
231
- contentTypes,
232
- isMultipleContentTypes,
233
- contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
234
- defaultContentType: contentTypes[0] ?? "application/json",
235
- hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
236
- };
237
- }
238
- function buildRequestConfigType(node, resolver) {
239
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
240
- const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
241
- return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
242
- }
243
- function buildOperationComments(node, options = {}) {
244
- const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
245
- const linkComment = getOperationLink(node, link);
246
- const filteredComments = (linkPosition === "beforeDeprecated" ? [
247
- node.description && `@description ${node.description}`,
248
- node.summary && `@summary ${node.summary}`,
249
- linkComment,
250
- node.deprecated && "@deprecated"
251
- ] : [
252
- node.description && `@description ${node.description}`,
253
- node.summary && `@summary ${node.summary}`,
254
- node.deprecated && "@deprecated",
255
- linkComment
256
- ]).filter((comment) => Boolean(comment));
257
- if (!splitLines) return filteredComments;
258
- return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
259
- }
260
- function getOperationParameters(node, options = {}) {
261
- const params = ast.caseParams(node.parameters, options.paramsCasing);
262
- return {
263
- path: params.filter((param) => param.in === "path"),
264
- query: params.filter((param) => param.in === "query"),
265
- header: params.filter((param) => param.in === "header"),
266
- cookie: params.filter((param) => param.in === "cookie")
267
- };
268
- }
269
- function getStatusCodeNumber(statusCode) {
270
- const code = Number(statusCode);
271
- return Number.isNaN(code) ? null : code;
272
- }
273
- function isErrorStatusCode(statusCode) {
274
- const code = getStatusCodeNumber(statusCode);
275
- return code !== null && code >= 400;
276
- }
277
- function resolveErrorNames(node, resolver) {
278
- return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
279
- }
280
- function resolveStatusCodeNames(node, resolver) {
281
- return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
282
- }
283
- /**
284
- * Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
285
- * Each member is `{ status: N; data: StatusNType; statusText: string }`.
286
- */
287
- function buildStatusUnionType(node, resolver) {
288
- const members = node.responses.map((r) => {
289
- const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
290
- const statusCode = Number.parseInt(r.statusCode, 10);
291
- return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
292
- });
293
- if (members.length === 1) return members[0];
294
- return `(${members.join(" | ")})`;
295
- }
296
- const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
297
- function resolveOperationTypeNames(node, resolver, options = {}) {
298
- const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
299
- let byResolver = typeNamesByResolver.get(resolver);
300
- if (byResolver) {
301
- const cached = byResolver.get(cacheKey);
302
- if (cached) return cached;
303
- } else {
304
- byResolver = /* @__PURE__ */ new Map();
305
- typeNamesByResolver.set(resolver, byResolver);
306
- }
307
- const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
308
- const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
309
- const exclude = new Set(options.exclude ?? []);
310
- const paramNames = [
311
- ...path.map((param) => resolver.resolvePathParamsName(node, param)),
312
- ...query.map((param) => resolver.resolveQueryParamsName(node, param)),
313
- ...header.map((param) => resolver.resolveHeaderParamsName(node, param))
314
- ];
315
- const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
316
- const result = (options.order === "body-response-first" ? [
317
- ...bodyAndResponseNames,
318
- ...paramNames,
319
- ...responseStatusNames
320
- ] : [
321
- ...paramNames,
322
- ...bodyAndResponseNames,
323
- ...responseStatusNames
324
- ]).filter((name) => Boolean(name) && !exclude.has(name));
325
- byResolver.set(cacheKey, result);
326
- return result;
327
- }
328
- //#endregion
329
- //#region ../../internals/tanstack-query/src/components/MutationKey.tsx
330
- const declarationPrinter$4 = functionPrinter({ mode: "declaration" });
331
- const mutationKeyTransformer = ({ node }) => {
332
- if (!node.path) return [];
333
- return [`{ url: '${Url.toPath(node.path)}' }`];
334
- };
335
- function MutationKey$1({ name, paramsCasing, node, transformer }) {
336
- const paramsNode = ast.createFunctionParameters({ params: [] });
337
- const paramsSignature = declarationPrinter$4.print(paramsNode) ?? "";
338
- const keys = (transformer ?? mutationKeyTransformer)({
339
- node,
340
- casing: paramsCasing
341
- });
342
- return /* @__PURE__ */ jsx(File.Source, {
343
- name,
344
- isExportable: true,
345
- isIndexable: true,
346
- children: /* @__PURE__ */ jsx(Function.Arrow, {
347
- name,
348
- export: true,
349
- params: paramsSignature,
350
- singleLine: true,
351
- children: `[${keys.join(", ")}] as const`
352
- })
353
- });
354
- }
355
- __name(MutationKey$1, "MutationKey");
356
- //#endregion
357
- //#region ../../internals/tanstack-query/src/utils.ts
358
- /**
359
- * Builds the shared `(…params, config = {})` parameter list for a TanStack
360
- * query-options function. The trailing `config` parameter is typed as a partial
361
- * `RequestConfig` with an optional `client`. Framework plugins wrap the result
362
- * when needed, for example vue-query applies `MaybeRefOrGetter`.
363
- */
364
- function buildQueryOptionsParams(node, options) {
365
- const { paramsType, paramsCasing, pathParamsType, resolver } = options;
366
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
367
- return ast.createOperationParams(node, {
368
- paramsType,
369
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
370
- paramsCasing,
371
- resolver,
372
- extraParams: [ast.createFunctionParameter({
373
- name: "config",
374
- type: ast.createParamsType({
375
- variant: "reference",
376
- name: requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"
377
- }),
378
- default: "{}"
379
- })]
380
- });
381
- }
382
- /**
383
- * Returns `'zod'` when response-direction parsing is enabled.
384
- * The string shorthand `'zod'` also enables response parsing.
385
- */
386
- function resolveResponseParser(parser) {
387
- if (!parser) return null;
388
- if (parser === "zod") return "zod";
389
- return parser.response ?? null;
390
- }
391
- /**
392
- * Returns `'zod'` when request body parsing is enabled.
393
- * The string shorthand `'zod'` also enables request body parsing (existing behavior).
394
- */
395
- function resolveRequestParser(parser) {
396
- if (!parser) return null;
397
- if (parser === "zod") return "zod";
398
- return parser.request ?? null;
399
- }
400
- /**
401
- * Returns `'zod'` when query-params parsing is enabled.
402
- * Only the object form `{ request: 'zod' }` enables this. `parser: 'zod'` does not.
403
- */
404
- function resolveQueryParamsParser(parser) {
405
- if (!parser || parser === "zod") return null;
406
- return parser.request ?? null;
407
- }
408
- /**
409
- * Collects the Zod schema import names for an operation based on the active parser directions.
410
- *
411
- * - `parser: 'zod'`: response and request body names (backward-compatible behavior).
412
- * - `parser: { request: 'zod' }`: request body and query params names.
413
- * - `parser: { response: 'zod' }`: response name only.
414
- * - `parser: { request: 'zod', response: 'zod' }`: all three.
415
- *
416
- * Returns an empty array when no resolver is provided or `parser` is falsy.
417
- */
418
- function resolveZodSchemaNames(node, zodResolver, parser) {
419
- if (!zodResolver || !parser) return [];
420
- const { query: queryParams } = getOperationParameters(node);
421
- return [
422
- resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
423
- resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
424
- resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
425
- ].filter((n) => Boolean(n));
426
- }
427
- /**
428
- * Resolve the type for a single path parameter.
429
- *
430
- * - When the resolver's group name differs from the individual param name
431
- * (e.g. kubbV4) → `GroupName['paramName']` (member access).
432
- * - When they match (v5 default) → `TypeName` (direct reference).
433
- */
434
- function resolvePathParamType(node, param, resolver) {
435
- const individualName = resolver.resolveParamName(node, param);
436
- const groupName = resolver.resolvePathParamsName(node, param);
437
- if (groupName !== individualName) return ast.createParamsType({
438
- variant: "member",
439
- base: groupName,
440
- key: param.name
441
- });
442
- return ast.createParamsType({
443
- variant: "reference",
444
- name: individualName
445
- });
446
- }
447
- /**
448
- * Derive a query-params group type from the resolver.
449
- * Returns `null` when no query params exist or when the group name
450
- * equals the individual param name (no real group).
451
- */
452
- function resolveQueryGroupType(node, params, resolver) {
453
- if (!params.length) return null;
454
- const firstParam = params[0];
455
- const groupName = resolver.resolveQueryParamsName(node, firstParam);
456
- if (groupName === resolver.resolveParamName(node, firstParam)) return null;
457
- return {
458
- type: ast.createParamsType({
459
- variant: "reference",
460
- name: groupName
461
- }),
462
- optional: params.every((p) => !p.required)
463
- };
464
- }
465
- /**
466
- * Build a single `FunctionParameterNode` for a query or header group.
467
- */
468
- function buildGroupParam(name, node, params, groupType, resolver) {
469
- if (groupType) return [ast.createFunctionParameter({
470
- name,
471
- type: groupType.type,
472
- optional: groupType.optional
473
- })];
474
- if (params.length) {
475
- const structProps = params.map((p) => ({
476
- name: p.name,
477
- type: ast.createParamsType({
478
- variant: "reference",
479
- name: resolver.resolveParamName(node, p)
480
- }),
481
- optional: !p.required
482
- }));
483
- return [ast.createFunctionParameter({
484
- name,
485
- type: ast.createParamsType({
486
- variant: "struct",
487
- properties: structProps
488
- }),
489
- optional: params.every((p) => !p.required)
490
- })];
491
- }
492
- return [];
493
- }
494
- /**
495
- * Build QueryKey params: pathParams + data + queryParams (NO headers, NO config).
496
- */
497
- function buildQueryKeyParams(node, options) {
498
- const { pathParamsType, paramsCasing, resolver } = options;
499
- const casedParams = ast.caseParams(node.parameters, paramsCasing);
500
- const pathParams = casedParams.filter((p) => p.in === "path");
501
- const queryParams = casedParams.filter((p) => p.in === "query");
502
- const queryGroupType = resolveQueryGroupType(node, queryParams, resolver);
503
- const bodyType = node.requestBody?.content?.[0]?.schema ? ast.createParamsType({
504
- variant: "reference",
505
- name: resolver.resolveDataName(node)
506
- }) : null;
507
- const bodyRequired = node.requestBody?.required ?? false;
508
- const params = [];
509
- if (pathParams.length) {
510
- const pathChildren = pathParams.map((p) => ast.createFunctionParameter({
511
- name: p.name,
512
- type: resolvePathParamType(node, p, resolver),
513
- optional: !p.required
514
- }));
515
- params.push({
516
- kind: "ParameterGroup",
517
- properties: pathChildren,
518
- inline: pathParamsType === "inline",
519
- default: pathChildren.every((c) => c.optional) ? "{}" : void 0
520
- });
521
- }
522
- if (bodyType) params.push(ast.createFunctionParameter({
523
- name: "data",
524
- type: bodyType,
525
- optional: !bodyRequired
526
- }));
527
- params.push(...buildGroupParam("params", node, queryParams, queryGroupType, resolver));
528
- return ast.createFunctionParameters({ params });
529
- }
530
- /**
531
- * Collect the names of the required params (no default) that drive the `enabled`
532
- * guard. These are exactly the params that should be made optional in the
533
- * generated signatures so callers can pass `undefined` to reach the disabled state.
534
- */
535
- function getEnabledParamNames(paramsNode) {
536
- const required = [];
537
- for (const param of paramsNode.params) if ("kind" in param && param.kind === "ParameterGroup") {
538
- const group = param;
539
- for (const child of group.properties) if (!child.optional && child.default === void 0) required.push(child.name);
540
- } else {
541
- const fp = param;
542
- if (!fp.optional && fp.default === void 0) required.push(fp.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
- if ("kind" in param && param.kind === "ParameterGroup") {
559
- const group = param;
560
- return {
561
- ...group,
562
- properties: group.properties.map((child) => nameSet.has(child.name) ? ast.createFunctionParameter({
563
- name: child.name,
564
- type: child.type,
565
- rest: child.rest,
566
- optional: true
567
- }) : child)
568
- };
569
- }
570
- const fp = param;
571
- return nameSet.has(fp.name) ? ast.createFunctionParameter({
572
- name: fp.name,
573
- type: fp.type,
574
- rest: fp.rest,
575
- optional: true
576
- }) : fp;
577
- });
578
- return ast.createFunctionParameters({ params });
579
- }
580
- /**
581
- * Add a non-null assertion (`!`) to the named params inside a printed client-call
582
- * string. Bridges the type gap created by `markParamsOptional` while keeping the
583
- * runtime identical (the `!` is erased at compile time).
584
- *
585
- * Handles destructured shorthand groups (`{ petId }` → `{ petId: petId! }`) and
586
- * standalone identifiers (`params` → `params!`).
587
- */
588
- function injectNonNullAssertions(callStr, names) {
589
- if (names.length === 0) return callStr;
590
- const nameSet = new Set(names);
591
- let result = callStr.replace(/\{\s*([\w,\s]+)\s*\}(?=\s*,)/g, (match, inner) => {
592
- if (inner.includes(":") || inner.includes("...")) return match;
593
- const keys = inner.split(",").map((k) => k.trim()).filter(Boolean);
594
- if (!keys.some((k) => nameSet.has(k))) return match;
595
- return `{ ${keys.map((k) => nameSet.has(k) ? `${k}: ${k}!` : k).join(", ")} }`;
596
- });
597
- result = result.replace(/(?<![{.:?])\b(\w+)\b(?=\s*,)/g, (match, name) => nameSet.has(name) ? `${name}!` : match);
598
- return result;
599
- }
600
- //#endregion
601
- //#region ../../internals/tanstack-query/src/components/QueryKey.tsx
602
- const declarationPrinter$3 = functionPrinter({ mode: "declaration" });
603
- const queryKeyTransformer = ({ node, casing }) => {
604
- if (!node.path) return [];
605
- const hasQueryParams = getOperationParameters(node).query.length > 0;
606
- const hasRequestBody = !!node.requestBody?.content?.[0]?.schema;
607
- return [
608
- Url.toObject(node.path, {
609
- type: "path",
610
- stringify: true,
611
- casing
612
- }),
613
- hasQueryParams ? "...(params ? [params] : [])" : null,
614
- hasRequestBody ? "...(data ? [data] : [])" : null
615
- ].filter(Boolean);
616
- };
617
- function QueryKey({ name, node, tsResolver, paramsCasing, pathParamsType, typeName, transformer }) {
618
- const baseParamsNode = buildQueryKeyParams(node, {
619
- pathParamsType,
620
- paramsCasing,
621
- resolver: tsResolver
622
- });
623
- const paramsNode = markParamsOptional(baseParamsNode, getEnabledParamNames(baseParamsNode));
624
- const paramsSignature = declarationPrinter$3.print(paramsNode) ?? "";
625
- const keys = (transformer ?? queryKeyTransformer)({
626
- node,
627
- casing: paramsCasing
628
- });
629
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
630
- name,
631
- isExportable: true,
632
- isIndexable: true,
633
- children: /* @__PURE__ */ jsx(Function.Arrow, {
634
- name,
635
- export: true,
636
- params: paramsSignature,
637
- singleLine: true,
638
- children: `[${keys.join(", ")}] as const`
639
- })
640
- }), /* @__PURE__ */ jsx(File.Source, {
641
- name: typeName,
642
- isTypeOnly: true,
643
- children: /* @__PURE__ */ jsx(Type, {
644
- name: typeName,
645
- children: `ReturnType<typeof ${name}>`
646
- })
647
- })] });
648
- }
649
- //#endregion
650
- //#region src/components/Mutation.tsx
651
- const declarationPrinter$2 = functionPrinter({ mode: "declaration" });
652
- const callPrinter$2 = functionPrinter({ mode: "call" });
653
- const keysPrinter = functionPrinter({ mode: "keys" });
654
- function createMutationArgParams(node, options) {
655
- return ast.createOperationParams(node, {
656
- paramsType: "inline",
657
- pathParamsType: "inline",
658
- paramsCasing: options.paramsCasing,
659
- resolver: options.resolver
660
- });
661
- }
662
- function buildMutationParamsNode(node, options) {
663
- const { dataReturnType, mutationKeyTypeName, mutationArgTypeName, resolver } = options;
664
- const responseName = resolver.resolveResponseName(node);
665
- const errorNames = resolveErrorNames(node, resolver);
666
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
667
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
668
- return ast.createFunctionParameters({ params: [ast.createFunctionParameter({
669
- name: "options",
670
- type: ast.createParamsType({
671
- variant: "reference",
672
- name: `{
673
- mutation?: SWRMutationConfiguration<${TData}, ${TError}, ${mutationKeyTypeName} | null, ${mutationArgTypeName}> & { throwOnError?: boolean },
674
- client?: ${buildRequestConfigType(node, resolver)},
675
- shouldFetch?: boolean,
676
- }`
677
- }),
678
- default: "{}"
679
- })] });
680
- }
681
- function Mutation({ name, clientName, mutationKeyName, mutationKeyTypeName, mutationArgTypeName, paramsCasing, paramsType, pathParamsType, dataReturnType, node, tsResolver }) {
682
- const responseName = tsResolver.resolveResponseName(node);
683
- const errorNames = resolveErrorNames(node, tsResolver);
684
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver);
685
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
686
- const mutationArgParamsNode = createMutationArgParams(node, {
687
- paramsCasing,
688
- resolver: tsResolver
689
- });
690
- const hasMutationParams = mutationArgParamsNode.params.length > 0;
691
- const argTypeBody = hasMutationParams ? declarationPrinter$2.print(mutationArgParamsNode) ?? "" : "";
692
- const argKeysStr = hasMutationParams ? keysPrinter.print(mutationArgParamsNode) ?? "" : "";
693
- const generics = [
694
- TData,
695
- TError,
696
- `${mutationKeyTypeName} | null`,
697
- mutationArgTypeName
698
- ];
699
- const paramsNode = buildMutationParamsNode(node, {
700
- paramsCasing,
701
- dataReturnType,
702
- mutationKeyTypeName,
703
- mutationArgTypeName,
704
- resolver: tsResolver
705
- });
706
- const paramsSignature = declarationPrinter$2.print(paramsNode) ?? "";
707
- const clientCallParamsNode = ast.createOperationParams(node, {
708
- paramsType,
709
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
710
- paramsCasing,
711
- resolver: tsResolver,
712
- extraParams: [ast.createFunctionParameter({
713
- name: "config",
714
- type: ast.createParamsType({
715
- variant: "reference",
716
- name: buildRequestConfigType(node, tsResolver)
717
- }),
718
- default: "{}"
719
- })]
720
- });
721
- const clientCallStr = callPrinter$2.print(clientCallParamsNode) ?? "";
722
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Source, {
723
- name: mutationArgTypeName,
724
- isExportable: true,
725
- isIndexable: true,
726
- isTypeOnly: true,
727
- children: /* @__PURE__ */ jsx(Type, {
728
- name: mutationArgTypeName,
729
- export: true,
730
- children: hasMutationParams ? `{ ${argTypeBody} }` : "never"
731
- })
732
- }), /* @__PURE__ */ jsx(File.Source, {
733
- name,
734
- isExportable: true,
735
- isIndexable: true,
736
- children: /* @__PURE__ */ jsx(Function, {
737
- name,
738
- export: true,
739
- params: paramsSignature,
740
- JSDoc: { comments: buildOperationComments(node) },
741
- children: `
742
- const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
743
- const mutationKey = ${mutationKeyName}()
744
-
745
- return useSWRMutation<${generics.join(", ")}>(
746
- shouldFetch ? mutationKey : null,
747
- async (_url${hasMutationParams ? `, { arg: { ${argKeysStr} } }` : ""}) => {
748
- return ${clientName}(${clientCallStr})
749
- },
750
- mutationOptions
751
- )
752
- `
753
- })
754
- })] });
755
- }
756
- //#endregion
757
- //#region src/components/MutationKey.tsx
758
- function MutationKey({ name, typeName, node, paramsCasing, pathParamsType, transformer }) {
759
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(MutationKey$1, {
760
- name,
761
- node,
762
- paramsCasing,
763
- pathParamsType,
764
- transformer
765
- }), /* @__PURE__ */ jsx(File.Source, {
766
- name: typeName,
767
- isExportable: true,
768
- isIndexable: true,
769
- isTypeOnly: true,
770
- children: /* @__PURE__ */ jsx(Type, {
771
- export: true,
772
- name: typeName,
773
- children: `ReturnType<typeof ${name}>`
774
- })
775
- })] });
776
- }
777
- //#endregion
778
- //#region src/components/QueryOptions.tsx
779
- const declarationPrinter$1 = functionPrinter({ mode: "declaration" });
780
- const callPrinter$1 = functionPrinter({ mode: "call" });
781
- function getQueryOptionsParams(node, options) {
782
- return buildQueryOptionsParams(node, options);
783
- }
784
- function QueryOptions({ name, clientName, node, tsResolver, paramsCasing, paramsType, pathParamsType }) {
785
- const enabledNames = getEnabledParamNames(buildQueryKeyParams(node, {
786
- pathParamsType,
787
- paramsCasing,
788
- resolver: tsResolver
789
- }));
790
- const paramsNode = markParamsOptional(getQueryOptionsParams(node, {
791
- paramsType,
792
- paramsCasing,
793
- pathParamsType,
794
- resolver: tsResolver
795
- }), enabledNames);
796
- const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
797
- const clientCallStr = injectNonNullAssertions(callPrinter$1.print(paramsNode) ?? "", enabledNames);
798
- return /* @__PURE__ */ jsx(File.Source, {
799
- name,
800
- isExportable: true,
801
- isIndexable: true,
802
- children: /* @__PURE__ */ jsx(Function, {
803
- name,
804
- export: true,
805
- params: paramsSignature,
806
- children: `
807
- return {
808
- fetcher: async () => {
809
- return ${clientName}(${clientCallStr})
810
- },
811
- }
812
- `
813
- })
814
- });
815
- }
816
- //#endregion
817
- //#region src/components/Query.tsx
818
- const declarationPrinter = functionPrinter({ mode: "declaration" });
819
- const callPrinter = functionPrinter({ mode: "call" });
820
- function buildQueryParamsNode(node, options) {
821
- const { paramsType, paramsCasing, pathParamsType, dataReturnType, resolver } = options;
822
- const responseName = resolver.resolveResponseName(node);
823
- const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : void 0;
824
- const errorNames = resolveErrorNames(node, resolver);
825
- const TData = dataReturnType === "data" ? responseName : buildStatusUnionType(node, resolver);
826
- const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
827
- const optionsParam = ast.createFunctionParameter({
828
- name: "options",
829
- type: ast.createParamsType({
830
- variant: "reference",
831
- name: `{
832
- query?: SWRConfiguration<${[TData, TError].join(", ")}>,
833
- client?: ${requestName ? `Partial<RequestConfig<${requestName}>> & { client?: Client }` : "Partial<RequestConfig> & { client?: Client }"},
834
- shouldFetch?: boolean,
835
- immutable?: boolean
836
- }`
837
- }),
838
- default: "{}"
839
- });
840
- return ast.createOperationParams(node, {
841
- paramsType,
842
- pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
843
- paramsCasing,
844
- resolver,
845
- extraParams: [optionsParam]
846
- });
847
- }
848
- function Query({ name, queryKeyTypeName, queryOptionsName, queryKeyName, paramsType, paramsCasing, pathParamsType, dataReturnType, node, tsResolver }) {
849
- const responseName = tsResolver.resolveResponseName(node);
850
- const errorNames = resolveErrorNames(node, tsResolver);
851
- const generics = [
852
- dataReturnType === "data" ? responseName : buildStatusUnionType(node, tsResolver),
853
- `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`,
854
- `${queryKeyTypeName} | null`
855
- ];
856
- const queryKeyParamsNode = buildQueryKeyParams(node, {
857
- pathParamsType,
858
- paramsCasing,
859
- resolver: tsResolver
860
- });
861
- const queryKeyParamsCall = callPrinter.print(queryKeyParamsNode) ?? "";
862
- const enabledNames = getEnabledParamNames(queryKeyParamsNode);
863
- const queryOptionsParamsNode = getQueryOptionsParams(node, {
864
- paramsType,
865
- paramsCasing,
866
- pathParamsType,
867
- resolver: tsResolver
868
- });
869
- const queryOptionsParamsCall = callPrinter.print(queryOptionsParamsNode) ?? "";
870
- const paramsNode = markParamsOptional(buildQueryParamsNode(node, {
871
- paramsType,
872
- paramsCasing,
873
- pathParamsType,
874
- dataReturnType,
875
- resolver: tsResolver
876
- }), enabledNames);
877
- const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
878
- const shouldFetchExpr = enabledNames.length ? `shouldFetch && !!(${enabledNames.join(" && ")})` : "shouldFetch";
879
- return /* @__PURE__ */ jsx(File.Source, {
880
- name,
881
- isExportable: true,
882
- isIndexable: true,
883
- children: /* @__PURE__ */ jsx(Function, {
884
- name,
885
- export: true,
886
- params: paramsSignature,
887
- JSDoc: { comments: buildOperationComments(node) },
888
- children: `
889
- const { query: queryOptions, client: config = {}, shouldFetch = true, immutable } = options ?? {}
890
-
891
- const queryKey = ${queryKeyName}(${queryKeyParamsCall})
892
-
893
- return useSWR<${generics.join(", ")}>(
894
- ${shouldFetchExpr} ? queryKey : null,
895
- {
896
- ...${queryOptionsName}(${queryOptionsParamsCall}),
897
- ...(immutable ? {
898
- revalidateIfStale: false,
899
- revalidateOnFocus: false,
900
- revalidateOnReconnect: false
901
- } : { }),
902
- ...queryOptions,
903
- }
904
- )
905
- `
906
- })
907
- });
908
- }
909
- //#endregion
910
- 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 };
911
-
912
- //# sourceMappingURL=components-CR9NLFcO.js.map