@kubb/plugin-fetch 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.
- package/README.md +70 -0
- package/dist/index.cjs +1260 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +211 -0
- package/dist/index.js +1231 -0
- package/dist/index.js.map +1 -0
- package/dist/rolldown-runtime-C0LytTxp.js +8 -0
- package/package.json +82 -0
- package/src/generators/clientGenerator.tsx +90 -0
- package/src/index.ts +3 -0
- package/src/plugin.ts +95 -0
- package/src/templates.ts +8 -0
- package/src/types.ts +19 -0
- package/templates/fetch.ts +578 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
import "./rolldown-runtime-C0LytTxp.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ast, defineGenerator, definePlugin, defineResolver } from "@kubb/core";
|
|
4
|
+
import { File, Function, jsxRenderer } from "@kubb/renderer-jsx";
|
|
5
|
+
import { createFunctionParameter, createFunctionParameters, functionPrinter, pluginTsName } from "@kubb/plugin-ts";
|
|
6
|
+
import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
|
|
7
|
+
import { pluginZodName } from "@kubb/plugin-zod";
|
|
8
|
+
import { buildJSDoc } from "@kubb/ast/utils";
|
|
9
|
+
import { macroSimplifyUnion } from "@kubb/ast/macros";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
//#region ../../internals/client/src/builders/parser.ts
|
|
12
|
+
/**
|
|
13
|
+
* Returns `true` when any direction of the parser uses zod (used for dependency checks).
|
|
14
|
+
*/
|
|
15
|
+
function isParserEnabled(parser) {
|
|
16
|
+
if (!parser) return false;
|
|
17
|
+
if (parser === "zod") return true;
|
|
18
|
+
return Boolean(parser.request || parser.response);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Returns `'zod'` when request body parsing is enabled, `null` otherwise. The string shorthand
|
|
22
|
+
* `'zod'` validates the response only, so it does not enable request parsing.
|
|
23
|
+
*/
|
|
24
|
+
function resolveRequestParser(parser) {
|
|
25
|
+
if (!parser || parser === "zod") return null;
|
|
26
|
+
return parser.request ?? null;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Returns `'zod'` when query-parameters parsing is enabled, `null` otherwise. Only the object form
|
|
30
|
+
* `{ request: 'zod' }` enables it.
|
|
31
|
+
*/
|
|
32
|
+
function resolveQueryParamsParser(parser) {
|
|
33
|
+
if (!parser || parser === "zod") return null;
|
|
34
|
+
return parser.request ?? null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns `'zod'` when response parsing is enabled, `null` otherwise. The string shorthand `'zod'`
|
|
38
|
+
* maps to response parsing.
|
|
39
|
+
*/
|
|
40
|
+
function resolveResponseParser(parser) {
|
|
41
|
+
if (!parser) return null;
|
|
42
|
+
if (parser === "zod") return "zod";
|
|
43
|
+
return parser.response ?? null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Resolves the zod expression a generated client validates a success response with. Only success
|
|
47
|
+
* (2xx) bodies reach the parse under the throw-on-error contract, so the success-only
|
|
48
|
+
* `<operation>ResponseSchema` is used; error bodies are never zod-parsed.
|
|
49
|
+
*/
|
|
50
|
+
function buildZodResponseParse(node, zodResolver) {
|
|
51
|
+
const name = zodResolver.resolveResponseName?.(node);
|
|
52
|
+
return name ? {
|
|
53
|
+
expression: name,
|
|
54
|
+
importNames: [name]
|
|
55
|
+
} : null;
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region ../../internals/client/src/builders/security.ts
|
|
59
|
+
function serializeAuth(auth) {
|
|
60
|
+
const parts = [`type: '${auth.type}'`];
|
|
61
|
+
if (auth.scheme) parts.push(`scheme: '${auth.scheme}'`);
|
|
62
|
+
if (auth.name) parts.push(`name: '${auth.name}'`);
|
|
63
|
+
if (auth.in) parts.push(`in: '${auth.in}'`);
|
|
64
|
+
return `{ ${parts.join(", ")} }`;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Maps an OpenAPI security scheme to the inline `Auth` object, or `null` when the runtime cannot
|
|
68
|
+
* place it (an unresolved `$ref`, or an `apiKey` without a name or outside `header` / `query` /
|
|
69
|
+
* `cookie`). `http` schemes other than `basic` are treated as bearer.
|
|
70
|
+
*/
|
|
71
|
+
function resolveSecurityScheme(scheme) {
|
|
72
|
+
if (!scheme || "$ref" in scheme) return null;
|
|
73
|
+
if (scheme.type === "apiKey") {
|
|
74
|
+
if (!scheme.name || scheme.in !== "header" && scheme.in !== "query" && scheme.in !== "cookie") return null;
|
|
75
|
+
return {
|
|
76
|
+
type: "apiKey",
|
|
77
|
+
name: scheme.name,
|
|
78
|
+
in: scheme.in
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
if (scheme.type === "http") return {
|
|
82
|
+
type: "http",
|
|
83
|
+
scheme: scheme.scheme?.toLowerCase() === "basic" ? "basic" : "bearer"
|
|
84
|
+
};
|
|
85
|
+
if (scheme.type === "oauth2") return { type: "oauth2" };
|
|
86
|
+
if (scheme.type === "openIdConnect") return { type: "openIdConnect" };
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Derives the per-operation security metadata from the OpenAPI document. The operation's own
|
|
91
|
+
* `security` overrides the global `security` (an explicit empty array disables auth), and every
|
|
92
|
+
* referenced scheme is resolved from `components.securitySchemes` into a flat, de-duplicated list of
|
|
93
|
+
* `Auth` objects the runtime walks in order.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* `getOperationSecurity({ document, method: 'POST', path: '/pet' })`
|
|
97
|
+
* `// [{ type: 'http', scheme: 'bearer' }]`
|
|
98
|
+
*/
|
|
99
|
+
function getOperationSecurity({ document, method, path }) {
|
|
100
|
+
if (!document) return void 0;
|
|
101
|
+
const requirements = (document.paths?.[path]?.[method.toLowerCase()])?.security ?? document.security;
|
|
102
|
+
if (!requirements?.length) return void 0;
|
|
103
|
+
const definitions = document.components?.securitySchemes ?? {};
|
|
104
|
+
const security = [];
|
|
105
|
+
const seen = /* @__PURE__ */ new Set();
|
|
106
|
+
for (const requirement of requirements) for (const schemeName of Object.keys(requirement)) {
|
|
107
|
+
if (seen.has(schemeName)) continue;
|
|
108
|
+
seen.add(schemeName);
|
|
109
|
+
const auth = resolveSecurityScheme(definitions[schemeName]);
|
|
110
|
+
if (auth) security.push(auth);
|
|
111
|
+
}
|
|
112
|
+
return security.length ? security : void 0;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Serializes the per-operation security into the literal emitted on each generated call's `security`
|
|
116
|
+
* field. The runtime `resolveAuth` helper walks it, calling the configured `auth` resolver per entry.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* `buildSecurityMetadata({ security: [{ type: 'http', scheme: 'bearer' }] }) // "[{ type: 'http', scheme: 'bearer' }]"`
|
|
120
|
+
*/
|
|
121
|
+
function buildSecurityMetadata({ security }) {
|
|
122
|
+
if (!security?.length) return null;
|
|
123
|
+
return `[${security.map(serializeAuth).join(", ")}]`;
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region ../../internals/utils/src/casing.ts
|
|
127
|
+
/**
|
|
128
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
129
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
130
|
+
* and capitalizes each word according to `pascal`.
|
|
131
|
+
*
|
|
132
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
133
|
+
*/
|
|
134
|
+
function toCamelOrPascal(text, pascal) {
|
|
135
|
+
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) => {
|
|
136
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
137
|
+
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
|
|
138
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Converts `text` to camelCase.
|
|
142
|
+
*
|
|
143
|
+
* @example Word boundaries
|
|
144
|
+
* `camelCase('hello-world') // 'helloWorld'`
|
|
145
|
+
*
|
|
146
|
+
* @example With a prefix
|
|
147
|
+
* `camelCase('tag', { prefix: 'create' }) // 'createTag'`
|
|
148
|
+
*/
|
|
149
|
+
function camelCase(text, { prefix = "", suffix = "" } = {}) {
|
|
150
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Converts `text` to PascalCase.
|
|
154
|
+
*
|
|
155
|
+
* @example Word boundaries
|
|
156
|
+
* `pascalCase('hello-world') // 'HelloWorld'`
|
|
157
|
+
*
|
|
158
|
+
* @example With a suffix
|
|
159
|
+
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
|
|
160
|
+
*/
|
|
161
|
+
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
|
|
162
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
163
|
+
}
|
|
164
|
+
//#endregion
|
|
165
|
+
//#region ../../internals/utils/src/fs.ts
|
|
166
|
+
/**
|
|
167
|
+
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
168
|
+
* (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
|
|
169
|
+
* every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
|
|
170
|
+
*
|
|
171
|
+
* Empty segments are dropped before joining. They arise when the name starts with a dot
|
|
172
|
+
* followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
|
|
173
|
+
* an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
|
|
174
|
+
* absolute path, letting generated files escape the configured output directory.
|
|
175
|
+
*
|
|
176
|
+
* @example Nested path from a dotted name
|
|
177
|
+
* `toFilePath('pet.petId') // 'pet/petId'`
|
|
178
|
+
*
|
|
179
|
+
* @example PascalCase the final segment
|
|
180
|
+
* `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
|
|
181
|
+
*
|
|
182
|
+
* @example Suffix applied to the final segment only
|
|
183
|
+
* `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
|
|
184
|
+
*/
|
|
185
|
+
function toFilePath(name, caseLast = camelCase) {
|
|
186
|
+
const parts = name.split(/\.(?=[a-zA-Z])/);
|
|
187
|
+
return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region ../../internals/utils/src/reserved.ts
|
|
191
|
+
/**
|
|
192
|
+
* JavaScript and Java reserved words.
|
|
193
|
+
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
194
|
+
*/
|
|
195
|
+
const reservedWords = new Set([
|
|
196
|
+
"abstract",
|
|
197
|
+
"arguments",
|
|
198
|
+
"boolean",
|
|
199
|
+
"break",
|
|
200
|
+
"byte",
|
|
201
|
+
"case",
|
|
202
|
+
"catch",
|
|
203
|
+
"char",
|
|
204
|
+
"class",
|
|
205
|
+
"const",
|
|
206
|
+
"continue",
|
|
207
|
+
"debugger",
|
|
208
|
+
"default",
|
|
209
|
+
"delete",
|
|
210
|
+
"do",
|
|
211
|
+
"double",
|
|
212
|
+
"else",
|
|
213
|
+
"enum",
|
|
214
|
+
"eval",
|
|
215
|
+
"export",
|
|
216
|
+
"extends",
|
|
217
|
+
"false",
|
|
218
|
+
"final",
|
|
219
|
+
"finally",
|
|
220
|
+
"float",
|
|
221
|
+
"for",
|
|
222
|
+
"function",
|
|
223
|
+
"goto",
|
|
224
|
+
"if",
|
|
225
|
+
"implements",
|
|
226
|
+
"import",
|
|
227
|
+
"in",
|
|
228
|
+
"instanceof",
|
|
229
|
+
"int",
|
|
230
|
+
"interface",
|
|
231
|
+
"let",
|
|
232
|
+
"long",
|
|
233
|
+
"native",
|
|
234
|
+
"new",
|
|
235
|
+
"null",
|
|
236
|
+
"package",
|
|
237
|
+
"private",
|
|
238
|
+
"protected",
|
|
239
|
+
"public",
|
|
240
|
+
"return",
|
|
241
|
+
"short",
|
|
242
|
+
"static",
|
|
243
|
+
"super",
|
|
244
|
+
"switch",
|
|
245
|
+
"synchronized",
|
|
246
|
+
"this",
|
|
247
|
+
"throw",
|
|
248
|
+
"throws",
|
|
249
|
+
"transient",
|
|
250
|
+
"true",
|
|
251
|
+
"try",
|
|
252
|
+
"typeof",
|
|
253
|
+
"var",
|
|
254
|
+
"void",
|
|
255
|
+
"volatile",
|
|
256
|
+
"while",
|
|
257
|
+
"with",
|
|
258
|
+
"yield",
|
|
259
|
+
"Array",
|
|
260
|
+
"Date",
|
|
261
|
+
"hasOwnProperty",
|
|
262
|
+
"Infinity",
|
|
263
|
+
"isFinite",
|
|
264
|
+
"isNaN",
|
|
265
|
+
"isPrototypeOf",
|
|
266
|
+
"length",
|
|
267
|
+
"Math",
|
|
268
|
+
"name",
|
|
269
|
+
"NaN",
|
|
270
|
+
"Number",
|
|
271
|
+
"Object",
|
|
272
|
+
"prototype",
|
|
273
|
+
"String",
|
|
274
|
+
"toString",
|
|
275
|
+
"undefined",
|
|
276
|
+
"valueOf"
|
|
277
|
+
]);
|
|
278
|
+
/**
|
|
279
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
280
|
+
*
|
|
281
|
+
* @example
|
|
282
|
+
* ```ts
|
|
283
|
+
* isValidVarName('status') // true
|
|
284
|
+
* isValidVarName('class') // false (reserved word)
|
|
285
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
286
|
+
* ```
|
|
287
|
+
*/
|
|
288
|
+
function isValidVarName(name) {
|
|
289
|
+
if (!name || reservedWords.has(name)) return false;
|
|
290
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Returns `name` when it's a syntactically valid JavaScript variable name,
|
|
294
|
+
* otherwise prefixes it with `_` so the result is a valid identifier.
|
|
295
|
+
*
|
|
296
|
+
* Useful for sanitizing OpenAPI schema names or operation IDs that start with
|
|
297
|
+
* a digit (e.g. `409`, `504AccountCancel`) before using them as exported
|
|
298
|
+
* variable, type, or function names.
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* ```ts
|
|
302
|
+
* ensureValidVarName('409') // '_409'
|
|
303
|
+
* ensureValidVarName('504AccountCancel') // '_504AccountCancel'
|
|
304
|
+
* ensureValidVarName('Pet') // 'Pet'
|
|
305
|
+
* ensureValidVarName('class') // '_class'
|
|
306
|
+
* ```
|
|
307
|
+
*/
|
|
308
|
+
function ensureValidVarName(name) {
|
|
309
|
+
if (!name || isValidVarName(name)) return name;
|
|
310
|
+
return `_${name}`;
|
|
311
|
+
}
|
|
312
|
+
//#endregion
|
|
313
|
+
//#region ../../internals/utils/src/url.ts
|
|
314
|
+
function transformParam(raw, casing) {
|
|
315
|
+
const param = isValidVarName(raw) ? raw : camelCase(raw);
|
|
316
|
+
return casing === "camelcase" ? camelCase(param) : param;
|
|
317
|
+
}
|
|
318
|
+
function toParamsObject(path, { replacer, casing } = {}) {
|
|
319
|
+
const params = {};
|
|
320
|
+
for (const match of path.matchAll(/\{([^}]+)\}/g)) {
|
|
321
|
+
const param = transformParam(match[1], casing);
|
|
322
|
+
const key = replacer ? replacer(param) : param;
|
|
323
|
+
params[key] = key;
|
|
324
|
+
}
|
|
325
|
+
return Object.keys(params).length > 0 ? params : null;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.
|
|
329
|
+
*/
|
|
330
|
+
var Url = class Url {
|
|
331
|
+
/**
|
|
332
|
+
* Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.
|
|
333
|
+
*
|
|
334
|
+
* @example
|
|
335
|
+
* Url.canParse('https://petstore.swagger.io/v2') // true
|
|
336
|
+
* Url.canParse('/pet/{petId}') // false
|
|
337
|
+
*/
|
|
338
|
+
static canParse(url, base) {
|
|
339
|
+
return URL.canParse(url, base);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Converts an OpenAPI/Swagger path to Express-style colon syntax.
|
|
343
|
+
*
|
|
344
|
+
* @example
|
|
345
|
+
* Url.toPath('/pet/{petId}') // '/pet/:petId'
|
|
346
|
+
*/
|
|
347
|
+
static toPath(path) {
|
|
348
|
+
return path.replace(/\{([^}]+)\}/g, ":$1");
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Converts an OpenAPI/Swagger path to a TypeScript template literal string.
|
|
352
|
+
* `prefix` is prepended inside the literal, `replacer` transforms each parameter name,
|
|
353
|
+
* and `casing` controls parameter identifier casing.
|
|
354
|
+
*
|
|
355
|
+
* @example
|
|
356
|
+
* Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'
|
|
360
|
+
*/
|
|
361
|
+
static toTemplateString(path, { prefix, replacer, casing } = {}) {
|
|
362
|
+
const result = path.split(/\{([^}]+)\}/).map((part, i) => {
|
|
363
|
+
if (i % 2 === 0) return part;
|
|
364
|
+
const param = transformParam(part, casing);
|
|
365
|
+
return `\${${replacer ? replacer(param) : param}}`;
|
|
366
|
+
}).join("");
|
|
367
|
+
return `\`${prefix ?? ""}${result}\``;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Converts an OpenAPI/Swagger path to a template literal that reads each parameter off the
|
|
371
|
+
* grouped `path` request option, e.g. `/pet/{petId}` becomes `` `/pet/${path.petId}` ``. Parameter
|
|
372
|
+
* names are camelCased to match the generated `path` type, and `prefix` is prepended inside the
|
|
373
|
+
* literal. Shared by the client and cypress generators that pass a grouped `path` object.
|
|
374
|
+
*
|
|
375
|
+
* @example
|
|
376
|
+
* Url.toGroupedTemplateString('/pet/{petId}') // '`/pet/${path.petId}`'
|
|
377
|
+
*/
|
|
378
|
+
static toGroupedTemplateString(path, { prefix } = {}) {
|
|
379
|
+
return Url.toTemplateString(path, {
|
|
380
|
+
prefix,
|
|
381
|
+
casing: "camelcase",
|
|
382
|
+
replacer: (name) => `path.${name}`
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Returns the path and its extracted params as a structured `URLObject`, or as a stringified
|
|
387
|
+
* expression when `stringify` is set.
|
|
388
|
+
*
|
|
389
|
+
* @example
|
|
390
|
+
* Url.toObject('/pet/{petId}')
|
|
391
|
+
* // { url: '/pet/:petId', params: { petId: 'petId' } }
|
|
392
|
+
*/
|
|
393
|
+
static toObject(path, { type = "path", replacer, stringify, casing } = {}) {
|
|
394
|
+
const object = {
|
|
395
|
+
url: type === "path" ? Url.toPath(path) : Url.toTemplateString(path, {
|
|
396
|
+
replacer,
|
|
397
|
+
casing
|
|
398
|
+
}),
|
|
399
|
+
params: toParamsObject(path, {
|
|
400
|
+
replacer,
|
|
401
|
+
casing
|
|
402
|
+
})
|
|
403
|
+
};
|
|
404
|
+
if (stringify) {
|
|
405
|
+
if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
|
|
406
|
+
if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
|
|
407
|
+
return `{ url: '${object.url}' }`;
|
|
408
|
+
}
|
|
409
|
+
return object;
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
//#endregion
|
|
413
|
+
//#region ../../internals/shared/src/params.ts
|
|
414
|
+
const caseParamsCache = /* @__PURE__ */ new WeakMap();
|
|
415
|
+
/**
|
|
416
|
+
* Applies camelCase to parameter names and returns a new array without mutating the input.
|
|
417
|
+
*
|
|
418
|
+
* Run it before handing parameters to schema builders so output property keys get the right casing
|
|
419
|
+
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
|
|
420
|
+
* original array is returned unchanged. Results are cached per input array.
|
|
421
|
+
*/
|
|
422
|
+
function caseParams(params, casing) {
|
|
423
|
+
if (!casing) return params;
|
|
424
|
+
const cached = caseParamsCache.get(params);
|
|
425
|
+
if (cached) return cached;
|
|
426
|
+
const result = params.map((param) => ({
|
|
427
|
+
...param,
|
|
428
|
+
name: camelCase(param.name)
|
|
429
|
+
}));
|
|
430
|
+
caseParamsCache.set(params, result);
|
|
431
|
+
return result;
|
|
432
|
+
}
|
|
433
|
+
//#endregion
|
|
434
|
+
//#region ../../internals/shared/src/operation.ts
|
|
435
|
+
/**
|
|
436
|
+
* Builds the `ResolverFileParams` every operation generator passes to
|
|
437
|
+
* `resolver.resolveFile`: a file named `name`, tagged by the operation's first
|
|
438
|
+
* tag (or `'default'`), at the operation's path. Centralizes the entry object
|
|
439
|
+
* that was repeated at dozens of call sites across the client and query plugins.
|
|
440
|
+
*
|
|
441
|
+
* @example
|
|
442
|
+
* ```ts
|
|
443
|
+
* resolver.resolveFile(operationFileEntry(node, node.operationId), { root, output, group })
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
function operationFileEntry(node, name, extname = ".ts") {
|
|
447
|
+
return {
|
|
448
|
+
name,
|
|
449
|
+
extname,
|
|
450
|
+
tag: node.tags[0] ?? "default",
|
|
451
|
+
path: node.path
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function getOperationLink(node, link) {
|
|
455
|
+
if (!link) return null;
|
|
456
|
+
if (typeof link === "function") return link(node) ?? null;
|
|
457
|
+
if (link === "urlPath") return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
|
|
458
|
+
return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
|
|
459
|
+
}
|
|
460
|
+
function buildOperationComments(node, options = {}) {
|
|
461
|
+
const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
|
|
462
|
+
const linkComment = getOperationLink(node, link);
|
|
463
|
+
const filteredComments = (linkPosition === "beforeDeprecated" ? [
|
|
464
|
+
node.description && `@description ${node.description}`,
|
|
465
|
+
node.summary && `@summary ${node.summary}`,
|
|
466
|
+
linkComment,
|
|
467
|
+
node.deprecated && "@deprecated"
|
|
468
|
+
] : [
|
|
469
|
+
node.description && `@description ${node.description}`,
|
|
470
|
+
node.summary && `@summary ${node.summary}`,
|
|
471
|
+
node.deprecated && "@deprecated",
|
|
472
|
+
linkComment
|
|
473
|
+
]).filter((comment) => Boolean(comment));
|
|
474
|
+
if (!splitLines) return filteredComments;
|
|
475
|
+
return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
|
|
476
|
+
}
|
|
477
|
+
function getOperationParameters(node, options = {}) {
|
|
478
|
+
const params = caseParams(node.parameters, options.paramsCasing === "original" ? void 0 : "camelcase");
|
|
479
|
+
return {
|
|
480
|
+
path: params.filter((param) => param.in === "path"),
|
|
481
|
+
query: params.filter((param) => param.in === "query"),
|
|
482
|
+
header: params.filter((param) => param.in === "header"),
|
|
483
|
+
cookie: params.filter((param) => param.in === "cookie")
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region ../../internals/shared/src/group.ts
|
|
488
|
+
/**
|
|
489
|
+
* Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
|
|
490
|
+
* shared default naming so every plugin groups output consistently:
|
|
491
|
+
*
|
|
492
|
+
* - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
|
|
493
|
+
* - other groups use the camelCased group (`pet store` → `petStore`).
|
|
494
|
+
*
|
|
495
|
+
* A user-provided `group.name` always wins over the default namer, so callers stay in
|
|
496
|
+
* control of their output folders. Returns `null` when grouping is disabled, matching the
|
|
497
|
+
* per-plugin convention.
|
|
498
|
+
*
|
|
499
|
+
* @param group - The user-supplied group option, or `undefined` to disable grouping.
|
|
500
|
+
*
|
|
501
|
+
* @example
|
|
502
|
+
* ```ts
|
|
503
|
+
* createGroupConfig(group) // shared across every plugin
|
|
504
|
+
* ```
|
|
505
|
+
*/
|
|
506
|
+
function createGroupConfig(group) {
|
|
507
|
+
if (!group) return null;
|
|
508
|
+
const defaultName = (ctx) => {
|
|
509
|
+
if (group.type === "path") return `${ctx.group.split("/")[1]}`;
|
|
510
|
+
return camelCase(ctx.group);
|
|
511
|
+
};
|
|
512
|
+
return {
|
|
513
|
+
...group,
|
|
514
|
+
name: group.name ? group.name : defaultName
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
//#endregion
|
|
518
|
+
//#region ../../internals/client/src/builders/generics.ts
|
|
519
|
+
/**
|
|
520
|
+
* Builds the `RequestResult` generic arguments for one operation: the plugin-ts per-status responses
|
|
521
|
+
* record plus the per-call `ThrowOnError` flag. `SuccessOf` / `ErrorOf` split the record inside the
|
|
522
|
+
* runtime, so this only names the record and threads `ThrowOnError`.
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* `buildRequestResultGenerics({ node, tsResolver }) // 'AddPetResponses, ThrowOnError'`
|
|
526
|
+
*/
|
|
527
|
+
function buildRequestResultGenerics({ node, tsResolver }) {
|
|
528
|
+
return `${tsResolver.resolveResponsesName(node)}, ThrowOnError`;
|
|
529
|
+
}
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region ../../internals/client/src/builders/returnStatement.ts
|
|
532
|
+
/**
|
|
533
|
+
* Builds the return statement of a generated operation function. The runtime call already resolves
|
|
534
|
+
* to `{ data, error, request, response }`; the generated code forwards that result and casts it to
|
|
535
|
+
* the operation's `RequestResult`, which carries the `throwOnError` discrimination.
|
|
536
|
+
*
|
|
537
|
+
* @example
|
|
538
|
+
* `return request({ method: 'POST', url: '/pet', ...config }) as Promise<RequestResult<AddPetResponses, ThrowOnError>>`
|
|
539
|
+
*/
|
|
540
|
+
function buildReturnStatement({ node, tsResolver, callConfig }) {
|
|
541
|
+
return `return request(${callConfig}) as Promise<RequestResult<${buildRequestResultGenerics({
|
|
542
|
+
node,
|
|
543
|
+
tsResolver
|
|
544
|
+
})}>>`;
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region ../../internals/client/src/builders/signature.ts
|
|
548
|
+
const declarationPrinter = functionPrinter({ mode: "declaration" });
|
|
549
|
+
/**
|
|
550
|
+
* Builds the grouped-options signature for one operation: a single `options` object whose `TData`
|
|
551
|
+
* is the plugin-ts `<Name>RequestConfig` (carrying a literal `url`), and a `RequestResult` return type
|
|
552
|
+
* keyed to the plugin-ts per-status responses record. There are no positional arguments.
|
|
553
|
+
*
|
|
554
|
+
* The generated file imports `<Name>RequestConfig` and `<Name>Responses` and uses them directly, so no
|
|
555
|
+
* per-operation input type has to be emitted.
|
|
556
|
+
*/
|
|
557
|
+
function buildGroupedOptionsSignature({ node, tsResolver }) {
|
|
558
|
+
const requestConfigName = tsResolver.resolveRequestConfigName(node);
|
|
559
|
+
const responsesName = tsResolver.resolveResponsesName(node);
|
|
560
|
+
const resultGenerics = buildRequestResultGenerics({
|
|
561
|
+
node,
|
|
562
|
+
tsResolver
|
|
563
|
+
});
|
|
564
|
+
return {
|
|
565
|
+
dataTypeName: requestConfigName,
|
|
566
|
+
paramsSignature: declarationPrinter.print(createFunctionParameters({ params: [createFunctionParameter({
|
|
567
|
+
name: "options",
|
|
568
|
+
type: `Options<${requestConfigName}, ThrowOnError>`
|
|
569
|
+
})] })) ?? "",
|
|
570
|
+
returnType: `Promise<RequestResult<${resultGenerics}>>`,
|
|
571
|
+
generics: ["ThrowOnError extends boolean = true"],
|
|
572
|
+
importedTypeNames: [requestConfigName, responsesName]
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
//#endregion
|
|
576
|
+
//#region ../../internals/client/src/builders/validator.ts
|
|
577
|
+
/**
|
|
578
|
+
* Builds the parser-hook expressions for one operation. Request parsing runs before the send;
|
|
579
|
+
* response parsing runs on the success body only. Returns `null` expressions when the matching
|
|
580
|
+
* parser direction is disabled or the schema is absent.
|
|
581
|
+
*/
|
|
582
|
+
function buildParserHooks({ node, parser, zodResolver }) {
|
|
583
|
+
const importedZodNames = [];
|
|
584
|
+
const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
|
|
585
|
+
const zodRequestName = zodResolver && resolveRequestParser(parser) === "zod" && hasRequestBody ? zodResolver.resolveDataName?.(node) : null;
|
|
586
|
+
const request = zodRequestName ? `(data: unknown) => ${zodRequestName}.parse(data)` : null;
|
|
587
|
+
if (zodRequestName) importedZodNames.push(zodRequestName);
|
|
588
|
+
const responseParse = zodResolver && resolveResponseParser(parser) === "zod" ? buildZodResponseParse(node, zodResolver) : null;
|
|
589
|
+
const response = responseParse ? `(data: unknown) => ${responseParse.expression}.parse(data)` : null;
|
|
590
|
+
if (responseParse) importedZodNames.push(...responseParse.importNames);
|
|
591
|
+
return {
|
|
592
|
+
request,
|
|
593
|
+
response,
|
|
594
|
+
importedZodNames
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
//#endregion
|
|
598
|
+
//#region ../../internals/client/src/components/Operation.tsx
|
|
599
|
+
/**
|
|
600
|
+
* Renders one client operation: the grouped `<Name>Request` type and the function that forwards a
|
|
601
|
+
* single `options` object to the resolved client and returns the `RequestResult`. The type, signature,
|
|
602
|
+
* and call config are built with the AST factory, and only the jsx-renderer emits the source.
|
|
603
|
+
*/
|
|
604
|
+
function Operation({ name, node, tsResolver, zodResolver, parser, security, isExportable = true, isIndexable = true }) {
|
|
605
|
+
if (!ast.isHttpOperationNode(node)) return null;
|
|
606
|
+
const signature = buildGroupedOptionsSignature({
|
|
607
|
+
node,
|
|
608
|
+
tsResolver
|
|
609
|
+
});
|
|
610
|
+
const parsers = buildParserHooks({
|
|
611
|
+
node,
|
|
612
|
+
parser,
|
|
613
|
+
zodResolver
|
|
614
|
+
});
|
|
615
|
+
const securityLiteral = buildSecurityMetadata({ security });
|
|
616
|
+
const parserEntries = [parsers.request ? `request: ${parsers.request}` : null, parsers.response ? `response: ${parsers.response}` : null].filter(Boolean);
|
|
617
|
+
const parserLiteral = parserEntries.length ? `parser: { ${parserEntries.join(", ")} }` : null;
|
|
618
|
+
const callConfig = `{ ${[
|
|
619
|
+
`method: '${node.method.toUpperCase()}'`,
|
|
620
|
+
`url: '${node.path}'`,
|
|
621
|
+
securityLiteral ? `security: ${securityLiteral}` : null,
|
|
622
|
+
parserLiteral,
|
|
623
|
+
"...config"
|
|
624
|
+
].filter(Boolean).join(", ")} }`;
|
|
625
|
+
return /* @__PURE__ */ jsx(File.Source, {
|
|
626
|
+
name,
|
|
627
|
+
isExportable,
|
|
628
|
+
isIndexable,
|
|
629
|
+
children: /* @__PURE__ */ jsxs(Function, {
|
|
630
|
+
name,
|
|
631
|
+
export: isExportable,
|
|
632
|
+
generics: signature.generics,
|
|
633
|
+
params: signature.paramsSignature,
|
|
634
|
+
returnType: signature.returnType,
|
|
635
|
+
JSDoc: { comments: buildOperationComments(node, {
|
|
636
|
+
link: "urlPath",
|
|
637
|
+
linkPosition: "beforeDeprecated",
|
|
638
|
+
splitLines: true
|
|
639
|
+
}) },
|
|
640
|
+
children: [
|
|
641
|
+
"const { client: request = client, ...config } = options",
|
|
642
|
+
/* @__PURE__ */ jsx("br", {}),
|
|
643
|
+
buildReturnStatement({
|
|
644
|
+
node,
|
|
645
|
+
tsResolver,
|
|
646
|
+
callConfig
|
|
647
|
+
})
|
|
648
|
+
]
|
|
649
|
+
})
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
//#endregion
|
|
653
|
+
//#region ../../internals/client/src/builders/sdkMethod.ts
|
|
654
|
+
/**
|
|
655
|
+
* Builds the call config literal forwarded to the contract client, mirroring the shared `Operation`
|
|
656
|
+
* component: `{ method, url, security?, parser?, ...config }`. The `...config` spread carries every
|
|
657
|
+
* per-call field (including `throwOnError`), so the method stays a thin wrapper over the contract.
|
|
658
|
+
*/
|
|
659
|
+
function buildCallConfig({ node, parser, zodResolver, security }) {
|
|
660
|
+
const parsers = buildParserHooks({
|
|
661
|
+
node,
|
|
662
|
+
parser,
|
|
663
|
+
zodResolver
|
|
664
|
+
});
|
|
665
|
+
const parserEntries = [parsers.request ? `request: ${parsers.request}` : null, parsers.response ? `response: ${parsers.response}` : null].filter(Boolean);
|
|
666
|
+
const parserLiteral = parserEntries.length ? `parser: { ${parserEntries.join(", ")} }` : null;
|
|
667
|
+
const securityLiteral = buildSecurityMetadata({ security });
|
|
668
|
+
return `{ ${[
|
|
669
|
+
`method: '${node.method.toUpperCase()}'`,
|
|
670
|
+
`url: '${node.path}'`,
|
|
671
|
+
securityLiteral ? `security: ${securityLiteral}` : null,
|
|
672
|
+
parserLiteral,
|
|
673
|
+
"...config"
|
|
674
|
+
].filter(Boolean).join(", ")} }`;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Builds a single instance method for a generated SDK class. The body forwards the single grouped
|
|
678
|
+
* `options` object to the instance's own client (`this.client`, built once in the constructor) and
|
|
679
|
+
* returns the `RequestResult`. A per-call `options.client` still overrides the instance client, so
|
|
680
|
+
* one operation can be routed to a different environment without a new instance.
|
|
681
|
+
*/
|
|
682
|
+
function buildSdkMethod({ node, name, tsResolver, zodResolver, parser, security }) {
|
|
683
|
+
if (!ast.isHttpOperationNode(node)) return "";
|
|
684
|
+
const signature = buildGroupedOptionsSignature({
|
|
685
|
+
node,
|
|
686
|
+
tsResolver
|
|
687
|
+
});
|
|
688
|
+
const returnStatement = buildReturnStatement({
|
|
689
|
+
node,
|
|
690
|
+
tsResolver,
|
|
691
|
+
callConfig: buildCallConfig({
|
|
692
|
+
node,
|
|
693
|
+
parser,
|
|
694
|
+
zodResolver,
|
|
695
|
+
security
|
|
696
|
+
})
|
|
697
|
+
});
|
|
698
|
+
const generics = signature.generics.length ? `<${signature.generics.join(", ")}>` : "";
|
|
699
|
+
const jsdoc = buildJSDoc(buildOperationComments(node, {
|
|
700
|
+
link: "urlPath",
|
|
701
|
+
linkPosition: "beforeDeprecated",
|
|
702
|
+
splitLines: true
|
|
703
|
+
}));
|
|
704
|
+
const methodBody = [
|
|
705
|
+
"const { client: request = this.client, ...config } = options",
|
|
706
|
+
"",
|
|
707
|
+
returnStatement
|
|
708
|
+
].map((line) => line ? ` ${line}` : "").join("\n");
|
|
709
|
+
return `${jsdoc} public ${name}${generics}(${signature.paramsSignature}): ${signature.returnType} {\n${methodBody}\n }`;
|
|
710
|
+
}
|
|
711
|
+
//#endregion
|
|
712
|
+
//#region ../../internals/client/src/components/SdkClient.tsx
|
|
713
|
+
/**
|
|
714
|
+
* Renders one instance class per tag with one method per operation. The constructor takes a client
|
|
715
|
+
* config object and builds its own client through `createClient`, so each environment is a separate
|
|
716
|
+
* instance: `const api = new PetClient({ baseURL }); api.getPetById(...)`. A per-call `client` option
|
|
717
|
+
* still overrides the instance client for a one-off call.
|
|
718
|
+
*/
|
|
719
|
+
function SdkClient({ name, isExportable = true, isIndexable = true, operations, parser, children }) {
|
|
720
|
+
const methods = operations.map(({ node, name: methodName, tsResolver, zodResolver, security }) => buildSdkMethod({
|
|
721
|
+
node,
|
|
722
|
+
name: methodName,
|
|
723
|
+
tsResolver,
|
|
724
|
+
zodResolver,
|
|
725
|
+
parser,
|
|
726
|
+
security
|
|
727
|
+
}));
|
|
728
|
+
const classCode = `export class ${name} {\n${[
|
|
729
|
+
" private readonly client: ClientInstance",
|
|
730
|
+
"",
|
|
731
|
+
" constructor(config: ClientConfig = {}) {",
|
|
732
|
+
" this.client = createClient(config)",
|
|
733
|
+
" }"
|
|
734
|
+
].join("\n")}\n\n${methods.join("\n\n")}\n}`;
|
|
735
|
+
return /* @__PURE__ */ jsxs(File.Source, {
|
|
736
|
+
name,
|
|
737
|
+
isExportable,
|
|
738
|
+
isIndexable,
|
|
739
|
+
children: [classCode, children]
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
//#endregion
|
|
743
|
+
//#region ../../internals/client/src/components/SdkFacade.tsx
|
|
744
|
+
/**
|
|
745
|
+
* Renders a composed root SDK class that instantiates every tag client from one shared config, so
|
|
746
|
+
* `new PetStore({ baseURL }).petClient.getPetById(...)` reaches an operation through a single entry
|
|
747
|
+
* point bound to one environment. The per-tag clients are read-only fields built in the constructor.
|
|
748
|
+
*/
|
|
749
|
+
function SdkFacade({ name, isExportable = true, isIndexable = true, members, children }) {
|
|
750
|
+
const fields = members.map((member) => ` readonly ${member.propName}: ${member.className}`);
|
|
751
|
+
const assignments = members.map((member) => ` this.${member.propName} = new ${member.className}(config)`);
|
|
752
|
+
const classCode = `export class ${name} {\n${[
|
|
753
|
+
...fields,
|
|
754
|
+
"",
|
|
755
|
+
" constructor(config: ClientConfig = {}) {",
|
|
756
|
+
...assignments,
|
|
757
|
+
" }"
|
|
758
|
+
].join("\n")}\n}`;
|
|
759
|
+
return /* @__PURE__ */ jsxs(File.Source, {
|
|
760
|
+
name,
|
|
761
|
+
isExportable,
|
|
762
|
+
isIndexable,
|
|
763
|
+
children: [classCode, children]
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
//#endregion
|
|
767
|
+
//#region ../../internals/client/src/generators/sdkGenerator.tsx
|
|
768
|
+
function resolveTypeImportNames(node, tsResolver) {
|
|
769
|
+
return [tsResolver.resolveRequestConfigName(node), tsResolver.resolveResponsesName(node)];
|
|
770
|
+
}
|
|
771
|
+
function resolveZodImportNames(node, zodResolver, parser) {
|
|
772
|
+
const { query: queryParams } = getOperationParameters(node, { paramsCasing: "original" });
|
|
773
|
+
return [
|
|
774
|
+
resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
|
|
775
|
+
resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
|
|
776
|
+
resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
|
|
777
|
+
].filter((n) => Boolean(n));
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Groups operations into one controller per tag. Operations without a tag fall back to a single
|
|
781
|
+
* `Client`/`ApiClient` controller, matching the resolver's default naming.
|
|
782
|
+
*/
|
|
783
|
+
function buildControllers(nodes, ctx) {
|
|
784
|
+
const { driver, resolver, root } = ctx;
|
|
785
|
+
const { output, group, parser } = ctx.options;
|
|
786
|
+
const pluginTs = driver.getPlugin(pluginTsName);
|
|
787
|
+
const tsResolver = driver.getResolver(pluginTsName);
|
|
788
|
+
const tsPluginOptions = pluginTs.options;
|
|
789
|
+
const pluginZod = isParserEnabled(parser) ? driver.getPlugin(pluginZodName) : null;
|
|
790
|
+
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
791
|
+
const document = ctx.adapter.document;
|
|
792
|
+
function buildOperationData(node) {
|
|
793
|
+
const typeFile = tsResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
794
|
+
root,
|
|
795
|
+
output: tsPluginOptions?.output ?? output,
|
|
796
|
+
group: tsPluginOptions?.group
|
|
797
|
+
});
|
|
798
|
+
const zodFile = zodResolver && pluginZod?.options ? zodResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
799
|
+
root,
|
|
800
|
+
output: pluginZod.options?.output ?? output,
|
|
801
|
+
group: pluginZod.options?.group ?? void 0
|
|
802
|
+
}) : null;
|
|
803
|
+
const security = ast.isHttpOperationNode(node) ? getOperationSecurity({
|
|
804
|
+
document,
|
|
805
|
+
method: node.method,
|
|
806
|
+
path: node.path
|
|
807
|
+
}) : void 0;
|
|
808
|
+
return {
|
|
809
|
+
node,
|
|
810
|
+
name: resolver.resolveName(node.operationId),
|
|
811
|
+
tsResolver,
|
|
812
|
+
zodResolver,
|
|
813
|
+
typeFile,
|
|
814
|
+
zodFile,
|
|
815
|
+
security
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
return nodes.reduce((acc, operationNode) => {
|
|
819
|
+
if (!ast.isHttpOperationNode(operationNode)) return acc;
|
|
820
|
+
const tag = operationNode.tags[0];
|
|
821
|
+
const name = tag ? group?.name?.({ group: camelCase(tag) }) ?? resolver.resolveGroupName(tag) : resolver.resolveClassName("ApiClient");
|
|
822
|
+
const file = resolver.resolveFile({
|
|
823
|
+
name,
|
|
824
|
+
extname: ".ts",
|
|
825
|
+
tag
|
|
826
|
+
}, {
|
|
827
|
+
root,
|
|
828
|
+
output,
|
|
829
|
+
group: group ?? void 0
|
|
830
|
+
});
|
|
831
|
+
const operationData = buildOperationData(operationNode);
|
|
832
|
+
const previous = acc.find((item) => item.file.path === file.path);
|
|
833
|
+
if (previous) previous.operations.push(operationData);
|
|
834
|
+
else acc.push({
|
|
835
|
+
name,
|
|
836
|
+
tag,
|
|
837
|
+
file,
|
|
838
|
+
operations: [operationData]
|
|
839
|
+
});
|
|
840
|
+
return acc;
|
|
841
|
+
}, []);
|
|
842
|
+
}
|
|
843
|
+
function collectImportsByFile(ops, pick) {
|
|
844
|
+
const namesByPath = /* @__PURE__ */ new Map();
|
|
845
|
+
const filesByPath = /* @__PURE__ */ new Map();
|
|
846
|
+
ops.forEach((op) => {
|
|
847
|
+
const { file, names } = pick(op);
|
|
848
|
+
if (!file || names.length === 0) return;
|
|
849
|
+
if (!namesByPath.has(file.path)) namesByPath.set(file.path, /* @__PURE__ */ new Set());
|
|
850
|
+
const set = namesByPath.get(file.path);
|
|
851
|
+
names.forEach((n) => set.add(n));
|
|
852
|
+
filesByPath.set(file.path, file);
|
|
853
|
+
});
|
|
854
|
+
return {
|
|
855
|
+
namesByPath,
|
|
856
|
+
filesByPath
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* Builds the class-based SDK generator for a client plugin (`@kubb/plugin-fetch`,
|
|
861
|
+
* `@kubb/plugin-axios`). Only registered when `sdk` is set; otherwise the plugin keeps its
|
|
862
|
+
* standalone per-operation functions.
|
|
863
|
+
*
|
|
864
|
+
* Every tag client is an instance class whose constructor takes a client config and builds its own
|
|
865
|
+
* client, so each environment is a separate instance. With `sdk.mode: 'tag'` (the default) it
|
|
866
|
+
* emits one class per tag and, when `sdk.name` is set, a composed root that instantiates every tag
|
|
867
|
+
* client. With `sdk.mode: 'flat'` it emits one class named by `sdk.name`, with every operation as a
|
|
868
|
+
* direct method.
|
|
869
|
+
*/
|
|
870
|
+
function createSdkGenerator() {
|
|
871
|
+
return defineGenerator({
|
|
872
|
+
name: "sdk",
|
|
873
|
+
renderer: jsxRenderer,
|
|
874
|
+
operations(nodes, ctx) {
|
|
875
|
+
const { config, resolver, root } = ctx;
|
|
876
|
+
const { output, group, parser, sdk } = ctx.options;
|
|
877
|
+
if (!ctx.driver.getPlugin(pluginTsName) || !sdk) return null;
|
|
878
|
+
const controllers = buildControllers(nodes, ctx);
|
|
879
|
+
const clientPath = path.resolve(root, ".kubb/client.ts");
|
|
880
|
+
const banner = (file) => resolver.resolveBanner(ctx.meta, {
|
|
881
|
+
output,
|
|
882
|
+
config,
|
|
883
|
+
file: {
|
|
884
|
+
path: file.path,
|
|
885
|
+
baseName: file.baseName
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
const footer = (file) => resolver.resolveFooter(ctx.meta, {
|
|
889
|
+
output,
|
|
890
|
+
config,
|
|
891
|
+
file: {
|
|
892
|
+
path: file.path,
|
|
893
|
+
baseName: file.baseName
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
const renderClassFile = (className, file, ops) => {
|
|
897
|
+
const { namesByPath: typeNamesByPath, filesByPath: typeFilesByPath } = collectImportsByFile(ops, (op) => ({
|
|
898
|
+
file: op.typeFile,
|
|
899
|
+
names: resolveTypeImportNames(op.node, op.tsResolver)
|
|
900
|
+
}));
|
|
901
|
+
const { namesByPath: zodNamesByPath, filesByPath: zodFilesByPath } = isParserEnabled(parser) ? collectImportsByFile(ops, (op) => ({
|
|
902
|
+
file: op.zodFile,
|
|
903
|
+
names: op.zodResolver ? resolveZodImportNames(op.node, op.zodResolver, parser) : []
|
|
904
|
+
})) : {
|
|
905
|
+
namesByPath: /* @__PURE__ */ new Map(),
|
|
906
|
+
filesByPath: /* @__PURE__ */ new Map()
|
|
907
|
+
};
|
|
908
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
909
|
+
baseName: file.baseName,
|
|
910
|
+
path: file.path,
|
|
911
|
+
meta: file.meta,
|
|
912
|
+
banner: banner(file),
|
|
913
|
+
footer: footer(file),
|
|
914
|
+
children: [
|
|
915
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
916
|
+
name: ["createClient"],
|
|
917
|
+
root: file.path,
|
|
918
|
+
path: clientPath
|
|
919
|
+
}),
|
|
920
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
921
|
+
name: [
|
|
922
|
+
"ClientConfig",
|
|
923
|
+
"ClientInstance",
|
|
924
|
+
"Options",
|
|
925
|
+
"RequestResult"
|
|
926
|
+
],
|
|
927
|
+
root: file.path,
|
|
928
|
+
path: clientPath,
|
|
929
|
+
isTypeOnly: true
|
|
930
|
+
}),
|
|
931
|
+
parser === "zod" && ops.some((op) => op.node.requestBody?.content?.[0]?.schema != null) && /* @__PURE__ */ jsx(File.Import, {
|
|
932
|
+
name: ["z"],
|
|
933
|
+
path: "zod",
|
|
934
|
+
isTypeOnly: true
|
|
935
|
+
}),
|
|
936
|
+
Array.from(typeNamesByPath.entries()).map(([filePath, set]) => /* @__PURE__ */ jsx(File.Import, {
|
|
937
|
+
name: Array.from(set),
|
|
938
|
+
root: file.path,
|
|
939
|
+
path: typeFilesByPath.get(filePath).path,
|
|
940
|
+
isTypeOnly: true
|
|
941
|
+
}, filePath)),
|
|
942
|
+
isParserEnabled(parser) && Array.from(zodNamesByPath.entries()).map(([filePath, set]) => /* @__PURE__ */ jsx(File.Import, {
|
|
943
|
+
name: Array.from(set),
|
|
944
|
+
root: file.path,
|
|
945
|
+
path: zodFilesByPath.get(filePath).path
|
|
946
|
+
}, filePath)),
|
|
947
|
+
/* @__PURE__ */ jsx(SdkClient, {
|
|
948
|
+
name: className,
|
|
949
|
+
operations: ops,
|
|
950
|
+
parser
|
|
951
|
+
})
|
|
952
|
+
]
|
|
953
|
+
}, file.path);
|
|
954
|
+
};
|
|
955
|
+
if (sdk.mode === "flat") return renderClassFile(resolver.resolveClassName(sdk.name ?? "sdk"), resolver.resolveFile({
|
|
956
|
+
name: sdk.name ?? "sdk",
|
|
957
|
+
extname: ".ts"
|
|
958
|
+
}, {
|
|
959
|
+
root,
|
|
960
|
+
output,
|
|
961
|
+
group: group ?? void 0
|
|
962
|
+
}), controllers.flatMap((controller) => controller.operations));
|
|
963
|
+
const classFiles = controllers.map(({ name, file, operations: ops }) => renderClassFile(name, file, ops));
|
|
964
|
+
if (!sdk.name) return /* @__PURE__ */ jsx(Fragment, { children: classFiles });
|
|
965
|
+
const sdkFile = resolver.resolveFile({
|
|
966
|
+
name: sdk.name,
|
|
967
|
+
extname: ".ts"
|
|
968
|
+
}, {
|
|
969
|
+
root,
|
|
970
|
+
output,
|
|
971
|
+
group: group ?? void 0
|
|
972
|
+
});
|
|
973
|
+
const facadeName = resolver.resolveClassName(sdk.name);
|
|
974
|
+
const members = controllers.map(({ name, tag }) => ({
|
|
975
|
+
className: name,
|
|
976
|
+
propName: resolver.resolveClientPropertyName(tag ?? name)
|
|
977
|
+
}));
|
|
978
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [classFiles, /* @__PURE__ */ jsxs(File, {
|
|
979
|
+
baseName: sdkFile.baseName,
|
|
980
|
+
path: sdkFile.path,
|
|
981
|
+
meta: sdkFile.meta,
|
|
982
|
+
banner: banner(sdkFile),
|
|
983
|
+
footer: footer(sdkFile),
|
|
984
|
+
children: [
|
|
985
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
986
|
+
name: ["ClientConfig"],
|
|
987
|
+
root: sdkFile.path,
|
|
988
|
+
path: clientPath,
|
|
989
|
+
isTypeOnly: true
|
|
990
|
+
}),
|
|
991
|
+
controllers.map(({ name, file }) => /* @__PURE__ */ jsx(File.Import, {
|
|
992
|
+
name: [name],
|
|
993
|
+
root: sdkFile.path,
|
|
994
|
+
path: file.path
|
|
995
|
+
}, name)),
|
|
996
|
+
/* @__PURE__ */ jsx(SdkFacade, {
|
|
997
|
+
name: facadeName,
|
|
998
|
+
members
|
|
999
|
+
})
|
|
1000
|
+
]
|
|
1001
|
+
}, sdkFile.path)] });
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
//#endregion
|
|
1006
|
+
//#region ../../internals/client/src/macros.ts
|
|
1007
|
+
/**
|
|
1008
|
+
* Macros the client plugins apply by default, ahead of any user macros. `macroSimplifyUnion`
|
|
1009
|
+
* drops union members a broader scalar already covers, keeping the generated response and error
|
|
1010
|
+
* unions tidy. A plugin wires them with `ctx.setMacros([...defaultMacros, ...userMacros])`.
|
|
1011
|
+
*/
|
|
1012
|
+
const defaultMacros = [macroSimplifyUnion];
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region ../../internals/client/src/resolver.ts
|
|
1015
|
+
/**
|
|
1016
|
+
* Default resolver shared by the client plugins. Functions and files use camelCase; classes and
|
|
1017
|
+
* tag groups use PascalCase.
|
|
1018
|
+
*
|
|
1019
|
+
* @example
|
|
1020
|
+
* ```ts
|
|
1021
|
+
* resolverClient.resolveName('show pet by id') // 'showPetById'
|
|
1022
|
+
* resolverClient.resolveGroupName('pet') // 'PetClient'
|
|
1023
|
+
* ```
|
|
1024
|
+
*/
|
|
1025
|
+
const resolverClient = defineResolver(() => ({
|
|
1026
|
+
name: "default",
|
|
1027
|
+
pluginName: "plugin-contract-client",
|
|
1028
|
+
default(name, type) {
|
|
1029
|
+
if (type === "file") return toFilePath(name);
|
|
1030
|
+
return ensureValidVarName(camelCase(name));
|
|
1031
|
+
},
|
|
1032
|
+
resolveName(name) {
|
|
1033
|
+
return this.default(name, "function");
|
|
1034
|
+
},
|
|
1035
|
+
resolvePathName(name, type) {
|
|
1036
|
+
return this.default(name, type);
|
|
1037
|
+
},
|
|
1038
|
+
resolveClassName(name) {
|
|
1039
|
+
return ensureValidVarName(pascalCase(name));
|
|
1040
|
+
},
|
|
1041
|
+
resolveGroupName(name) {
|
|
1042
|
+
return ensureValidVarName(pascalCase(`${name} Client`));
|
|
1043
|
+
},
|
|
1044
|
+
resolveClientPropertyName(name) {
|
|
1045
|
+
return ensureValidVarName(camelCase(name));
|
|
1046
|
+
}
|
|
1047
|
+
}));
|
|
1048
|
+
//#endregion
|
|
1049
|
+
//#region src/generators/clientGenerator.tsx
|
|
1050
|
+
/**
|
|
1051
|
+
* Built-in operation generator for `@kubb/plugin-fetch`. Emits one async function per OpenAPI
|
|
1052
|
+
* operation using the shared `Operation` component: a grouped `<Name>Request` type and a function that
|
|
1053
|
+
* forwards a single `options` object to the bundled `client` and returns the `RequestResult`.
|
|
1054
|
+
*/
|
|
1055
|
+
const clientGenerator = defineGenerator({
|
|
1056
|
+
name: "fetch",
|
|
1057
|
+
renderer: jsxRenderer,
|
|
1058
|
+
operation(node, ctx) {
|
|
1059
|
+
if (!ast.isHttpOperationNode(node)) return null;
|
|
1060
|
+
const { config, driver, resolver, root } = ctx;
|
|
1061
|
+
const { output, parser, group } = ctx.options;
|
|
1062
|
+
const pluginTs = driver.getPlugin(pluginTsName);
|
|
1063
|
+
if (!pluginTs) return null;
|
|
1064
|
+
const tsResolver = driver.getResolver(pluginTsName);
|
|
1065
|
+
const pluginZod = resolveResponseParser(parser) === "zod" || resolveRequestParser(parser) === "zod" ? driver.getPlugin(pluginZodName) : null;
|
|
1066
|
+
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
1067
|
+
const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
|
|
1068
|
+
const importedTypeNames = [tsResolver.resolveRequestConfigName(node), tsResolver.resolveResponsesName(node)];
|
|
1069
|
+
const importedZodNames = zodResolver ? [resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null, resolveRequestParser(parser) === "zod" && hasRequestBody ? zodResolver.resolveDataName?.(node) : null].filter((name) => Boolean(name)) : [];
|
|
1070
|
+
const meta = {
|
|
1071
|
+
name: resolver.resolveName(node.operationId),
|
|
1072
|
+
file: resolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1073
|
+
root,
|
|
1074
|
+
output,
|
|
1075
|
+
group: group ?? void 0
|
|
1076
|
+
}),
|
|
1077
|
+
fileTs: tsResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1078
|
+
root,
|
|
1079
|
+
output: pluginTs.options?.output ?? output,
|
|
1080
|
+
group: pluginTs.options?.group ?? void 0
|
|
1081
|
+
}),
|
|
1082
|
+
fileZod: zodResolver && pluginZod?.options ? zodResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1083
|
+
root,
|
|
1084
|
+
output: pluginZod.options.output ?? output,
|
|
1085
|
+
group: pluginZod.options?.group ?? void 0
|
|
1086
|
+
}) : null
|
|
1087
|
+
};
|
|
1088
|
+
const security = getOperationSecurity({
|
|
1089
|
+
document: ctx.adapter.document,
|
|
1090
|
+
method: node.method,
|
|
1091
|
+
path: node.path
|
|
1092
|
+
});
|
|
1093
|
+
const clientPath = path.resolve(root, ".kubb/client.ts");
|
|
1094
|
+
return /* @__PURE__ */ jsxs(File, {
|
|
1095
|
+
baseName: meta.file.baseName,
|
|
1096
|
+
path: meta.file.path,
|
|
1097
|
+
meta: meta.file.meta,
|
|
1098
|
+
banner: resolver.resolveBanner(ctx.meta, {
|
|
1099
|
+
output,
|
|
1100
|
+
config,
|
|
1101
|
+
file: {
|
|
1102
|
+
path: meta.file.path,
|
|
1103
|
+
baseName: meta.file.baseName
|
|
1104
|
+
}
|
|
1105
|
+
}),
|
|
1106
|
+
footer: resolver.resolveFooter(ctx.meta, {
|
|
1107
|
+
output,
|
|
1108
|
+
config,
|
|
1109
|
+
file: {
|
|
1110
|
+
path: meta.file.path,
|
|
1111
|
+
baseName: meta.file.baseName
|
|
1112
|
+
}
|
|
1113
|
+
}),
|
|
1114
|
+
children: [
|
|
1115
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
1116
|
+
name: ["client"],
|
|
1117
|
+
root: meta.file.path,
|
|
1118
|
+
path: clientPath
|
|
1119
|
+
}),
|
|
1120
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
1121
|
+
name: ["Options", "RequestResult"],
|
|
1122
|
+
root: meta.file.path,
|
|
1123
|
+
path: clientPath,
|
|
1124
|
+
isTypeOnly: true
|
|
1125
|
+
}),
|
|
1126
|
+
meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
1127
|
+
name: Array.from(new Set(importedTypeNames)),
|
|
1128
|
+
root: meta.file.path,
|
|
1129
|
+
path: meta.fileTs.path,
|
|
1130
|
+
isTypeOnly: true
|
|
1131
|
+
}),
|
|
1132
|
+
meta.fileZod && importedZodNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
1133
|
+
name: importedZodNames,
|
|
1134
|
+
root: meta.file.path,
|
|
1135
|
+
path: meta.fileZod.path
|
|
1136
|
+
}),
|
|
1137
|
+
/* @__PURE__ */ jsx(Operation, {
|
|
1138
|
+
name: meta.name,
|
|
1139
|
+
node,
|
|
1140
|
+
tsResolver,
|
|
1141
|
+
zodResolver,
|
|
1142
|
+
parser,
|
|
1143
|
+
security
|
|
1144
|
+
})
|
|
1145
|
+
]
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
});
|
|
1149
|
+
//#endregion
|
|
1150
|
+
//#region src/templates.ts
|
|
1151
|
+
/**
|
|
1152
|
+
* Absolute path to the fetch client runtime template, resolved relative to this package's own
|
|
1153
|
+
* location so it stays correct no matter which package imports it. Pass it to a file node's `copy`
|
|
1154
|
+
* field to emit the runtime into the generated `.kubb/client.ts` verbatim.
|
|
1155
|
+
*/
|
|
1156
|
+
const fetchClientTemplatePath = fileURLToPath(new URL("../templates/fetch.ts", import.meta.url));
|
|
1157
|
+
//#endregion
|
|
1158
|
+
//#region src/plugin.ts
|
|
1159
|
+
/**
|
|
1160
|
+
* Canonical plugin name for `@kubb/plugin-fetch`. Used for driver lookups and cross-plugin
|
|
1161
|
+
* dependency references.
|
|
1162
|
+
*/
|
|
1163
|
+
const pluginFetchName = "plugin-fetch";
|
|
1164
|
+
/**
|
|
1165
|
+
* Generates a type-safe HTTP client pinned to the Fetch API. Each operation becomes one async
|
|
1166
|
+
* function that takes a single grouped `options` object and returns the shared `RequestResult`
|
|
1167
|
+
* contract. The runtime is always bundled into `.kubb/client.ts`, so generated code never imports
|
|
1168
|
+
* from `@kubb/plugin-fetch` and the only runtime dependency is the global `fetch`.
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* ```ts
|
|
1172
|
+
* import { defineConfig } from 'kubb'
|
|
1173
|
+
* import { pluginTs } from '@kubb/plugin-ts'
|
|
1174
|
+
* import { pluginFetch } from '@kubb/plugin-fetch'
|
|
1175
|
+
*
|
|
1176
|
+
* export default defineConfig({
|
|
1177
|
+
* input: { path: './petStore.yaml' },
|
|
1178
|
+
* output: { path: './src/gen' },
|
|
1179
|
+
* plugins: [
|
|
1180
|
+
* pluginTs(),
|
|
1181
|
+
* pluginFetch({ output: { path: './clients' } }),
|
|
1182
|
+
* ],
|
|
1183
|
+
* })
|
|
1184
|
+
* ```
|
|
1185
|
+
*/
|
|
1186
|
+
const pluginFetch = definePlugin((options) => {
|
|
1187
|
+
const { output = {
|
|
1188
|
+
path: "clients",
|
|
1189
|
+
barrel: { type: "named" }
|
|
1190
|
+
}, exclude = [], include, override = [], baseURL, parser = false, group, sdk, resolver: userResolver } = options;
|
|
1191
|
+
const resolved = {
|
|
1192
|
+
output,
|
|
1193
|
+
exclude,
|
|
1194
|
+
include,
|
|
1195
|
+
override,
|
|
1196
|
+
group: createGroupConfig(group),
|
|
1197
|
+
baseURL,
|
|
1198
|
+
parser,
|
|
1199
|
+
sdk: sdk ? {
|
|
1200
|
+
mode: sdk.mode ?? "tag",
|
|
1201
|
+
name: sdk.name
|
|
1202
|
+
} : void 0,
|
|
1203
|
+
resolver: userResolver ? {
|
|
1204
|
+
...resolverClient,
|
|
1205
|
+
...userResolver
|
|
1206
|
+
} : resolverClient
|
|
1207
|
+
};
|
|
1208
|
+
const selectedGenerators = resolved.sdk ? [createSdkGenerator()] : [clientGenerator];
|
|
1209
|
+
return {
|
|
1210
|
+
name: pluginFetchName,
|
|
1211
|
+
options,
|
|
1212
|
+
dependencies: [pluginTsName, isParserEnabled(resolved.parser) ? pluginZodName : null].filter((dependency) => Boolean(dependency)),
|
|
1213
|
+
hooks: { "kubb:plugin:setup"(ctx) {
|
|
1214
|
+
ctx.setOptions(resolved);
|
|
1215
|
+
ctx.setResolver(resolved.resolver);
|
|
1216
|
+
ctx.setMacros([...defaultMacros, ...options.macros ?? []]);
|
|
1217
|
+
for (const gen of selectedGenerators) ctx.addGenerator(gen);
|
|
1218
|
+
const root = path.resolve(ctx.config.root, ctx.config.output.path);
|
|
1219
|
+
ctx.injectFile({
|
|
1220
|
+
baseName: "client.ts",
|
|
1221
|
+
path: path.resolve(root, ".kubb/client.ts"),
|
|
1222
|
+
copy: fetchClientTemplatePath,
|
|
1223
|
+
footer: baseURL ? `client.setConfig({ baseURL: ${JSON.stringify(baseURL)} })` : void 0
|
|
1224
|
+
});
|
|
1225
|
+
} }
|
|
1226
|
+
};
|
|
1227
|
+
});
|
|
1228
|
+
//#endregion
|
|
1229
|
+
export { clientGenerator, pluginFetch as default, pluginFetch, pluginFetchName };
|
|
1230
|
+
|
|
1231
|
+
//# sourceMappingURL=index.js.map
|