@kubb/plugin-client 5.0.0-beta.56 → 5.5.2
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 +8 -61
- package/dist/index.cjs +754 -1745
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +170 -349
- package/dist/index.js +733 -1733
- package/dist/index.js.map +1 -1
- package/package.json +10 -63
- package/src/generators/clientGenerator.tsx +6 -132
- package/src/index.ts +1 -9
- package/src/plugin.ts +32 -122
- package/src/types.ts +27 -249
- package/dist/chunk-Bx3C2hgW.cjs +0 -38
- package/dist/clients/axios.cjs +0 -68
- package/dist/clients/axios.cjs.map +0 -1
- package/dist/clients/axios.d.ts +0 -49
- package/dist/clients/axios.js +0 -58
- package/dist/clients/axios.js.map +0 -1
- package/dist/clients/fetch.cjs +0 -128
- package/dist/clients/fetch.cjs.map +0 -1
- package/dist/clients/fetch.d.ts +0 -50
- package/dist/clients/fetch.js +0 -120
- package/dist/clients/fetch.js.map +0 -1
- package/dist/templates/clients/axios.source.cjs +0 -7
- package/dist/templates/clients/axios.source.cjs.map +0 -1
- package/dist/templates/clients/axios.source.d.ts +0 -7
- package/dist/templates/clients/axios.source.js +0 -6
- package/dist/templates/clients/axios.source.js.map +0 -1
- package/dist/templates/clients/fetch.source.cjs +0 -7
- package/dist/templates/clients/fetch.source.cjs.map +0 -1
- package/dist/templates/clients/fetch.source.d.ts +0 -7
- package/dist/templates/clients/fetch.source.js +0 -6
- package/dist/templates/clients/fetch.source.js.map +0 -1
- package/dist/templates/config.source.cjs +0 -7
- package/dist/templates/config.source.cjs.map +0 -1
- package/dist/templates/config.source.d.ts +0 -7
- package/dist/templates/config.source.js +0 -6
- package/dist/templates/config.source.js.map +0 -1
- package/src/clients/axios.ts +0 -113
- package/src/clients/fetch.ts +0 -201
- package/src/components/ClassClient.tsx +0 -161
- package/src/components/Client.tsx +0 -281
- package/src/components/StaticClassClient.tsx +0 -153
- package/src/components/Url.tsx +0 -90
- package/src/components/WrapperClient.tsx +0 -33
- package/src/functionParams.ts +0 -118
- package/src/generators/classClientGenerator.tsx +0 -261
- package/src/generators/groupedClientGenerator.tsx +0 -82
- package/src/generators/operationsGenerator.ts +0 -47
- package/src/generators/staticClassClientGenerator.tsx +0 -240
- package/src/resolvers/resolverClient.ts +0 -46
- package/src/templates/clients/axios.source.ts +0 -4
- package/src/templates/clients/fetch.source.ts +0 -4
- package/src/templates/config.source.ts +0 -4
- package/src/utils.ts +0 -259
- /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,14 +1,216 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import { source as source$1 } from "./templates/clients/fetch.source.js";
|
|
4
|
-
import { source as source$2 } from "./templates/config.source.js";
|
|
1
|
+
import "./rolldown-runtime-C0LytTxp.js";
|
|
2
|
+
import { Resolver, Url, ast, createResolver, defineGenerator, definePlugin, macroSimplifyUnion } from "kubb/kit";
|
|
5
3
|
import path from "node:path";
|
|
6
|
-
import {
|
|
7
|
-
import { buildJSDoc, stringify } from "@kubb/ast/utils";
|
|
8
|
-
import { functionPrinter, pluginTsName } from "@kubb/plugin-ts";
|
|
9
|
-
import { Const, File, Function, jsxRenderer } from "@kubb/renderer-jsx";
|
|
10
|
-
import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
|
|
4
|
+
import { createFunctionParameter, createFunctionParameters, functionPrinter, pluginTsName } from "@kubb/plugin-ts";
|
|
11
5
|
import { pluginZodName } from "@kubb/plugin-zod";
|
|
6
|
+
import { File, Function, jsxRenderer } from "kubb/jsx";
|
|
7
|
+
import { jsx, jsxs } from "kubb/jsx/jsx-runtime";
|
|
8
|
+
//#region ../../internals/shared/src/params.ts
|
|
9
|
+
/**
|
|
10
|
+
* Drops parameters that share the same name, keeping the first.
|
|
11
|
+
*
|
|
12
|
+
* A malformed spec can declare the same parameter name twice within one `in` location. Both would
|
|
13
|
+
* resolve to the same output property, so emitting both would yield an object type with a duplicate
|
|
14
|
+
* member, which TypeScript rejects. This is a defensive guard against that case, not a casing guard:
|
|
15
|
+
* parameter names flow through unchanged, so no two distinct names ever collide here anymore.
|
|
16
|
+
*/
|
|
17
|
+
function dedupeParams(params) {
|
|
18
|
+
const seen = /* @__PURE__ */ new Set();
|
|
19
|
+
return params.filter((param) => {
|
|
20
|
+
if (seen.has(param.name)) return false;
|
|
21
|
+
seen.add(param.name);
|
|
22
|
+
return true;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region ../../internals/shared/src/operation.ts
|
|
27
|
+
/**
|
|
28
|
+
* Builds the `ResolverFileParams` every operation generator passes to
|
|
29
|
+
* `resolver.file`: a file named `name`, tagged by the operation's first
|
|
30
|
+
* tag (or `'default'`), at the operation's path. Centralizes the entry object
|
|
31
|
+
* that was repeated at dozens of call sites across the client and query plugins.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
function operationFileEntry(node, name, extname = ".ts") {
|
|
39
|
+
return {
|
|
40
|
+
name,
|
|
41
|
+
extname,
|
|
42
|
+
tag: node.tags[0] ?? "default",
|
|
43
|
+
path: node.path
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolves a dependency plugin's generated file for `node.operationId`, cached in `cache` (the
|
|
48
|
+
* current node's `ctx.cache`) under the resolver's own plugin name. Several dependents reading the
|
|
49
|
+
* same dependency for the same operation in one pass (a query plugin's several hook generators, the
|
|
50
|
+
* MCP handler, ...) share one computed name and path instead of each calling `resolver.file` again.
|
|
51
|
+
*
|
|
52
|
+
* @example Cache `plugin-ts`'s file for the current operation
|
|
53
|
+
* ```ts
|
|
54
|
+
* const fileTs = resolveDependencyOperationFile({ cache: ctx.cache, node, resolver: tsResolver, root, output })
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
function resolveDependencyOperationFile(options) {
|
|
58
|
+
const { cache, node, resolver, root, output, group } = options;
|
|
59
|
+
return cache.ensureItem(`${resolver.pluginName}:operationFile`, () => resolver.file({
|
|
60
|
+
...operationFileEntry(node, node.operationId),
|
|
61
|
+
root,
|
|
62
|
+
output,
|
|
63
|
+
group: group ?? void 0
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
function getOperationLink(node, link) {
|
|
67
|
+
if (!link) return null;
|
|
68
|
+
if (typeof link === "function") return link(node) ?? null;
|
|
69
|
+
return node.path ? `{@link ${Url.toPath(node.path)}}` : null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Derives the shared `ContentTypeInfo` shape from a list of content types, tracking whether several
|
|
73
|
+
* are present and the union, default, and form-data flags the client uses to pick one.
|
|
74
|
+
*/
|
|
75
|
+
function buildContentTypeInfo(contentTypes) {
|
|
76
|
+
const isMultipleContentTypes = contentTypes.length > 1;
|
|
77
|
+
return {
|
|
78
|
+
contentTypes,
|
|
79
|
+
isMultipleContentTypes,
|
|
80
|
+
contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
|
|
81
|
+
defaultContentType: contentTypes[0] ?? "application/json",
|
|
82
|
+
hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function getContentTypeInfo(node) {
|
|
86
|
+
return buildContentTypeInfo(node.requestBody?.content?.map((e) => e.contentType) ?? []);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The request-body counterpart for the primary success response: the content types it documents and
|
|
90
|
+
* whether several are present, so the client can let a caller pick which one to accept.
|
|
91
|
+
*/
|
|
92
|
+
function getResponseContentTypeInfo(node) {
|
|
93
|
+
return buildContentTypeInfo(getPrimarySuccessResponse(node)?.content?.map((e) => e.contentType) ?? []);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Reads the single base content type of an operation's primary success response, lowercased and
|
|
97
|
+
* stripped of any `; charset=...` suffix. Returns `undefined` when the response declares zero or
|
|
98
|
+
* more than one content type, since neither case has a single type to act on.
|
|
99
|
+
*/
|
|
100
|
+
function getPrimarySuccessContentType(node) {
|
|
101
|
+
const contentTypes = getPrimarySuccessResponse(node)?.content?.map((entry) => entry.contentType) ?? [];
|
|
102
|
+
if (contentTypes.length !== 1) return void 0;
|
|
103
|
+
return contentTypes[0].split(";")[0].trim().toLowerCase();
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Whether an operation streams its primary success response as Server-Sent Events
|
|
107
|
+
* (`text/event-stream`). The client generator uses this to return a typed event stream instead of a
|
|
108
|
+
* one-shot `RequestResult`.
|
|
109
|
+
*/
|
|
110
|
+
function isEventStream(node) {
|
|
111
|
+
return getPrimarySuccessContentType(node) === "text/event-stream";
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Derives the default `responseType` for an operation from its primary success response.
|
|
115
|
+
*
|
|
116
|
+
* Returns a value only when that response declares a single non-JSON content type. `text/event-stream`
|
|
117
|
+
* and other binary types (`application/octet-stream`, `application/pdf`, `image/*`, `audio/*`,
|
|
118
|
+
* `video/*`) map to a stream or `'blob'`, and other `text/*` maps to `'text'`. Otherwise `undefined`,
|
|
119
|
+
* leaving the runtime client's `Content-Type` auto-detection in charge.
|
|
120
|
+
*/
|
|
121
|
+
function getResponseType(node) {
|
|
122
|
+
const baseType = getPrimarySuccessContentType(node);
|
|
123
|
+
if (!baseType) return void 0;
|
|
124
|
+
if (baseType === "application/json" || baseType.endsWith("+json") || baseType === "text/json") return void 0;
|
|
125
|
+
if (baseType === "text/event-stream") return "stream";
|
|
126
|
+
if (baseType.startsWith("text/")) return "text";
|
|
127
|
+
if (baseType === "application/octet-stream" || baseType === "application/pdf" || /^(image|audio|video)\//.test(baseType)) return "blob";
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Which of the grouped request options an operation carries.
|
|
131
|
+
*/
|
|
132
|
+
function getRequestGroups(node) {
|
|
133
|
+
const { path, query, header } = getOperationParameters(node);
|
|
134
|
+
return {
|
|
135
|
+
path: path.length > 0,
|
|
136
|
+
query: query.length > 0,
|
|
137
|
+
body: Boolean(node.requestBody?.content?.[0]?.schema),
|
|
138
|
+
headers: header.length > 0
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Resolves which grouped request options an operation carries together with whether each group
|
|
143
|
+
* holds a required member. The grouped parameter stays optional only when nothing inside it is
|
|
144
|
+
* required, matching the generated `RequestConfig` type.
|
|
145
|
+
*/
|
|
146
|
+
function getRequestGroupOptionality(node) {
|
|
147
|
+
const groups = getRequestGroups(node);
|
|
148
|
+
const { path, query, header } = getOperationParameters(node);
|
|
149
|
+
const hasRequiredPath = path.some((param) => param.required);
|
|
150
|
+
const hasRequiredQuery = query.some((param) => param.required);
|
|
151
|
+
const hasRequiredHeader = header.some((param) => param.required);
|
|
152
|
+
return {
|
|
153
|
+
groups,
|
|
154
|
+
hasRequiredPath,
|
|
155
|
+
hasRequiredQuery,
|
|
156
|
+
hasRequiredHeader,
|
|
157
|
+
isOptional: !hasRequiredPath && !hasRequiredQuery && !hasRequiredHeader && !groups.body
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function buildOperationComments(node, options = {}) {
|
|
161
|
+
const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
|
|
162
|
+
const linkComment = getOperationLink(node, link);
|
|
163
|
+
const filteredComments = (linkPosition === "beforeDeprecated" ? [
|
|
164
|
+
node.description && `@description ${node.description}`,
|
|
165
|
+
node.summary && `@summary ${node.summary}`,
|
|
166
|
+
linkComment,
|
|
167
|
+
node.deprecated && "@deprecated"
|
|
168
|
+
] : [
|
|
169
|
+
node.description && `@description ${node.description}`,
|
|
170
|
+
node.summary && `@summary ${node.summary}`,
|
|
171
|
+
node.deprecated && "@deprecated",
|
|
172
|
+
linkComment
|
|
173
|
+
]).filter((comment) => Boolean(comment));
|
|
174
|
+
if (!splitLines) return filteredComments;
|
|
175
|
+
return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
|
|
176
|
+
}
|
|
177
|
+
const operationParameterGroupsByNode = /* @__PURE__ */ new WeakMap();
|
|
178
|
+
/**
|
|
179
|
+
* Groups an operation's parameters by location (`path`/`query`/`header`/`cookie`), deduping each
|
|
180
|
+
* group by name. Every plugin generator visiting the same `OperationNode` shares one AST instance
|
|
181
|
+
* (see `KubbDriver`), so the result is cached per node to avoid re-filtering and re-deduping the
|
|
182
|
+
* same parameters once per plugin.
|
|
183
|
+
*/
|
|
184
|
+
function getOperationParameters(node) {
|
|
185
|
+
const cached = operationParameterGroupsByNode.get(node);
|
|
186
|
+
if (cached) return cached;
|
|
187
|
+
const groups = {
|
|
188
|
+
path: dedupeParams(node.parameters.filter((param) => param.in === "path")),
|
|
189
|
+
query: dedupeParams(node.parameters.filter((param) => param.in === "query")),
|
|
190
|
+
header: dedupeParams(node.parameters.filter((param) => param.in === "header")),
|
|
191
|
+
cookie: dedupeParams(node.parameters.filter((param) => param.in === "cookie"))
|
|
192
|
+
};
|
|
193
|
+
operationParameterGroupsByNode.set(node, groups);
|
|
194
|
+
return groups;
|
|
195
|
+
}
|
|
196
|
+
function getStatusCodeNumber(statusCode) {
|
|
197
|
+
const code = Number(statusCode);
|
|
198
|
+
return Number.isNaN(code) ? null : code;
|
|
199
|
+
}
|
|
200
|
+
function isSuccessStatusCode(statusCode) {
|
|
201
|
+
const code = getStatusCodeNumber(statusCode);
|
|
202
|
+
return code !== null && code >= 200 && code < 300;
|
|
203
|
+
}
|
|
204
|
+
function getSuccessResponses(responses) {
|
|
205
|
+
return responses.filter((response) => isSuccessStatusCode(response.statusCode));
|
|
206
|
+
}
|
|
207
|
+
function getOperationSuccessResponses(node) {
|
|
208
|
+
return getSuccessResponses(node.responses);
|
|
209
|
+
}
|
|
210
|
+
function getPrimarySuccessResponse(node) {
|
|
211
|
+
return getOperationSuccessResponses(node)[0] ?? null;
|
|
212
|
+
}
|
|
213
|
+
//#endregion
|
|
12
214
|
//#region ../../internals/utils/src/casing.ts
|
|
13
215
|
/**
|
|
14
216
|
* Shared implementation for camelCase and PascalCase conversion.
|
|
@@ -48,37 +250,12 @@ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
|
|
|
48
250
|
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
49
251
|
}
|
|
50
252
|
//#endregion
|
|
51
|
-
//#region ../../internals/utils/src/fs.ts
|
|
52
|
-
/**
|
|
53
|
-
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
54
|
-
* (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
|
|
55
|
-
* every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
|
|
56
|
-
*
|
|
57
|
-
* Empty segments are dropped before joining. They arise when the name starts with a dot
|
|
58
|
-
* followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
|
|
59
|
-
* an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
|
|
60
|
-
* absolute path, letting generated files escape the configured output directory.
|
|
61
|
-
*
|
|
62
|
-
* @example Nested path from a dotted name
|
|
63
|
-
* `toFilePath('pet.petId') // 'pet/petId'`
|
|
64
|
-
*
|
|
65
|
-
* @example PascalCase the final segment
|
|
66
|
-
* `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
|
|
67
|
-
*
|
|
68
|
-
* @example Suffix applied to the final segment only
|
|
69
|
-
* `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
|
|
70
|
-
*/
|
|
71
|
-
function toFilePath(name, caseLast = camelCase) {
|
|
72
|
-
const parts = name.split(/\.(?=[a-zA-Z])/);
|
|
73
|
-
return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
|
|
74
|
-
}
|
|
75
|
-
//#endregion
|
|
76
253
|
//#region ../../internals/utils/src/reserved.ts
|
|
77
254
|
/**
|
|
78
255
|
* JavaScript and Java reserved words.
|
|
79
256
|
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
80
257
|
*/
|
|
81
|
-
const reservedWords = new Set([
|
|
258
|
+
const reservedWords = /* @__PURE__ */ new Set([
|
|
82
259
|
"abstract",
|
|
83
260
|
"arguments",
|
|
84
261
|
"boolean",
|
|
@@ -173,7 +350,7 @@ const reservedWords = new Set([
|
|
|
173
350
|
*/
|
|
174
351
|
function isValidVarName(name) {
|
|
175
352
|
if (!name || reservedWords.has(name)) return false;
|
|
176
|
-
return
|
|
353
|
+
return isIdentifier(name);
|
|
177
354
|
}
|
|
178
355
|
/**
|
|
179
356
|
* Returns `name` when it's a syntactically valid JavaScript variable name,
|
|
@@ -195,252 +372,21 @@ function ensureValidVarName(name) {
|
|
|
195
372
|
if (!name || isValidVarName(name)) return name;
|
|
196
373
|
return `_${name}`;
|
|
197
374
|
}
|
|
198
|
-
//#endregion
|
|
199
|
-
//#region ../../internals/utils/src/url.ts
|
|
200
|
-
function transformParam(raw, casing) {
|
|
201
|
-
const param = isValidVarName(raw) ? raw : camelCase(raw);
|
|
202
|
-
return casing === "camelcase" ? camelCase(param) : param;
|
|
203
|
-
}
|
|
204
|
-
function toParamsObject(path, { replacer, casing } = {}) {
|
|
205
|
-
const params = {};
|
|
206
|
-
for (const match of path.matchAll(/\{([^}]+)\}/g)) {
|
|
207
|
-
const param = transformParam(match[1], casing);
|
|
208
|
-
const key = replacer ? replacer(param) : param;
|
|
209
|
-
params[key] = key;
|
|
210
|
-
}
|
|
211
|
-
return Object.keys(params).length > 0 ? params : null;
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.
|
|
215
|
-
*/
|
|
216
|
-
var Url$1 = class Url$1 {
|
|
217
|
-
static {
|
|
218
|
-
__name(this, "Url");
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.
|
|
222
|
-
*
|
|
223
|
-
* @example
|
|
224
|
-
* Url.canParse('https://petstore.swagger.io/v2') // true
|
|
225
|
-
* Url.canParse('/pet/{petId}') // false
|
|
226
|
-
*/
|
|
227
|
-
static canParse(url, base) {
|
|
228
|
-
return URL.canParse(url, base);
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* Converts an OpenAPI/Swagger path to Express-style colon syntax.
|
|
232
|
-
*
|
|
233
|
-
* @example
|
|
234
|
-
* Url.toPath('/pet/{petId}') // '/pet/:petId'
|
|
235
|
-
*/
|
|
236
|
-
static toPath(path) {
|
|
237
|
-
return path.replace(/\{([^}]+)\}/g, ":$1");
|
|
238
|
-
}
|
|
239
|
-
/**
|
|
240
|
-
* Converts an OpenAPI/Swagger path to a TypeScript template literal string.
|
|
241
|
-
* `prefix` is prepended inside the literal, `replacer` transforms each parameter name,
|
|
242
|
-
* and `casing` controls parameter identifier casing.
|
|
243
|
-
*
|
|
244
|
-
* @example
|
|
245
|
-
* Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'
|
|
246
|
-
*
|
|
247
|
-
* @example
|
|
248
|
-
* Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'
|
|
249
|
-
*/
|
|
250
|
-
static toTemplateString(path, { prefix, replacer, casing } = {}) {
|
|
251
|
-
const result = path.split(/\{([^}]+)\}/).map((part, i) => {
|
|
252
|
-
if (i % 2 === 0) return part;
|
|
253
|
-
const param = transformParam(part, casing);
|
|
254
|
-
return `\${${replacer ? replacer(param) : param}}`;
|
|
255
|
-
}).join("");
|
|
256
|
-
return `\`${prefix ?? ""}${result}\``;
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Returns the path and its extracted params as a structured `URLObject`, or as a stringified
|
|
260
|
-
* expression when `stringify` is set.
|
|
261
|
-
*
|
|
262
|
-
* @example
|
|
263
|
-
* Url.toObject('/pet/{petId}')
|
|
264
|
-
* // { url: '/pet/:petId', params: { petId: 'petId' } }
|
|
265
|
-
*/
|
|
266
|
-
static toObject(path, { type = "path", replacer, stringify, casing } = {}) {
|
|
267
|
-
const object = {
|
|
268
|
-
url: type === "path" ? Url$1.toPath(path) : Url$1.toTemplateString(path, {
|
|
269
|
-
replacer,
|
|
270
|
-
casing
|
|
271
|
-
}),
|
|
272
|
-
params: toParamsObject(path, {
|
|
273
|
-
replacer,
|
|
274
|
-
casing
|
|
275
|
-
})
|
|
276
|
-
};
|
|
277
|
-
if (stringify) {
|
|
278
|
-
if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
|
|
279
|
-
if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
|
|
280
|
-
return `{ url: '${object.url}' }`;
|
|
281
|
-
}
|
|
282
|
-
return object;
|
|
283
|
-
}
|
|
284
|
-
};
|
|
285
|
-
//#endregion
|
|
286
|
-
//#region ../../internals/shared/src/operation.ts
|
|
287
375
|
/**
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
*
|
|
376
|
+
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
|
|
377
|
+
*
|
|
378
|
+
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
|
|
379
|
+
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
|
|
380
|
+
* deciding whether an object key needs quoting.
|
|
292
381
|
*
|
|
293
382
|
* @example
|
|
294
383
|
* ```ts
|
|
295
|
-
*
|
|
384
|
+
* isIdentifier('name') // true
|
|
385
|
+
* isIdentifier('x-total')// false
|
|
296
386
|
* ```
|
|
297
387
|
*/
|
|
298
|
-
function
|
|
299
|
-
return
|
|
300
|
-
name,
|
|
301
|
-
extname,
|
|
302
|
-
tag: node.tags[0] ?? "default",
|
|
303
|
-
path: node.path
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
function getOperationLink(node, link) {
|
|
307
|
-
if (!link) return null;
|
|
308
|
-
if (typeof link === "function") return link(node) ?? null;
|
|
309
|
-
if (link === "urlPath") return node.path ? `{@link ${Url$1.toPath(node.path)}}` : null;
|
|
310
|
-
return node.path ? `{@link ${node.path.replaceAll("{", ":").replaceAll("}", "")}}` : null;
|
|
311
|
-
}
|
|
312
|
-
function getContentTypeInfo(node) {
|
|
313
|
-
const contentTypes = node.requestBody?.content?.map((e) => e.contentType) ?? [];
|
|
314
|
-
const isMultipleContentTypes = contentTypes.length > 1;
|
|
315
|
-
return {
|
|
316
|
-
contentTypes,
|
|
317
|
-
isMultipleContentTypes,
|
|
318
|
-
contentTypeUnion: isMultipleContentTypes ? contentTypes.map((ct) => JSON.stringify(ct)).join(" | ") : "",
|
|
319
|
-
defaultContentType: contentTypes[0] ?? "application/json",
|
|
320
|
-
hasFormData: contentTypes.some((ct) => ct === "multipart/form-data")
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Derives the default `responseType` for an operation from its primary success response.
|
|
325
|
-
*
|
|
326
|
-
* Returns a value only when that response declares a single non-JSON content type — a binary type
|
|
327
|
-
* (`application/octet-stream`, `application/pdf`, `image/*`, `audio/*`, `video/*`) maps to `'blob'`
|
|
328
|
-
* and other `text/*` maps to `'text'`. Otherwise `undefined`, leaving the runtime client's
|
|
329
|
-
* `Content-Type` auto-detection in charge.
|
|
330
|
-
*/
|
|
331
|
-
function getResponseType(node) {
|
|
332
|
-
const contentTypes = getPrimarySuccessResponse(node)?.content?.map((entry) => entry.contentType) ?? [];
|
|
333
|
-
if (contentTypes.length !== 1) return void 0;
|
|
334
|
-
const baseType = contentTypes[0].split(";")[0].trim().toLowerCase();
|
|
335
|
-
if (baseType === "application/json" || baseType.endsWith("+json") || baseType === "text/json") return void 0;
|
|
336
|
-
if (baseType.startsWith("text/")) return "text";
|
|
337
|
-
if (baseType === "application/octet-stream" || baseType === "application/pdf" || /^(image|audio|video)\//.test(baseType)) return "blob";
|
|
338
|
-
}
|
|
339
|
-
function buildRequestConfigType(node, resolver) {
|
|
340
|
-
const requestName = node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null;
|
|
341
|
-
const { isMultipleContentTypes, contentTypeUnion } = getContentTypeInfo(node);
|
|
342
|
-
return `${requestName ? `Partial<RequestConfig<${requestName}>>` : "Partial<RequestConfig>"} & { ${["client?: Client", isMultipleContentTypes ? `contentType?: ${contentTypeUnion}` : null].filter(Boolean).join("; ")} }`;
|
|
343
|
-
}
|
|
344
|
-
function buildOperationComments(node, options = {}) {
|
|
345
|
-
const { link = "pathTemplate", linkPosition = "afterDeprecated", splitLines = false } = options;
|
|
346
|
-
const linkComment = getOperationLink(node, link);
|
|
347
|
-
const filteredComments = (linkPosition === "beforeDeprecated" ? [
|
|
348
|
-
node.description && `@description ${node.description}`,
|
|
349
|
-
node.summary && `@summary ${node.summary}`,
|
|
350
|
-
linkComment,
|
|
351
|
-
node.deprecated && "@deprecated"
|
|
352
|
-
] : [
|
|
353
|
-
node.description && `@description ${node.description}`,
|
|
354
|
-
node.summary && `@summary ${node.summary}`,
|
|
355
|
-
node.deprecated && "@deprecated",
|
|
356
|
-
linkComment
|
|
357
|
-
]).filter((comment) => Boolean(comment));
|
|
358
|
-
if (!splitLines) return filteredComments;
|
|
359
|
-
return filteredComments.flatMap((text) => text.split(/\r?\n/).map((line) => line.trim())).filter((comment) => Boolean(comment));
|
|
360
|
-
}
|
|
361
|
-
function getOperationParameters(node, options = {}) {
|
|
362
|
-
const params = ast.caseParams(node.parameters, options.paramsCasing);
|
|
363
|
-
return {
|
|
364
|
-
path: params.filter((param) => param.in === "path"),
|
|
365
|
-
query: params.filter((param) => param.in === "query"),
|
|
366
|
-
header: params.filter((param) => param.in === "header"),
|
|
367
|
-
cookie: params.filter((param) => param.in === "cookie")
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
function getStatusCodeNumber(statusCode) {
|
|
371
|
-
const code = Number(statusCode);
|
|
372
|
-
return Number.isNaN(code) ? null : code;
|
|
373
|
-
}
|
|
374
|
-
function isSuccessStatusCode(statusCode) {
|
|
375
|
-
const code = getStatusCodeNumber(statusCode);
|
|
376
|
-
return code !== null && code >= 200 && code < 300;
|
|
377
|
-
}
|
|
378
|
-
function isErrorStatusCode(statusCode) {
|
|
379
|
-
const code = getStatusCodeNumber(statusCode);
|
|
380
|
-
return code !== null && code >= 400;
|
|
381
|
-
}
|
|
382
|
-
function getSuccessResponses(responses) {
|
|
383
|
-
return responses.filter((response) => isSuccessStatusCode(response.statusCode));
|
|
384
|
-
}
|
|
385
|
-
function getOperationSuccessResponses(node) {
|
|
386
|
-
return getSuccessResponses(node.responses);
|
|
387
|
-
}
|
|
388
|
-
function getPrimarySuccessResponse(node) {
|
|
389
|
-
return getOperationSuccessResponses(node)[0] ?? null;
|
|
390
|
-
}
|
|
391
|
-
function resolveErrorNames(node, resolver) {
|
|
392
|
-
return node.responses.filter((response) => isErrorStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
|
|
393
|
-
}
|
|
394
|
-
function resolveSuccessNames(node, resolver) {
|
|
395
|
-
return node.responses.filter((response) => isSuccessStatusCode(response.statusCode)).map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
|
|
396
|
-
}
|
|
397
|
-
function resolveStatusCodeNames(node, resolver) {
|
|
398
|
-
return node.responses.map((response) => resolver.resolveResponseStatusName(node, response.statusCode));
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Builds the discriminated union type string for `dataReturnType: 'full'` return shapes.
|
|
402
|
-
* Each member is `{ status: N; data: StatusNType; statusText: string }`.
|
|
403
|
-
*/
|
|
404
|
-
function buildStatusUnionType(node, resolver) {
|
|
405
|
-
const members = node.responses.map((r) => {
|
|
406
|
-
const typeName = resolver.resolveResponseStatusName(node, r.statusCode);
|
|
407
|
-
const statusCode = Number.parseInt(r.statusCode, 10);
|
|
408
|
-
return `{ status: ${Number.isNaN(statusCode) ? "number" : String(statusCode)}; data: ${typeName}; statusText: string }`;
|
|
409
|
-
});
|
|
410
|
-
if (members.length === 1) return members[0];
|
|
411
|
-
return `(${members.join(" | ")})`;
|
|
412
|
-
}
|
|
413
|
-
const typeNamesByResolver = /* @__PURE__ */ new WeakMap();
|
|
414
|
-
function resolveOperationTypeNames(node, resolver, options = {}) {
|
|
415
|
-
const cacheKey = `${node.operationId}\0${options.paramsCasing ?? ""}\0${options.order ?? ""}\0${options.responseStatusNames ?? ""}\0${(options.exclude ?? []).join(",")}`;
|
|
416
|
-
let byResolver = typeNamesByResolver.get(resolver);
|
|
417
|
-
if (byResolver) {
|
|
418
|
-
const cached = byResolver.get(cacheKey);
|
|
419
|
-
if (cached) return cached;
|
|
420
|
-
} else {
|
|
421
|
-
byResolver = /* @__PURE__ */ new Map();
|
|
422
|
-
typeNamesByResolver.set(resolver, byResolver);
|
|
423
|
-
}
|
|
424
|
-
const { path, query, header } = getOperationParameters(node, { paramsCasing: options.paramsCasing });
|
|
425
|
-
const responseStatusNames = options.responseStatusNames === "error" ? resolveErrorNames(node, resolver) : options.responseStatusNames === false ? [] : resolveStatusCodeNames(node, resolver);
|
|
426
|
-
const exclude = new Set(options.exclude ?? []);
|
|
427
|
-
const paramNames = [
|
|
428
|
-
...path.map((param) => resolver.resolvePathParamsName(node, param)),
|
|
429
|
-
...query.map((param) => resolver.resolveQueryParamsName(node, param)),
|
|
430
|
-
...header.map((param) => resolver.resolveHeaderParamsName(node, param))
|
|
431
|
-
];
|
|
432
|
-
const bodyAndResponseNames = [node.requestBody?.content?.[0]?.schema ? resolver.resolveDataName(node) : null, resolver.resolveResponseName(node)];
|
|
433
|
-
const result = (options.order === "body-response-first" ? [
|
|
434
|
-
...bodyAndResponseNames,
|
|
435
|
-
...paramNames,
|
|
436
|
-
...responseStatusNames
|
|
437
|
-
] : [
|
|
438
|
-
...paramNames,
|
|
439
|
-
...bodyAndResponseNames,
|
|
440
|
-
...responseStatusNames
|
|
441
|
-
]).filter((name) => Boolean(name) && !exclude.has(name));
|
|
442
|
-
byResolver.set(cacheKey, result);
|
|
443
|
-
return result;
|
|
388
|
+
function isIdentifier(name) {
|
|
389
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
444
390
|
}
|
|
445
391
|
//#endregion
|
|
446
392
|
//#region ../../internals/shared/src/group.ts
|
|
@@ -474,1599 +420,653 @@ function createGroupConfig(group) {
|
|
|
474
420
|
};
|
|
475
421
|
}
|
|
476
422
|
//#endregion
|
|
477
|
-
//#region ../../internals/
|
|
478
|
-
function buildParamsMapping(originalParams, mappedParams) {
|
|
479
|
-
const mapping = {};
|
|
480
|
-
let hasChanged = false;
|
|
481
|
-
originalParams.forEach((param, i) => {
|
|
482
|
-
const mappedName = mappedParams[i]?.name ?? param.name;
|
|
483
|
-
mapping[param.name] = mappedName;
|
|
484
|
-
if (param.name !== mappedName) hasChanged = true;
|
|
485
|
-
});
|
|
486
|
-
return hasChanged ? mapping : null;
|
|
487
|
-
}
|
|
488
|
-
//#endregion
|
|
489
|
-
//#region src/functionParams.ts
|
|
490
|
-
const declarationPrinter$4 = functionPrinter({ mode: "declaration" });
|
|
491
|
-
const callPrinter = functionPrinter({ mode: "call" });
|
|
492
|
-
function isGroup(spec) {
|
|
493
|
-
return "children" in spec;
|
|
494
|
-
}
|
|
495
|
-
function createType(type) {
|
|
496
|
-
return type ? ast.createParamsType({
|
|
497
|
-
variant: "reference",
|
|
498
|
-
name: type
|
|
499
|
-
}) : null;
|
|
500
|
-
}
|
|
501
|
-
function createDeclarationLeaf(name, spec) {
|
|
502
|
-
if (spec.default !== void 0) return ast.createFunctionParameter({
|
|
503
|
-
name,
|
|
504
|
-
type: createType(spec.type) ?? void 0,
|
|
505
|
-
default: spec.default,
|
|
506
|
-
rest: spec.mode === "inlineSpread"
|
|
507
|
-
});
|
|
508
|
-
return ast.createFunctionParameter({
|
|
509
|
-
name,
|
|
510
|
-
type: createType(spec.type) ?? void 0,
|
|
511
|
-
optional: !!spec.optional,
|
|
512
|
-
rest: spec.mode === "inlineSpread"
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
function createDeclarationParam(name, spec) {
|
|
516
|
-
if (isGroup(spec)) return ast.createParameterGroup({
|
|
517
|
-
inline: spec.mode === "inlineSpread",
|
|
518
|
-
default: spec.default,
|
|
519
|
-
properties: Object.entries(spec.children).filter(([, child]) => child != null).map(([childName, child]) => createDeclarationLeaf(childName, child))
|
|
520
|
-
});
|
|
521
|
-
return createDeclarationLeaf(name, spec);
|
|
522
|
-
}
|
|
523
|
-
function createCallParam(name, spec) {
|
|
524
|
-
if (isGroup(spec)) return ast.createParameterGroup({
|
|
525
|
-
inline: spec.mode === "inlineSpread",
|
|
526
|
-
properties: Object.entries(spec.children).filter(([, child]) => child != null).map(([childName, child]) => ast.createFunctionParameter({
|
|
527
|
-
name: child?.mode === "inlineSpread" ? spec.mode === "inlineSpread" ? child.value ?? childName : `...${child.value ?? childName}` : child?.value ? `${childName}: ${child.value}` : childName,
|
|
528
|
-
rest: spec.mode === "inlineSpread" && child?.mode === "inlineSpread"
|
|
529
|
-
}))
|
|
530
|
-
});
|
|
531
|
-
return ast.createFunctionParameter({
|
|
532
|
-
name: spec.value ?? name,
|
|
533
|
-
rest: spec.mode === "inlineSpread"
|
|
534
|
-
});
|
|
535
|
-
}
|
|
423
|
+
//#region ../../internals/client/src/builders/generics.ts
|
|
536
424
|
/**
|
|
537
|
-
*
|
|
538
|
-
*
|
|
425
|
+
* Builds the `RequestResult` generic arguments for one operation: the per-status responses record
|
|
426
|
+
* plus the per-call `ThrowOnError` flag. `SuccessOf` / `ErrorOf` split the record inside the
|
|
427
|
+
* runtime, so this only names the record and threads `ThrowOnError`.
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* `buildRequestResultGenerics({ node, types }) // 'AddPetResponses, ThrowOnError'`
|
|
539
431
|
*/
|
|
540
|
-
function
|
|
541
|
-
|
|
542
|
-
return {
|
|
543
|
-
toConstructor() {
|
|
544
|
-
return declarationPrinter$4.print(ast.createFunctionParameters({ params: entries.map(([name, spec]) => createDeclarationParam(name, spec)) })) ?? "";
|
|
545
|
-
},
|
|
546
|
-
toCall() {
|
|
547
|
-
return callPrinter.print(ast.createFunctionParameters({ params: entries.map(([name, spec]) => createCallParam(name, spec)) })) ?? "";
|
|
548
|
-
}
|
|
549
|
-
};
|
|
432
|
+
function buildRequestResultGenerics({ node, types }) {
|
|
433
|
+
return `${types.response.responses(node)}, ThrowOnError`;
|
|
550
434
|
}
|
|
551
|
-
//#endregion
|
|
552
|
-
//#region src/utils.ts
|
|
553
435
|
/**
|
|
554
|
-
*
|
|
436
|
+
* Builds the full return type an operation's function signature uses: `Unwrappable<RequestResult>`
|
|
437
|
+
* for the default `returnType: 'full'`, already a promise so no further wrapping is needed, a plain
|
|
438
|
+
* `Promise<RequestResult>` for the internal `'plain'` shape, or a
|
|
439
|
+
* `Promise` of the runtime's `UnwrappedResult` when `returnType: 'data'` narrows a resolved call
|
|
440
|
+
* down to the bare success body.
|
|
441
|
+
*
|
|
442
|
+
* @example
|
|
443
|
+
* `buildResultType({ node, types, returnType: 'data' }) // 'Promise<UnwrappedResult<AddPetResponses, ThrowOnError>>'`
|
|
555
444
|
*/
|
|
556
|
-
function
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
445
|
+
function buildResultType({ node, types, returnType }) {
|
|
446
|
+
const generics = buildRequestResultGenerics({
|
|
447
|
+
node,
|
|
448
|
+
types
|
|
449
|
+
});
|
|
450
|
+
if (returnType === "data") return `Promise<UnwrappedResult<${generics}>>`;
|
|
451
|
+
if (returnType === "plain") return `Promise<RequestResult<${generics}>>`;
|
|
452
|
+
return `Unwrappable<RequestResult<${generics}>>`;
|
|
560
453
|
}
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region ../../internals/client/src/builders/returnStatement.ts
|
|
561
456
|
/**
|
|
562
|
-
*
|
|
563
|
-
*
|
|
457
|
+
* Builds the return statement of a generated operation function. With the default
|
|
458
|
+
* `returnType: 'full'` the runtime call already resolves to `{ data, error, request, response }`.
|
|
459
|
+
* The generated code casts that result to the operation's `RequestResult`, then wraps it with
|
|
460
|
+
* `withUnwrap`, so the caller can `await` it directly or call `.unwrap()` for the bare success
|
|
461
|
+
* body. With `returnType: 'data'` it instead routes the call through the runtime's `unwrapResult`,
|
|
462
|
+
* which narrows the resolved value down to the bare success body the same way `RequestResult`
|
|
463
|
+
* already does, using the plugin default when the call leaves `throwOnError` unset.
|
|
464
|
+
* With `returnType: 'plain'` it returns the runtime call as is, cast to `RequestResult`, with no helper.
|
|
465
|
+
*
|
|
466
|
+
* Cast first, wrap second, for the `'full'` path. That order keeps `withUnwrap`'s generic inferred
|
|
467
|
+
* as `RequestResult` instead of the runtime's own internal result type. Casting an `Unwrappable<A>`
|
|
468
|
+
* straight to `Unwrappable<B>` does not work: the `.then` overload stays pinned to `A`, and `as`
|
|
469
|
+
* rejects that two-generic swap even where `A` and `B` on their own would satisfy it.
|
|
470
|
+
*
|
|
471
|
+
* @example
|
|
472
|
+
* `return withUnwrap(request({ method: 'POST', url: '/pet', ...config }) as Promise<RequestResult<AddPetResponses, ThrowOnError>>)`
|
|
473
|
+
* @example
|
|
474
|
+
* `return unwrapResult(request({ method: 'POST', url: '/pet', ...config }), config.throwOnError ?? false) as Promise<UnwrappedResult<AddPetResponses, ThrowOnError>>`
|
|
475
|
+
* @example
|
|
476
|
+
* `return request({ method: 'POST', url: '/pet', ...config }) as Promise<RequestResult<AddPetResponses, ThrowOnError>>`
|
|
564
477
|
*/
|
|
565
|
-
function
|
|
566
|
-
if (
|
|
567
|
-
|
|
568
|
-
|
|
478
|
+
function buildReturnStatement({ node, types, callConfig, returnType, throwOnErrorDefault }) {
|
|
479
|
+
if (returnType === "data") return `return unwrapResult(request(${callConfig}), config.throwOnError ?? ${throwOnErrorDefault}) as ${buildResultType({
|
|
480
|
+
node,
|
|
481
|
+
types,
|
|
482
|
+
returnType
|
|
483
|
+
})}`;
|
|
484
|
+
if (returnType === "plain") return `return request(${callConfig}) as Promise<RequestResult<${buildRequestResultGenerics({
|
|
485
|
+
node,
|
|
486
|
+
types
|
|
487
|
+
})}>>`;
|
|
488
|
+
return `return withUnwrap(request(${callConfig}) as Promise<RequestResult<${buildRequestResultGenerics({
|
|
489
|
+
node,
|
|
490
|
+
types
|
|
491
|
+
})}>>)`;
|
|
492
|
+
}
|
|
493
|
+
//#endregion
|
|
494
|
+
//#region ../../internals/client/src/builders/security.ts
|
|
495
|
+
function serializeAuth(auth) {
|
|
496
|
+
const parts = [`type: '${auth.type}'`];
|
|
497
|
+
if (auth.scheme) parts.push(`scheme: '${auth.scheme}'`);
|
|
498
|
+
if (auth.name) parts.push(`name: '${auth.name}'`);
|
|
499
|
+
if (auth.in) parts.push(`in: '${auth.in}'`);
|
|
500
|
+
return `{ ${parts.join(", ")} }`;
|
|
569
501
|
}
|
|
570
502
|
/**
|
|
571
|
-
*
|
|
572
|
-
*
|
|
573
|
-
*
|
|
503
|
+
* Maps an OpenAPI security scheme to the inline `Auth` object, or `null` when the runtime cannot
|
|
504
|
+
* place it (an unresolved `$ref`, or an `apiKey` without a name or outside `header` / `query` /
|
|
505
|
+
* `cookie`). `http` schemes other than `basic` are treated as bearer.
|
|
574
506
|
*/
|
|
575
|
-
function
|
|
576
|
-
if (!
|
|
577
|
-
|
|
507
|
+
function resolveSecurityScheme(scheme) {
|
|
508
|
+
if (!scheme || "$ref" in scheme) return null;
|
|
509
|
+
if (scheme.type === "apiKey") {
|
|
510
|
+
if (!scheme.name || scheme.in !== "header" && scheme.in !== "query" && scheme.in !== "cookie") return null;
|
|
511
|
+
return {
|
|
512
|
+
type: "apiKey",
|
|
513
|
+
name: scheme.name,
|
|
514
|
+
in: scheme.in
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
if (scheme.type === "http") return {
|
|
518
|
+
type: "http",
|
|
519
|
+
scheme: scheme.scheme?.toLowerCase() === "basic" ? "basic" : "bearer"
|
|
520
|
+
};
|
|
521
|
+
if (scheme.type === "oauth2") return { type: "oauth2" };
|
|
522
|
+
if (scheme.type === "openIdConnect") return { type: "openIdConnect" };
|
|
523
|
+
return null;
|
|
578
524
|
}
|
|
579
525
|
/**
|
|
580
|
-
*
|
|
581
|
-
* `
|
|
526
|
+
* Derives the per-operation security metadata from the OpenAPI document. The operation's own
|
|
527
|
+
* `security` overrides the global `security` (an explicit empty array disables auth), and every
|
|
528
|
+
* referenced scheme is resolved from `components.securitySchemes` into a flat, de-duplicated list of
|
|
529
|
+
* `Auth` objects the runtime walks in order.
|
|
530
|
+
*
|
|
531
|
+
* @example
|
|
532
|
+
* `getOperationSecurity({ document, method: 'POST', path: '/pet' })`
|
|
533
|
+
* `// [{ type: 'http', scheme: 'bearer' }]`
|
|
582
534
|
*/
|
|
583
|
-
function
|
|
584
|
-
if (!
|
|
585
|
-
|
|
586
|
-
return
|
|
535
|
+
function getOperationSecurity({ document, method, path }) {
|
|
536
|
+
if (!document) return void 0;
|
|
537
|
+
const requirements = (document.paths?.[path]?.[method.toLowerCase()])?.security ?? document.security;
|
|
538
|
+
if (!requirements?.length) return void 0;
|
|
539
|
+
const definitions = document.components?.securitySchemes ?? {};
|
|
540
|
+
const security = [];
|
|
541
|
+
const seen = /* @__PURE__ */ new Set();
|
|
542
|
+
for (const requirement of requirements) for (const schemeName of Object.keys(requirement)) {
|
|
543
|
+
if (seen.has(schemeName)) continue;
|
|
544
|
+
seen.add(schemeName);
|
|
545
|
+
const auth = resolveSecurityScheme(definitions[schemeName]);
|
|
546
|
+
if (auth) security.push(auth);
|
|
547
|
+
}
|
|
548
|
+
return security.length ? security : void 0;
|
|
587
549
|
}
|
|
588
550
|
/**
|
|
589
|
-
*
|
|
590
|
-
*
|
|
551
|
+
* Serializes the per-operation security into the literal emitted on each generated call's `security`
|
|
552
|
+
* field. The runtime `resolveAuth` helper walks it, calling the configured `auth` resolver per entry.
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
* `buildSecurityMetadata({ security: [{ type: 'http', scheme: 'bearer' }] }) // "[{ type: 'http', scheme: 'bearer' }]"`
|
|
591
556
|
*/
|
|
592
|
-
function
|
|
593
|
-
|
|
557
|
+
function buildSecurityMetadata({ security }) {
|
|
558
|
+
if (!security?.length) return null;
|
|
559
|
+
return `[${security.map(serializeAuth).join(", ")}]`;
|
|
594
560
|
}
|
|
561
|
+
//#endregion
|
|
562
|
+
//#region ../../internals/client/src/builders/signature.ts
|
|
563
|
+
const declarationPrinter = functionPrinter({ mode: "declaration" });
|
|
595
564
|
/**
|
|
596
|
-
*
|
|
597
|
-
*
|
|
565
|
+
* Builds the grouped-options signature for one operation: a single `options` object whose `TData`
|
|
566
|
+
* is the `<Name>Options` type, and a `RequestResult` return type keyed to the per-status responses
|
|
567
|
+
* record. There are no positional arguments.
|
|
598
568
|
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
569
|
+
* The generated file imports `<Name>Options` and `<Name>Responses` and uses them directly, so no
|
|
570
|
+
* per-operation input type has to be emitted. Both names come from `types`, which is `plugin-ts` or
|
|
571
|
+
* `plugin-zod`'s inferred types (see `resolveOperationTypes`).
|
|
602
572
|
*/
|
|
603
|
-
function
|
|
604
|
-
const
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
573
|
+
function buildGroupedOptionsSignature({ node, types, returnType, throwOnErrorDefault }) {
|
|
574
|
+
const optionsName = types.response.options(node);
|
|
575
|
+
const { isOptional } = getRequestGroupOptionality(node);
|
|
576
|
+
return {
|
|
577
|
+
paramsSignature: declarationPrinter.print(createFunctionParameters({ params: [createFunctionParameter({
|
|
578
|
+
name: "options",
|
|
579
|
+
type: `Options<${optionsName}, ThrowOnError>`,
|
|
580
|
+
...isOptional ? { default: "{}" } : {}
|
|
581
|
+
})] })) ?? "",
|
|
582
|
+
returnType: buildResultType({
|
|
583
|
+
node,
|
|
584
|
+
types,
|
|
585
|
+
returnType
|
|
586
|
+
}),
|
|
587
|
+
generics: [`ThrowOnError extends boolean = ${throwOnErrorDefault}`]
|
|
588
|
+
};
|
|
616
589
|
}
|
|
590
|
+
//#endregion
|
|
591
|
+
//#region ../../internals/client/src/builders/validatorOptions.ts
|
|
617
592
|
/**
|
|
618
|
-
*
|
|
619
|
-
*
|
|
593
|
+
* Returns `'zod'` when request body parsing is enabled, `null` otherwise. The string shorthand
|
|
594
|
+
* `'zod'` validates the response only, so it does not enable request parsing.
|
|
620
595
|
*/
|
|
621
|
-
function
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
const requestName = node.requestBody?.content?.[0]?.schema ? tsResolver.resolveDataName(node) : null;
|
|
625
|
-
const responseType = getResponseType(node);
|
|
626
|
-
return createFunctionParams({ config: {
|
|
627
|
-
mode: "object",
|
|
628
|
-
children: {
|
|
629
|
-
requestConfig: { mode: "inlineSpread" },
|
|
630
|
-
method: { value: JSON.stringify(ast.isHttpOperationNode(node) ? node.method.toUpperCase() : "") },
|
|
631
|
-
url: { value: url },
|
|
632
|
-
baseURL: baseURL ? { value: JSON.stringify(baseURL) } : null,
|
|
633
|
-
params: queryParamsName ? zodQueryParamsName ? { value: "requestParams" } : {} : null,
|
|
634
|
-
data: requestName ? { value: isMultipleContentTypes && hasFormData ? "contentType === 'multipart/form-data' ? formData as FormData : requestData" : isFormData ? "formData as FormData" : "requestData" } : null,
|
|
635
|
-
contentType: isMultipleContentTypes ? {} : null,
|
|
636
|
-
responseType: responseType ? { value: JSON.stringify(responseType) } : null,
|
|
637
|
-
headers: headers.length ? { value: `{ ${headers.join(", ")}, ...requestConfig.headers }` } : null
|
|
638
|
-
}
|
|
639
|
-
} });
|
|
596
|
+
function resolveRequestValidator(validator) {
|
|
597
|
+
if (!validator || validator === "zod") return null;
|
|
598
|
+
return validator.request ?? null;
|
|
640
599
|
}
|
|
641
600
|
/**
|
|
642
|
-
*
|
|
643
|
-
*
|
|
601
|
+
* Returns `'zod'` when response parsing is enabled, `null` otherwise. The string shorthand `'zod'`
|
|
602
|
+
* maps to response parsing.
|
|
644
603
|
*/
|
|
645
|
-
function
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
if (node.requestBody?.content?.[0]?.schema) return "const requestData = data";
|
|
650
|
-
return "";
|
|
604
|
+
function resolveResponseValidator(validator) {
|
|
605
|
+
if (!validator) return null;
|
|
606
|
+
if (validator === "zod") return "zod";
|
|
607
|
+
return validator.response ?? null;
|
|
651
608
|
}
|
|
652
609
|
/**
|
|
653
|
-
*
|
|
654
|
-
*
|
|
655
|
-
*
|
|
610
|
+
* Resolves the zod expression a generated client validates a success response with. Only success
|
|
611
|
+
* (2xx) bodies reach the parse under the throw-on-error contract, so the success-only
|
|
612
|
+
* `<operation>ResponseSchema` is used; error bodies are never zod-parsed.
|
|
656
613
|
*/
|
|
657
|
-
function
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
return `const requestParams = ${zodQueryParamsName}.parse(params)`;
|
|
614
|
+
function buildZodResponseParse(node, zodResolver) {
|
|
615
|
+
const name = zodResolver.response.response(node);
|
|
616
|
+
return name ? {
|
|
617
|
+
expression: name,
|
|
618
|
+
importNames: [name]
|
|
619
|
+
} : null;
|
|
664
620
|
}
|
|
665
621
|
/**
|
|
666
|
-
*
|
|
667
|
-
*
|
|
622
|
+
* Resolves the zod expression a generated client validates an error body with on the non-throw path.
|
|
623
|
+
* Uses the error-only `<operation>ErrorSchema` (the union of non-2xx statuses); returns `null` when the
|
|
624
|
+
* operation documents no error responses with a schema.
|
|
668
625
|
*/
|
|
669
|
-
function
|
|
670
|
-
|
|
626
|
+
function buildZodErrorParse(node, zodResolver) {
|
|
627
|
+
if (!node.responses.some((res) => !isSuccessStatusCode(res.statusCode) && res.content?.some((entry) => entry.schema))) return null;
|
|
628
|
+
const name = zodResolver.response.error?.(node);
|
|
629
|
+
return name ? {
|
|
630
|
+
expression: name,
|
|
631
|
+
importNames: [name]
|
|
632
|
+
} : null;
|
|
671
633
|
}
|
|
634
|
+
//#endregion
|
|
635
|
+
//#region ../../internals/client/src/builders/validator.ts
|
|
672
636
|
/**
|
|
673
|
-
* Builds the
|
|
674
|
-
*
|
|
675
|
-
*
|
|
637
|
+
* Builds the validator-hook references for one operation. Request validation runs before the send;
|
|
638
|
+
* response validation runs on the success body only. Returns `null` references when the matching
|
|
639
|
+
* direction is disabled or the schema is absent.
|
|
676
640
|
*/
|
|
677
|
-
function
|
|
678
|
-
const
|
|
679
|
-
const
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
if (
|
|
686
|
-
|
|
641
|
+
function buildValidatorHooks({ node, validator, zodResolver }) {
|
|
642
|
+
const importedZodNames = [];
|
|
643
|
+
const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
|
|
644
|
+
const zodRequestName = zodResolver && resolveRequestValidator(validator) === "zod" && hasRequestBody ? zodResolver.response.body(node) : null;
|
|
645
|
+
const request = zodRequestName ?? null;
|
|
646
|
+
if (zodRequestName) importedZodNames.push(zodRequestName);
|
|
647
|
+
const responseParse = zodResolver && resolveResponseValidator(validator) === "zod" ? buildZodResponseParse(node, zodResolver) : null;
|
|
648
|
+
const response = responseParse ? responseParse.expression : null;
|
|
649
|
+
if (responseParse) importedZodNames.push(...responseParse.importNames);
|
|
650
|
+
const errorParse = zodResolver && resolveResponseValidator(validator) === "zod" ? buildZodErrorParse(node, zodResolver) : null;
|
|
651
|
+
const error = errorParse ? errorParse.expression : null;
|
|
652
|
+
if (errorParse) importedZodNames.push(...errorParse.importNames);
|
|
653
|
+
return {
|
|
654
|
+
request,
|
|
655
|
+
response,
|
|
656
|
+
error,
|
|
657
|
+
importedZodNames
|
|
658
|
+
};
|
|
687
659
|
}
|
|
688
660
|
//#endregion
|
|
689
|
-
//#region src/
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
661
|
+
//#region ../../internals/client/src/builders/styles.ts
|
|
662
|
+
/**
|
|
663
|
+
* Renders a parameter name as an object-literal key, quoted when it is not a bare identifier.
|
|
664
|
+
* Path keys are camelCased to match the URL template placeholders. Query, header, and cookie keys
|
|
665
|
+
* keep the spec name, matching the remapped keys the runtime serializes.
|
|
666
|
+
*/
|
|
667
|
+
function toKey(name, location) {
|
|
668
|
+
const key = location === "path" ? camelCase(name) : name;
|
|
669
|
+
return isValidVarName(key) ? key : JSON.stringify(key);
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Serializes one parameter's metadata into a `{ style, explode }` literal, or `null` when the
|
|
673
|
+
* parameter carries neither. Path and query carry the serialization `style`; header and cookie use a
|
|
674
|
+
* fixed style (`simple` and `form`), so only `explode` is emitted for them.
|
|
675
|
+
*/
|
|
676
|
+
function serializeParameter(parameter) {
|
|
677
|
+
const parts = [];
|
|
678
|
+
if ((parameter.in === "path" || parameter.in === "query") && parameter.style) parts.push(`style: '${parameter.style}'`);
|
|
679
|
+
if (parameter.explode !== void 0) parts.push(`explode: ${parameter.explode}`);
|
|
680
|
+
return parts.length > 0 ? `{ ${parts.join(", ")} }` : null;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Builds the per-operation `styles` literal from the operation's parameters, grouped by location.
|
|
684
|
+
* Path entries are keyed by the camelCased name to match the URL template placeholders; query,
|
|
685
|
+
* header, and cookie entries keep the spec name to match the keys the runtime serializes.
|
|
686
|
+
* Only parameters whose source defines `style` or `explode` are emitted, so calls without
|
|
687
|
+
* serialization metadata keep the runtime defaults and existing output is unchanged. Returns `null`
|
|
688
|
+
* when no parameter carries metadata.
|
|
689
|
+
*
|
|
690
|
+
* @example
|
|
691
|
+
* ```ts
|
|
692
|
+
* // a path param with { style: 'matrix', explode: true } and a query param with { explode: false }
|
|
693
|
+
* buildStyles({ node }) // "{ path: { id: { style: 'matrix', explode: true } }, query: { tags: { explode: false } } }"
|
|
694
|
+
* ```
|
|
695
|
+
*/
|
|
696
|
+
function buildStyles({ node }) {
|
|
697
|
+
if (!ast.isHttpOperationNode(node)) return null;
|
|
698
|
+
const groups = {
|
|
699
|
+
path: [],
|
|
700
|
+
query: [],
|
|
701
|
+
header: [],
|
|
702
|
+
cookie: []
|
|
696
703
|
};
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
704
|
+
for (const parameter of node.parameters) {
|
|
705
|
+
const literal = serializeParameter(parameter);
|
|
706
|
+
if (!literal) continue;
|
|
707
|
+
groups[parameter.in].push(`${toKey(parameter.name, parameter.in)}: ${literal}`);
|
|
708
|
+
}
|
|
709
|
+
const locations = Object.keys(groups).filter((location) => groups[location].length > 0);
|
|
710
|
+
if (locations.length === 0) return null;
|
|
711
|
+
return `{ ${locations.map((location) => `${location}: { ${groups[location].join(", ")} }`).join(", ")} }`;
|
|
703
712
|
}
|
|
704
|
-
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region ../../internals/client/src/components/Operation.tsx
|
|
715
|
+
/**
|
|
716
|
+
* Renders one client operation: the grouped `<Name>Request` type and the function that forwards a
|
|
717
|
+
* single `options` object to the resolved client and returns the `Unwrappable<RequestResult>`. The
|
|
718
|
+
* type, signature, and call config are built with the AST factory, and only the jsx-renderer emits
|
|
719
|
+
* the source.
|
|
720
|
+
*/
|
|
721
|
+
function Operation({ name, node, types, zodResolver, validator, returnType, throwOnErrorDefault, security, isExportable = true, isIndexable = true }) {
|
|
705
722
|
if (!ast.isHttpOperationNode(node)) return null;
|
|
706
|
-
const
|
|
707
|
-
paramsType,
|
|
708
|
-
paramsCasing,
|
|
709
|
-
pathParamsType,
|
|
723
|
+
const signature = buildGroupedOptionsSignature({
|
|
710
724
|
node,
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
const { path: originalPathParams } = getOperationParameters(node);
|
|
715
|
-
const { path: casedPathParams } = getOperationParameters(node, { paramsCasing });
|
|
716
|
-
const pathParamsMapping = paramsCasing ? buildParamsMapping(originalPathParams, casedPathParams) : null;
|
|
717
|
-
return /* @__PURE__ */ jsx(File.Source, {
|
|
718
|
-
name,
|
|
719
|
-
isExportable,
|
|
720
|
-
isIndexable,
|
|
721
|
-
children: /* @__PURE__ */ jsxs(Function, {
|
|
722
|
-
name,
|
|
723
|
-
export: isExportable,
|
|
724
|
-
params: paramsSignature,
|
|
725
|
-
children: [
|
|
726
|
-
pathParamsMapping && Object.entries(pathParamsMapping).filter(([originalName, camelCaseName]) => isValidVarName(originalName) && originalName !== camelCaseName).map(([originalName, camelCaseName]) => `const ${originalName} = ${camelCaseName}`).join("\n"),
|
|
727
|
-
pathParamsMapping && Object.keys(pathParamsMapping).length > 0 && /* @__PURE__ */ jsx("br", {}),
|
|
728
|
-
/* @__PURE__ */ jsx(Const, {
|
|
729
|
-
name: "res",
|
|
730
|
-
children: `{ method: '${node.method.toUpperCase()}', url: ${Url$1.toTemplateString(node.path, { prefix: baseURL })} as const }`
|
|
731
|
-
}),
|
|
732
|
-
/* @__PURE__ */ jsx("br", {}),
|
|
733
|
-
"return res"
|
|
734
|
-
]
|
|
735
|
-
})
|
|
725
|
+
types,
|
|
726
|
+
returnType,
|
|
727
|
+
throwOnErrorDefault
|
|
736
728
|
});
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
function buildClientParamsNode({ paramsType, paramsCasing, pathParamsType, node, tsResolver, isConfigurable }) {
|
|
742
|
-
return ast.createOperationParams(node, {
|
|
743
|
-
paramsType,
|
|
744
|
-
pathParamsType: paramsType === "object" ? "object" : pathParamsType === "object" ? "object" : "inline",
|
|
745
|
-
paramsCasing,
|
|
746
|
-
resolver: tsResolver,
|
|
747
|
-
extraParams: [...isConfigurable ? [ast.createFunctionParameter({
|
|
748
|
-
name: "config",
|
|
749
|
-
type: ast.createParamsType({
|
|
750
|
-
variant: "reference",
|
|
751
|
-
name: buildRequestConfigType(node, tsResolver)
|
|
752
|
-
}),
|
|
753
|
-
default: "{}"
|
|
754
|
-
})] : []]
|
|
729
|
+
const validators = buildValidatorHooks({
|
|
730
|
+
node,
|
|
731
|
+
validator,
|
|
732
|
+
zodResolver
|
|
755
733
|
});
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
const
|
|
760
|
-
const
|
|
734
|
+
const securityLiteral = buildSecurityMetadata({ security });
|
|
735
|
+
const stylesLiteral = buildStyles({ node });
|
|
736
|
+
const { defaultContentType } = getContentTypeInfo(node);
|
|
737
|
+
const bakedRequestContentType = Boolean(node.requestBody?.content?.[0]?.schema) && defaultContentType !== "application/json" ? defaultContentType : null;
|
|
738
|
+
const mergeContentType = Boolean(bakedRequestContentType) && getResponseContentTypeInfo(node).isMultipleContentTypes;
|
|
739
|
+
const contentTypeLiteral = !bakedRequestContentType ? null : mergeContentType ? `contentType: { request: '${bakedRequestContentType}', ...(typeof contentType === 'string' ? { request: contentType } : contentType) }` : `contentType: { request: '${bakedRequestContentType}' }`;
|
|
740
|
+
const eventStream = isEventStream(node);
|
|
761
741
|
const responseType = getResponseType(node);
|
|
762
|
-
const
|
|
763
|
-
const
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
const requestName = node.requestBody?.content?.[0]?.schema ? tsResolver.resolveDataName(node) : null;
|
|
768
|
-
const successNames = resolveSuccessNames(node, tsResolver);
|
|
769
|
-
const responseName = successNames.length > 0 ? successNames.join(" | ") : tsResolver.resolveResponseName(node);
|
|
770
|
-
const queryParamsName = originalQueryParams.length > 0 ? tsResolver.resolveQueryParamsName(node, originalQueryParams[0]) : null;
|
|
771
|
-
const headerParamsName = originalHeaderParams.length > 0 ? tsResolver.resolveHeaderParamsName(node, originalHeaderParams[0]) : null;
|
|
772
|
-
const requestParser = resolveRequestParser(parser);
|
|
773
|
-
const responseParser = resolveResponseParser(parser);
|
|
774
|
-
const zodResponseName = zodResolver && responseParser === "zod" ? zodResolver.resolveResponseName?.(node) : null;
|
|
775
|
-
const zodRequestName = zodResolver && requestParser === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null;
|
|
776
|
-
const queryParamsParser = resolveQueryParamsParser(parser);
|
|
777
|
-
const zodQueryParamsName = zodResolver && queryParamsParser === "zod" && originalQueryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, originalQueryParams[0]) : null;
|
|
778
|
-
const errorNames = node.responses.filter((r) => {
|
|
779
|
-
return Number.parseInt(r.statusCode, 10) >= 400;
|
|
780
|
-
}).map((r) => tsResolver.resolveResponseStatusName(node, r.statusCode));
|
|
781
|
-
const headers = [!isMultipleContentTypes && contentType !== "application/json" && contentType !== "multipart/form-data" ? `'Content-Type': '${contentType}'` : null, headerParamsName ? headerParamsMapping ? "...mappedHeaders" : "...headers" : null].filter(Boolean);
|
|
782
|
-
const TError = `ResponseErrorConfig<${errorNames.length > 0 ? errorNames.join(" | ") : "Error"}>`;
|
|
783
|
-
const allStatusNames = node.responses.map((r) => tsResolver.resolveResponseStatusName(node, r.statusCode));
|
|
784
|
-
const generics = [
|
|
785
|
-
dataReturnType === "full" ? allStatusNames.length > 0 ? allStatusNames.join(" | ") : responseName : responseName,
|
|
786
|
-
TError,
|
|
787
|
-
parser === "zod" && zodRequestName ? `z.output<typeof ${zodRequestName}>` : requestName || "unknown"
|
|
742
|
+
const responseTypeLiteral = responseType ? `responseType: '${responseType}'` : null;
|
|
743
|
+
const validatorEntries = [
|
|
744
|
+
validators.request ? `request: ${validators.request}` : null,
|
|
745
|
+
validators.response ? `response: ${validators.response}` : null,
|
|
746
|
+
validators.error ? `error: ${validators.error}` : null
|
|
788
747
|
].filter(Boolean);
|
|
789
|
-
const
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
748
|
+
const validatorLiteral = validatorEntries.length ? `validator: { ${validatorEntries.join(", ")} }` : null;
|
|
749
|
+
const callConfig = `{ ${[
|
|
750
|
+
`method: '${node.method.toUpperCase()}'`,
|
|
751
|
+
`url: '${node.path}'`,
|
|
752
|
+
securityLiteral ? `security: ${securityLiteral}` : null,
|
|
753
|
+
stylesLiteral ? `styles: ${stylesLiteral}` : null,
|
|
754
|
+
validatorLiteral,
|
|
755
|
+
contentTypeLiteral,
|
|
756
|
+
responseTypeLiteral,
|
|
757
|
+
"...config",
|
|
758
|
+
`throwOnError: config.throwOnError ?? ${throwOnErrorDefault}`
|
|
759
|
+
].filter(Boolean).join(", ")} }`;
|
|
760
|
+
const eventType = `SuccessOf<${types.response.responses(node)}>`;
|
|
761
|
+
const functionReturnType = eventStream ? `Promise<EventStreamResult<${eventType}>>` : signature.returnType;
|
|
762
|
+
const returnStatement = eventStream ? `return toEventStream<${eventType}>(request(${callConfig}))` : buildReturnStatement({
|
|
793
763
|
node,
|
|
794
|
-
|
|
795
|
-
|
|
764
|
+
types,
|
|
765
|
+
callConfig,
|
|
766
|
+
returnType,
|
|
767
|
+
throwOnErrorDefault
|
|
796
768
|
});
|
|
797
|
-
|
|
798
|
-
const urlParamsNode = buildUrlParamsNode({
|
|
799
|
-
paramsType,
|
|
800
|
-
paramsCasing,
|
|
801
|
-
pathParamsType,
|
|
802
|
-
node,
|
|
803
|
-
tsResolver
|
|
804
|
-
});
|
|
805
|
-
const urlParamsCall = functionPrinter({ mode: "call" }).print(urlParamsNode) ?? "";
|
|
806
|
-
const clientParams = createFunctionParams({ config: {
|
|
807
|
-
mode: "object",
|
|
808
|
-
children: {
|
|
809
|
-
method: { value: stringify(node.method.toUpperCase()) },
|
|
810
|
-
url: { value: urlName ? `${urlName}(${urlParamsCall}).url.toString()` : Url$1.toTemplateString(node.path) },
|
|
811
|
-
baseURL: baseURL && !urlName ? { value: `\`${baseURL}\`` } : null,
|
|
812
|
-
params: queryParamsName ? zodQueryParamsName ? { value: "requestParams" } : queryParamsMapping ? { value: "mappedParams" } : {} : null,
|
|
813
|
-
data: requestName ? { value: isMultipleContentTypes && hasFormData ? "contentType === 'multipart/form-data' ? formData as FormData : requestData" : isFormData ? "formData as FormData" : "requestData" } : null,
|
|
814
|
-
contentType: isConfigurable && isMultipleContentTypes ? {} : null,
|
|
815
|
-
responseType: responseType ? { value: stringify(responseType) } : null,
|
|
816
|
-
requestConfig: isConfigurable ? { mode: "inlineSpread" } : null,
|
|
817
|
-
headers: headers.length ? { value: isConfigurable ? `{ ${headers.join(", ")}, ...requestConfig.headers }` : `{ ${headers.join(", ")} }` } : null
|
|
818
|
-
}
|
|
819
|
-
} });
|
|
820
|
-
const statusUnionType = dataReturnType === "full" ? buildStatusUnionType(node, tsResolver) : null;
|
|
821
|
-
const childrenElement = children ? children : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
822
|
-
dataReturnType === "full" && responseParser === "zod" && zodResponseName && statusUnionType && `return {...res, data: ${zodResponseName}.parse(res.data)} as ${statusUnionType}`,
|
|
823
|
-
dataReturnType === "full" && responseParser !== "zod" && statusUnionType && `return res as ${statusUnionType}`,
|
|
824
|
-
dataReturnType === "data" && responseParser === "zod" && zodResponseName && `return ${zodResponseName}.parse(res.data)`,
|
|
825
|
-
dataReturnType === "data" && responseParser !== "zod" && "return res.data"
|
|
826
|
-
] });
|
|
827
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("br", {}), /* @__PURE__ */ jsx(File.Source, {
|
|
769
|
+
return /* @__PURE__ */ jsx(File.Source, {
|
|
828
770
|
name,
|
|
829
771
|
isExportable,
|
|
830
772
|
isIndexable,
|
|
831
773
|
children: /* @__PURE__ */ jsxs(Function, {
|
|
832
774
|
name,
|
|
833
|
-
async: true,
|
|
834
775
|
export: isExportable,
|
|
835
|
-
|
|
776
|
+
generics: signature.generics,
|
|
777
|
+
params: signature.paramsSignature,
|
|
778
|
+
returnType: functionReturnType,
|
|
836
779
|
JSDoc: { comments: buildOperationComments(node, {
|
|
837
780
|
link: "urlPath",
|
|
838
781
|
linkPosition: "beforeDeprecated",
|
|
839
782
|
splitLines: true
|
|
840
783
|
}) },
|
|
841
|
-
returnType,
|
|
842
784
|
children: [
|
|
843
|
-
|
|
785
|
+
mergeContentType ? "const { client: request = client, contentType, ...config } = options" : "const { client: request = client, ...config } = options",
|
|
844
786
|
/* @__PURE__ */ jsx("br", {}),
|
|
845
|
-
|
|
846
|
-
pathParamsMapping && /* @__PURE__ */ jsx("br", {}),
|
|
847
|
-
queryParamsMapping && queryParamsName && /* @__PURE__ */ jsxs(Fragment, { children: [`const mappedParams = params ? { ${Object.entries(queryParamsMapping).map(([originalName, camelCaseName]) => `"${originalName}": params.${camelCaseName}`).join(", ")} } : undefined`, /* @__PURE__ */ jsx("br", {})] }),
|
|
848
|
-
headerParamsMapping && headerParamsName && /* @__PURE__ */ jsxs(Fragment, { children: [`const mappedHeaders = headers ? { ${Object.entries(headerParamsMapping).map(([originalName, camelCaseName]) => `"${originalName}": headers.${camelCaseName}`).join(", ")} } : undefined`, /* @__PURE__ */ jsx("br", {})] }),
|
|
849
|
-
requestParser === "zod" && zodRequestName ? `const requestData = ${zodRequestName}.parse(data)` : requestName && "const requestData = data",
|
|
850
|
-
zodQueryParamsName && `const requestParams = ${zodQueryParamsName}.parse(params)`,
|
|
851
|
-
(isFormData || isMultipleContentTypes && hasFormData) && requestName && "const formData = buildFormData(requestData)",
|
|
852
|
-
/* @__PURE__ */ jsx("br", {}),
|
|
853
|
-
isConfigurable ? `const res = await request<${generics.join(", ")}>(${clientParams.toCall()})` : `const res = await client<${generics.join(", ")}>(${clientParams.toCall()})`,
|
|
854
|
-
/* @__PURE__ */ jsx("br", {}),
|
|
855
|
-
childrenElement
|
|
787
|
+
returnStatement
|
|
856
788
|
]
|
|
857
789
|
})
|
|
858
|
-
})] });
|
|
859
|
-
}
|
|
860
|
-
//#endregion
|
|
861
|
-
//#region src/components/ClassClient.tsx
|
|
862
|
-
const declarationPrinter$1 = functionPrinter({ mode: "declaration" });
|
|
863
|
-
function generateMethod$1({ node, name, tsResolver, zodResolver, baseURL, dataReturnType, parser, paramsType, paramsCasing, pathParamsType }) {
|
|
864
|
-
if (!ast.isHttpOperationNode(node)) return "";
|
|
865
|
-
const { defaultContentType: contentType, isMultipleContentTypes, hasFormData } = getContentTypeInfo(node);
|
|
866
|
-
const isFormData = !isMultipleContentTypes && contentType === "multipart/form-data";
|
|
867
|
-
const { header: headerParams } = getOperationParameters(node);
|
|
868
|
-
const headerParamsName = headerParams.length > 0 ? tsResolver.resolveHeaderParamsName(node, headerParams[0]) : null;
|
|
869
|
-
const headers = isMultipleContentTypes ? headerParamsName ? ["...headers"] : [] : buildHeaders(contentType, !!headerParamsName);
|
|
870
|
-
const generics = buildGenerics(node, tsResolver, {
|
|
871
|
-
dataReturnType,
|
|
872
|
-
zodResolver,
|
|
873
|
-
parser
|
|
874
|
-
});
|
|
875
|
-
const paramsNode = buildClientParamsNode({
|
|
876
|
-
paramsType,
|
|
877
|
-
paramsCasing,
|
|
878
|
-
pathParamsType,
|
|
879
|
-
node,
|
|
880
|
-
tsResolver,
|
|
881
|
-
isConfigurable: true
|
|
882
|
-
});
|
|
883
|
-
const paramsSignature = declarationPrinter$1.print(paramsNode) ?? "";
|
|
884
|
-
const { query: queryParams } = getOperationParameters(node);
|
|
885
|
-
const zodQueryParamsName = zodResolver && resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null;
|
|
886
|
-
const clientParams = buildClassClientParams({
|
|
887
|
-
node,
|
|
888
|
-
url: Url$1.toTemplateString(node.path, { casing: paramsCasing }),
|
|
889
|
-
baseURL,
|
|
890
|
-
tsResolver,
|
|
891
|
-
isFormData,
|
|
892
|
-
isMultipleContentTypes,
|
|
893
|
-
hasFormData,
|
|
894
|
-
headers,
|
|
895
|
-
zodQueryParamsName
|
|
896
|
-
});
|
|
897
|
-
const jsdoc = buildJSDoc(buildOperationComments(node, {
|
|
898
|
-
link: "urlPath",
|
|
899
|
-
linkPosition: "beforeDeprecated",
|
|
900
|
-
splitLines: true
|
|
901
|
-
}));
|
|
902
|
-
const requestDataLine = buildRequestDataLine({
|
|
903
|
-
parser,
|
|
904
|
-
node,
|
|
905
|
-
zodResolver
|
|
906
|
-
});
|
|
907
|
-
const queryParamsLine = buildQueryParamsLine({
|
|
908
|
-
parser,
|
|
909
|
-
node,
|
|
910
|
-
zodResolver
|
|
911
|
-
});
|
|
912
|
-
const formDataLine = buildFormDataLine(isFormData || isMultipleContentTypes && hasFormData, !!node.requestBody?.content?.[0]?.schema);
|
|
913
|
-
const returnStatement = buildReturnStatement({
|
|
914
|
-
dataReturnType,
|
|
915
|
-
parser,
|
|
916
|
-
node,
|
|
917
|
-
zodResolver,
|
|
918
|
-
tsResolver
|
|
919
|
-
});
|
|
920
|
-
return `${jsdoc}async ${name}(${paramsSignature}) {\n${[
|
|
921
|
-
`const { client: request = client, ${isMultipleContentTypes ? `contentType = ${stringify(contentType)}, ` : ""}...requestConfig } = mergeConfig(this.#config, config)`,
|
|
922
|
-
"",
|
|
923
|
-
requestDataLine,
|
|
924
|
-
queryParamsLine,
|
|
925
|
-
formDataLine,
|
|
926
|
-
`const res = await request<${generics.join(", ")}>(${clientParams.toCall()})`,
|
|
927
|
-
returnStatement
|
|
928
|
-
].filter(Boolean).map((line) => ` ${line}`).join("\n")}\n }`;
|
|
929
|
-
}
|
|
930
|
-
__name(generateMethod$1, "generateMethod");
|
|
931
|
-
function ClassClient({ name, isExportable = true, isIndexable = true, operations, baseURL, dataReturnType, parser, paramsType, paramsCasing, pathParamsType, children }) {
|
|
932
|
-
const classCode = `export class ${name} {
|
|
933
|
-
#config: Partial<RequestConfig> & { client?: Client }
|
|
934
|
-
|
|
935
|
-
constructor(config: Partial<RequestConfig> & { client?: Client } = {}) {
|
|
936
|
-
this.#config = config
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
${operations.map(({ node, name: methodName, tsResolver, zodResolver }) => generateMethod$1({
|
|
940
|
-
node,
|
|
941
|
-
name: methodName,
|
|
942
|
-
tsResolver,
|
|
943
|
-
zodResolver,
|
|
944
|
-
baseURL,
|
|
945
|
-
dataReturnType,
|
|
946
|
-
parser,
|
|
947
|
-
paramsType,
|
|
948
|
-
paramsCasing,
|
|
949
|
-
pathParamsType
|
|
950
|
-
})).join("\n\n")}
|
|
951
|
-
}`;
|
|
952
|
-
return /* @__PURE__ */ jsxs(File.Source, {
|
|
953
|
-
name,
|
|
954
|
-
isExportable,
|
|
955
|
-
isIndexable,
|
|
956
|
-
children: [classCode, children]
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
//#endregion
|
|
960
|
-
//#region src/components/WrapperClient.tsx
|
|
961
|
-
function WrapperClient({ name, controllers, isExportable = true, isIndexable = true }) {
|
|
962
|
-
const classCode = `export class ${name} {
|
|
963
|
-
${controllers.map(({ className, propertyName }) => ` readonly ${propertyName}: ${className}`).join("\n")}
|
|
964
|
-
|
|
965
|
-
constructor(config: Partial<RequestConfig> & { client?: Client } = {}) {
|
|
966
|
-
${controllers.map(({ className, propertyName }) => ` this.${propertyName} = new ${className}(config)`).join("\n")}
|
|
967
|
-
}
|
|
968
|
-
}`;
|
|
969
|
-
return /* @__PURE__ */ jsx(File.Source, {
|
|
970
|
-
name,
|
|
971
|
-
isExportable,
|
|
972
|
-
isIndexable,
|
|
973
|
-
children: classCode
|
|
974
790
|
});
|
|
975
791
|
}
|
|
976
792
|
//#endregion
|
|
977
|
-
//#region src/
|
|
978
|
-
function resolveTypeImportNames$1(node, tsResolver) {
|
|
979
|
-
return resolveOperationTypeNames(node, tsResolver, { order: "body-response-first" });
|
|
980
|
-
}
|
|
981
|
-
__name(resolveTypeImportNames$1, "resolveTypeImportNames");
|
|
982
|
-
function resolveZodImportNames$1(node, zodResolver, parser) {
|
|
983
|
-
const { query: queryParams } = getOperationParameters(node);
|
|
984
|
-
return [
|
|
985
|
-
resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
|
|
986
|
-
resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
|
|
987
|
-
resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
|
|
988
|
-
].filter((n) => Boolean(n));
|
|
989
|
-
}
|
|
990
|
-
__name(resolveZodImportNames$1, "resolveZodImportNames");
|
|
793
|
+
//#region ../../internals/client/src/resolveOperationTypes.ts
|
|
991
794
|
/**
|
|
992
|
-
*
|
|
993
|
-
*
|
|
994
|
-
* per operation and a shared constructor for request configuration.
|
|
795
|
+
* Warning a client generator reports when neither plugin can supply the operation types, so the
|
|
796
|
+
* pipeline says why nothing was generated instead of silently emitting no files.
|
|
995
797
|
*/
|
|
996
|
-
const
|
|
997
|
-
name: "classClient",
|
|
998
|
-
renderer: jsxRenderer,
|
|
999
|
-
operations(nodes, ctx) {
|
|
1000
|
-
const { config, driver, resolver, root } = ctx;
|
|
1001
|
-
const { output, group, dataReturnType, paramsCasing, paramsType, pathParamsType, parser, importPath, sdk } = ctx.options;
|
|
1002
|
-
const baseURL = ctx.options.baseURL ?? ctx.meta.baseURL;
|
|
1003
|
-
const pluginTs = driver.getPlugin(pluginTsName);
|
|
1004
|
-
if (!pluginTs) return null;
|
|
1005
|
-
const tsResolver = driver.getResolver(pluginTsName);
|
|
1006
|
-
const tsPluginOptions = pluginTs.options;
|
|
1007
|
-
const pluginZod = isParserEnabled(parser) ? driver.getPlugin(pluginZodName) : null;
|
|
1008
|
-
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
1009
|
-
function buildOperationData(node) {
|
|
1010
|
-
const typeFile = tsResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1011
|
-
root,
|
|
1012
|
-
output: tsPluginOptions?.output ?? output,
|
|
1013
|
-
group: tsPluginOptions?.group
|
|
1014
|
-
});
|
|
1015
|
-
const zodFile = zodResolver && pluginZod?.options ? zodResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1016
|
-
root,
|
|
1017
|
-
output: pluginZod.options?.output ?? output,
|
|
1018
|
-
group: pluginZod.options?.group ?? void 0
|
|
1019
|
-
}) : null;
|
|
1020
|
-
return {
|
|
1021
|
-
node,
|
|
1022
|
-
name: resolver.resolveName(node.operationId),
|
|
1023
|
-
tsResolver,
|
|
1024
|
-
zodResolver,
|
|
1025
|
-
typeFile,
|
|
1026
|
-
zodFile
|
|
1027
|
-
};
|
|
1028
|
-
}
|
|
1029
|
-
const controllers = nodes.reduce((acc, operationNode) => {
|
|
1030
|
-
if (!ast.isHttpOperationNode(operationNode)) return acc;
|
|
1031
|
-
const tag = operationNode.tags[0];
|
|
1032
|
-
const groupName = tag ? group?.name?.({ group: camelCase(tag) }) ?? resolver.resolveGroupName(tag) : resolver.resolveClassName("Client");
|
|
1033
|
-
if (!tag && !group) {
|
|
1034
|
-
const name = resolver.resolveClassName("ApiClient");
|
|
1035
|
-
const file = resolver.resolveFile({
|
|
1036
|
-
name,
|
|
1037
|
-
extname: ".ts"
|
|
1038
|
-
}, {
|
|
1039
|
-
root,
|
|
1040
|
-
output,
|
|
1041
|
-
group: group ?? void 0
|
|
1042
|
-
});
|
|
1043
|
-
const operationData = buildOperationData(operationNode);
|
|
1044
|
-
const previous = acc.find((item) => item.file.path === file.path);
|
|
1045
|
-
if (previous) previous.operations.push(operationData);
|
|
1046
|
-
else acc.push({
|
|
1047
|
-
name,
|
|
1048
|
-
propertyName: resolver.resolveClientPropertyName(name),
|
|
1049
|
-
file,
|
|
1050
|
-
operations: [operationData]
|
|
1051
|
-
});
|
|
1052
|
-
return acc;
|
|
1053
|
-
}
|
|
1054
|
-
if (tag) {
|
|
1055
|
-
const name = groupName;
|
|
1056
|
-
const file = resolver.resolveFile({
|
|
1057
|
-
name,
|
|
1058
|
-
extname: ".ts",
|
|
1059
|
-
tag
|
|
1060
|
-
}, {
|
|
1061
|
-
root,
|
|
1062
|
-
output,
|
|
1063
|
-
group: group ?? void 0
|
|
1064
|
-
});
|
|
1065
|
-
const operationData = buildOperationData(operationNode);
|
|
1066
|
-
const previous = acc.find((item) => item.file.path === file.path);
|
|
1067
|
-
if (previous) previous.operations.push(operationData);
|
|
1068
|
-
else acc.push({
|
|
1069
|
-
name,
|
|
1070
|
-
propertyName: resolver.resolveClientPropertyName(name),
|
|
1071
|
-
file,
|
|
1072
|
-
operations: [operationData]
|
|
1073
|
-
});
|
|
1074
|
-
}
|
|
1075
|
-
return acc;
|
|
1076
|
-
}, []);
|
|
1077
|
-
function collectTypeImports(ops) {
|
|
1078
|
-
const typeImportsByFile = /* @__PURE__ */ new Map();
|
|
1079
|
-
const typeFilesByPath = /* @__PURE__ */ new Map();
|
|
1080
|
-
ops.forEach((op) => {
|
|
1081
|
-
const names = resolveTypeImportNames$1(op.node, tsResolver);
|
|
1082
|
-
if (!typeImportsByFile.has(op.typeFile.path)) typeImportsByFile.set(op.typeFile.path, /* @__PURE__ */ new Set());
|
|
1083
|
-
const imports = typeImportsByFile.get(op.typeFile.path);
|
|
1084
|
-
names.forEach((n) => {
|
|
1085
|
-
imports.add(n);
|
|
1086
|
-
});
|
|
1087
|
-
typeFilesByPath.set(op.typeFile.path, op.typeFile);
|
|
1088
|
-
});
|
|
1089
|
-
return {
|
|
1090
|
-
typeImportsByFile,
|
|
1091
|
-
typeFilesByPath
|
|
1092
|
-
};
|
|
1093
|
-
}
|
|
1094
|
-
function collectZodImports(ops) {
|
|
1095
|
-
const zodImportsByFile = /* @__PURE__ */ new Map();
|
|
1096
|
-
const zodFilesByPath = /* @__PURE__ */ new Map();
|
|
1097
|
-
ops.forEach((op) => {
|
|
1098
|
-
if (!op.zodFile || !zodResolver) return;
|
|
1099
|
-
const names = resolveZodImportNames$1(op.node, zodResolver, parser);
|
|
1100
|
-
if (!zodImportsByFile.has(op.zodFile.path)) zodImportsByFile.set(op.zodFile.path, /* @__PURE__ */ new Set());
|
|
1101
|
-
const imports = zodImportsByFile.get(op.zodFile.path);
|
|
1102
|
-
names.forEach((n) => {
|
|
1103
|
-
imports.add(n);
|
|
1104
|
-
});
|
|
1105
|
-
zodFilesByPath.set(op.zodFile.path, op.zodFile);
|
|
1106
|
-
});
|
|
1107
|
-
return {
|
|
1108
|
-
zodImportsByFile,
|
|
1109
|
-
zodFilesByPath
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
const files = controllers.map(({ name, file, operations: ops }) => {
|
|
1113
|
-
const { typeImportsByFile, typeFilesByPath } = collectTypeImports(ops);
|
|
1114
|
-
const { zodImportsByFile, zodFilesByPath } = isParserEnabled(parser) ? collectZodImports(ops) : {
|
|
1115
|
-
zodImportsByFile: /* @__PURE__ */ new Map(),
|
|
1116
|
-
zodFilesByPath: /* @__PURE__ */ new Map()
|
|
1117
|
-
};
|
|
1118
|
-
const hasFormData = ops.some((op) => op.node.requestBody?.content?.some((e) => e.contentType === "multipart/form-data") ?? false);
|
|
1119
|
-
return /* @__PURE__ */ jsxs(File, {
|
|
1120
|
-
baseName: file.baseName,
|
|
1121
|
-
path: file.path,
|
|
1122
|
-
meta: file.meta,
|
|
1123
|
-
banner: resolver.resolveBanner(ctx.meta, {
|
|
1124
|
-
output,
|
|
1125
|
-
config,
|
|
1126
|
-
file: {
|
|
1127
|
-
path: file.path,
|
|
1128
|
-
baseName: file.baseName
|
|
1129
|
-
}
|
|
1130
|
-
}),
|
|
1131
|
-
footer: resolver.resolveFooter(ctx.meta, {
|
|
1132
|
-
output,
|
|
1133
|
-
config,
|
|
1134
|
-
file: {
|
|
1135
|
-
path: file.path,
|
|
1136
|
-
baseName: file.baseName
|
|
1137
|
-
}
|
|
1138
|
-
}),
|
|
1139
|
-
children: [
|
|
1140
|
-
importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1141
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1142
|
-
name: "client",
|
|
1143
|
-
path: importPath
|
|
1144
|
-
}),
|
|
1145
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1146
|
-
name: ["mergeConfig"],
|
|
1147
|
-
path: importPath
|
|
1148
|
-
}),
|
|
1149
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1150
|
-
name: [
|
|
1151
|
-
"Client",
|
|
1152
|
-
"RequestConfig",
|
|
1153
|
-
"ResponseErrorConfig"
|
|
1154
|
-
],
|
|
1155
|
-
path: importPath,
|
|
1156
|
-
isTypeOnly: true
|
|
1157
|
-
})
|
|
1158
|
-
] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1159
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1160
|
-
name: ["client"],
|
|
1161
|
-
root: file.path,
|
|
1162
|
-
path: path.resolve(root, ".kubb/client.ts")
|
|
1163
|
-
}),
|
|
1164
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1165
|
-
name: ["mergeConfig"],
|
|
1166
|
-
root: file.path,
|
|
1167
|
-
path: path.resolve(root, ".kubb/client.ts")
|
|
1168
|
-
}),
|
|
1169
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1170
|
-
name: [
|
|
1171
|
-
"Client",
|
|
1172
|
-
"RequestConfig",
|
|
1173
|
-
"ResponseErrorConfig"
|
|
1174
|
-
],
|
|
1175
|
-
root: file.path,
|
|
1176
|
-
path: path.resolve(root, ".kubb/client.ts"),
|
|
1177
|
-
isTypeOnly: true
|
|
1178
|
-
})
|
|
1179
|
-
] }),
|
|
1180
|
-
hasFormData && /* @__PURE__ */ jsx(File.Import, {
|
|
1181
|
-
name: ["buildFormData"],
|
|
1182
|
-
root: file.path,
|
|
1183
|
-
path: path.resolve(root, ".kubb/config.ts")
|
|
1184
|
-
}),
|
|
1185
|
-
parser === "zod" && zodResolver && ops.some((op) => op.node.requestBody?.content?.[0]?.schema != null) && /* @__PURE__ */ jsx(File.Import, {
|
|
1186
|
-
name: ["z"],
|
|
1187
|
-
path: "zod",
|
|
1188
|
-
isTypeOnly: true
|
|
1189
|
-
}),
|
|
1190
|
-
Array.from(typeImportsByFile.entries()).map(([filePath, importSet]) => {
|
|
1191
|
-
const typeFile = typeFilesByPath.get(filePath);
|
|
1192
|
-
if (!typeFile) return null;
|
|
1193
|
-
const importNames = Array.from(importSet).filter(Boolean);
|
|
1194
|
-
if (importNames.length === 0) return null;
|
|
1195
|
-
return /* @__PURE__ */ jsx(File.Import, {
|
|
1196
|
-
name: importNames,
|
|
1197
|
-
root: file.path,
|
|
1198
|
-
path: typeFile.path,
|
|
1199
|
-
isTypeOnly: true
|
|
1200
|
-
}, filePath);
|
|
1201
|
-
}),
|
|
1202
|
-
isParserEnabled(parser) && Array.from(zodImportsByFile.entries()).map(([filePath, importSet]) => {
|
|
1203
|
-
const zodFile = zodFilesByPath.get(filePath);
|
|
1204
|
-
if (!zodFile) return null;
|
|
1205
|
-
const importNames = Array.from(importSet).filter(Boolean);
|
|
1206
|
-
if (importNames.length === 0) return null;
|
|
1207
|
-
return /* @__PURE__ */ jsx(File.Import, {
|
|
1208
|
-
name: importNames,
|
|
1209
|
-
root: file.path,
|
|
1210
|
-
path: zodFile.path
|
|
1211
|
-
}, filePath);
|
|
1212
|
-
}),
|
|
1213
|
-
/* @__PURE__ */ jsx(ClassClient, {
|
|
1214
|
-
name,
|
|
1215
|
-
operations: ops,
|
|
1216
|
-
baseURL,
|
|
1217
|
-
dataReturnType,
|
|
1218
|
-
pathParamsType,
|
|
1219
|
-
paramsCasing,
|
|
1220
|
-
paramsType,
|
|
1221
|
-
parser
|
|
1222
|
-
})
|
|
1223
|
-
]
|
|
1224
|
-
}, file.path);
|
|
1225
|
-
});
|
|
1226
|
-
if (sdk) {
|
|
1227
|
-
const sdkFile = resolver.resolveFile({
|
|
1228
|
-
name: sdk.className,
|
|
1229
|
-
extname: ".ts"
|
|
1230
|
-
}, {
|
|
1231
|
-
root,
|
|
1232
|
-
output,
|
|
1233
|
-
group: group ?? void 0
|
|
1234
|
-
});
|
|
1235
|
-
files.push(/* @__PURE__ */ jsxs(File, {
|
|
1236
|
-
baseName: sdkFile.baseName,
|
|
1237
|
-
path: sdkFile.path,
|
|
1238
|
-
meta: sdkFile.meta,
|
|
1239
|
-
banner: resolver.resolveBanner(ctx.meta, {
|
|
1240
|
-
output,
|
|
1241
|
-
config,
|
|
1242
|
-
file: {
|
|
1243
|
-
path: sdkFile.path,
|
|
1244
|
-
baseName: sdkFile.baseName
|
|
1245
|
-
}
|
|
1246
|
-
}),
|
|
1247
|
-
footer: resolver.resolveFooter(ctx.meta, {
|
|
1248
|
-
output,
|
|
1249
|
-
config,
|
|
1250
|
-
file: {
|
|
1251
|
-
path: sdkFile.path,
|
|
1252
|
-
baseName: sdkFile.baseName
|
|
1253
|
-
}
|
|
1254
|
-
}),
|
|
1255
|
-
children: [
|
|
1256
|
-
importPath ? /* @__PURE__ */ jsx(File.Import, {
|
|
1257
|
-
name: ["Client", "RequestConfig"],
|
|
1258
|
-
path: importPath,
|
|
1259
|
-
isTypeOnly: true
|
|
1260
|
-
}) : /* @__PURE__ */ jsx(File.Import, {
|
|
1261
|
-
name: ["Client", "RequestConfig"],
|
|
1262
|
-
root: sdkFile.path,
|
|
1263
|
-
path: path.resolve(root, ".kubb/client.ts"),
|
|
1264
|
-
isTypeOnly: true
|
|
1265
|
-
}),
|
|
1266
|
-
controllers.map(({ name, file }) => /* @__PURE__ */ jsx(File.Import, {
|
|
1267
|
-
name: [name],
|
|
1268
|
-
root: sdkFile.path,
|
|
1269
|
-
path: file.path
|
|
1270
|
-
}, name)),
|
|
1271
|
-
/* @__PURE__ */ jsx(WrapperClient, {
|
|
1272
|
-
name: sdk.className,
|
|
1273
|
-
controllers: controllers.map(({ name, propertyName }) => ({
|
|
1274
|
-
className: name,
|
|
1275
|
-
propertyName
|
|
1276
|
-
}))
|
|
1277
|
-
})
|
|
1278
|
-
]
|
|
1279
|
-
}, sdkFile.path));
|
|
1280
|
-
}
|
|
1281
|
-
return /* @__PURE__ */ jsx(Fragment, { children: files });
|
|
1282
|
-
}
|
|
1283
|
-
});
|
|
1284
|
-
//#endregion
|
|
1285
|
-
//#region src/generators/clientGenerator.tsx
|
|
798
|
+
const MISSING_OPERATION_TYPES_WARNING = "Skipped: no operation types available. Add `pluginTs()`, or `pluginZod({ inferred: true })` to type the client from its zod schemas.";
|
|
1286
799
|
/**
|
|
1287
|
-
*
|
|
1288
|
-
*
|
|
1289
|
-
* `
|
|
800
|
+
* Picks the plugin a generated client takes its `Options` and `Responses` types from.
|
|
801
|
+
*
|
|
802
|
+
* `plugin-ts` wins whenever it is in the pipeline, so existing configs keep the types they generate
|
|
803
|
+
* today. Without it, `pluginZod({ inferred: true })` takes over: its inferred options and responses
|
|
804
|
+
* types are built from the same shared schemas as the `plugin-ts` ones, so a client typed off
|
|
805
|
+
* `z.infer` carries what the codecs decode to (a `Temporal` instance, a `Date`) rather than the raw
|
|
806
|
+
* wire type. Returns `null` when neither is available, leaving the caller nothing to type against.
|
|
807
|
+
*
|
|
808
|
+
* @example
|
|
809
|
+
* ```ts
|
|
810
|
+
* const types = resolveOperationTypes(ctx.driver)
|
|
811
|
+
* if (!types) return null
|
|
812
|
+
* types.response.options(node) // 'GetPetByIdOptions', or 'GetPetByIdOptionsSchemaType' from zod
|
|
813
|
+
* ```
|
|
1290
814
|
*/
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
if (!pluginTs) return null;
|
|
1301
|
-
const tsResolver = driver.getResolver(pluginTsName);
|
|
1302
|
-
const pluginZod = isParserEnabled(parser) ? driver.getPlugin(pluginZodName) : null;
|
|
1303
|
-
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
1304
|
-
const importedTypeNames = resolveOperationTypeNames(node, tsResolver, { paramsCasing });
|
|
1305
|
-
const { query: queryParams } = getOperationParameters(node);
|
|
1306
|
-
const importedZodNames = zodResolver ? [
|
|
1307
|
-
resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
|
|
1308
|
-
resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
|
|
1309
|
-
resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
|
|
1310
|
-
].filter((name) => Boolean(name)) : [];
|
|
1311
|
-
const zodRequestName = zodResolver && parser === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) ?? null : null;
|
|
1312
|
-
const meta = {
|
|
1313
|
-
name: resolver.resolveName(node.operationId),
|
|
1314
|
-
urlName: resolver.resolveUrlName(node),
|
|
1315
|
-
file: resolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1316
|
-
root,
|
|
1317
|
-
output,
|
|
1318
|
-
group: group ?? void 0
|
|
1319
|
-
}),
|
|
1320
|
-
fileTs: tsResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1321
|
-
root,
|
|
1322
|
-
output: pluginTs.options?.output ?? output,
|
|
1323
|
-
group: pluginTs.options?.group ?? void 0
|
|
1324
|
-
}),
|
|
1325
|
-
fileZod: zodResolver && pluginZod?.options ? zodResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1326
|
-
root,
|
|
1327
|
-
output: pluginZod.options.output ?? output,
|
|
1328
|
-
group: pluginZod.options?.group ?? void 0
|
|
1329
|
-
}) : null
|
|
815
|
+
function resolveOperationTypes(driver) {
|
|
816
|
+
const pluginTs = driver.getPlugin(pluginTsName);
|
|
817
|
+
if (pluginTs) {
|
|
818
|
+
const resolver = driver.getResolver(pluginTsName);
|
|
819
|
+
return {
|
|
820
|
+
response: resolver.response,
|
|
821
|
+
resolver,
|
|
822
|
+
output: pluginTs.options?.output,
|
|
823
|
+
group: pluginTs.options?.group
|
|
1330
824
|
};
|
|
1331
|
-
const hasFormData = node.requestBody?.content?.some((e) => e.contentType === "multipart/form-data") ?? false;
|
|
1332
|
-
return /* @__PURE__ */ jsxs(File, {
|
|
1333
|
-
baseName: meta.file.baseName,
|
|
1334
|
-
path: meta.file.path,
|
|
1335
|
-
meta: meta.file.meta,
|
|
1336
|
-
banner: resolver.resolveBanner(ctx.meta, {
|
|
1337
|
-
output,
|
|
1338
|
-
config,
|
|
1339
|
-
file: {
|
|
1340
|
-
path: meta.file.path,
|
|
1341
|
-
baseName: meta.file.baseName
|
|
1342
|
-
}
|
|
1343
|
-
}),
|
|
1344
|
-
footer: resolver.resolveFooter(ctx.meta, {
|
|
1345
|
-
output,
|
|
1346
|
-
config,
|
|
1347
|
-
file: {
|
|
1348
|
-
path: meta.file.path,
|
|
1349
|
-
baseName: meta.file.baseName
|
|
1350
|
-
}
|
|
1351
|
-
}),
|
|
1352
|
-
children: [
|
|
1353
|
-
importPath ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Import, {
|
|
1354
|
-
name: "client",
|
|
1355
|
-
path: importPath
|
|
1356
|
-
}), /* @__PURE__ */ jsx(File.Import, {
|
|
1357
|
-
name: [
|
|
1358
|
-
"Client",
|
|
1359
|
-
"RequestConfig",
|
|
1360
|
-
"ResponseErrorConfig"
|
|
1361
|
-
],
|
|
1362
|
-
path: importPath,
|
|
1363
|
-
isTypeOnly: true
|
|
1364
|
-
})] }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(File.Import, {
|
|
1365
|
-
name: ["client"],
|
|
1366
|
-
root: meta.file.path,
|
|
1367
|
-
path: path.resolve(root, ".kubb/client.ts")
|
|
1368
|
-
}), /* @__PURE__ */ jsx(File.Import, {
|
|
1369
|
-
name: [
|
|
1370
|
-
"Client",
|
|
1371
|
-
"RequestConfig",
|
|
1372
|
-
"ResponseErrorConfig"
|
|
1373
|
-
],
|
|
1374
|
-
root: meta.file.path,
|
|
1375
|
-
path: path.resolve(root, ".kubb/client.ts"),
|
|
1376
|
-
isTypeOnly: true
|
|
1377
|
-
})] }),
|
|
1378
|
-
hasFormData && /* @__PURE__ */ jsx(File.Import, {
|
|
1379
|
-
name: ["buildFormData"],
|
|
1380
|
-
root: meta.file.path,
|
|
1381
|
-
path: path.resolve(root, ".kubb/config.ts")
|
|
1382
|
-
}),
|
|
1383
|
-
zodRequestName && /* @__PURE__ */ jsx(File.Import, {
|
|
1384
|
-
name: ["z"],
|
|
1385
|
-
path: "zod",
|
|
1386
|
-
isTypeOnly: true
|
|
1387
|
-
}),
|
|
1388
|
-
meta.fileZod && importedZodNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
1389
|
-
name: importedZodNames,
|
|
1390
|
-
root: meta.file.path,
|
|
1391
|
-
path: meta.fileZod.path
|
|
1392
|
-
}),
|
|
1393
|
-
meta.fileTs && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
1394
|
-
name: Array.from(new Set(importedTypeNames)),
|
|
1395
|
-
root: meta.file.path,
|
|
1396
|
-
path: meta.fileTs.path,
|
|
1397
|
-
isTypeOnly: true
|
|
1398
|
-
}),
|
|
1399
|
-
/* @__PURE__ */ jsx(Url, {
|
|
1400
|
-
name: meta.urlName,
|
|
1401
|
-
baseURL,
|
|
1402
|
-
pathParamsType,
|
|
1403
|
-
paramsCasing,
|
|
1404
|
-
paramsType,
|
|
1405
|
-
node,
|
|
1406
|
-
tsResolver,
|
|
1407
|
-
isIndexable: urlType === "export",
|
|
1408
|
-
isExportable: urlType === "export"
|
|
1409
|
-
}),
|
|
1410
|
-
/* @__PURE__ */ jsx(Client, {
|
|
1411
|
-
name: meta.name,
|
|
1412
|
-
urlName: meta.urlName,
|
|
1413
|
-
baseURL,
|
|
1414
|
-
dataReturnType,
|
|
1415
|
-
pathParamsType,
|
|
1416
|
-
paramsCasing,
|
|
1417
|
-
paramsType,
|
|
1418
|
-
node,
|
|
1419
|
-
tsResolver,
|
|
1420
|
-
zodResolver,
|
|
1421
|
-
parser
|
|
1422
|
-
})
|
|
1423
|
-
]
|
|
1424
|
-
});
|
|
1425
825
|
}
|
|
1426
|
-
|
|
826
|
+
const pluginZod = driver.getPlugin(pluginZodName);
|
|
827
|
+
if (!pluginZod?.options?.inferred) return null;
|
|
828
|
+
const resolver = driver.getResolver(pluginZodName);
|
|
829
|
+
return {
|
|
830
|
+
response: {
|
|
831
|
+
options: resolver.response.options,
|
|
832
|
+
responses: (node) => resolver.schema.type(resolver.response.responses(node))
|
|
833
|
+
},
|
|
834
|
+
resolver,
|
|
835
|
+
output: pluginZod.options.output,
|
|
836
|
+
group: pluginZod.options.group
|
|
837
|
+
};
|
|
838
|
+
}
|
|
1427
839
|
//#endregion
|
|
1428
|
-
//#region src/generators/
|
|
840
|
+
//#region ../../internals/client/src/generators/clientGenerator.tsx
|
|
1429
841
|
/**
|
|
1430
|
-
*
|
|
1431
|
-
*
|
|
1432
|
-
* `
|
|
1433
|
-
*
|
|
842
|
+
* Builds the built-in per-operation generator shared by the client plugins (`@kubb/plugin-fetch`,
|
|
843
|
+
* `@kubb/plugin-axios`). Emits one async function per OpenAPI operation using the shared
|
|
844
|
+
* `Operation` component: a grouped `<Name>Request` type and a function that forwards a single
|
|
845
|
+
* `options` object to the bundled `client` and returns the `Unwrappable<RequestResult>`. Only the
|
|
846
|
+
* generator `name` differs between plugins. Every other resolution, import, and rendering step is
|
|
847
|
+
* identical.
|
|
1434
848
|
*/
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
849
|
+
function createClientGenerator(name, resolveClientPath) {
|
|
850
|
+
return defineGenerator({
|
|
851
|
+
name,
|
|
852
|
+
renderer: jsxRenderer,
|
|
853
|
+
operation(node, ctx) {
|
|
854
|
+
if (!ast.isHttpOperationNode(node)) return null;
|
|
855
|
+
const { config, driver, resolver, root } = ctx;
|
|
856
|
+
const { output, validator, returnType, throwOnErrorDefault, group } = ctx.options;
|
|
857
|
+
const types = resolveOperationTypes(driver);
|
|
858
|
+
if (!types) {
|
|
859
|
+
ctx.warn(MISSING_OPERATION_TYPES_WARNING);
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
const pluginZod = resolveResponseValidator(validator) === "zod" || resolveRequestValidator(validator) === "zod" ? driver.getPlugin(pluginZodName) : null;
|
|
863
|
+
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
864
|
+
const hasRequestBody = Boolean(node.requestBody?.content?.[0]?.schema);
|
|
865
|
+
const importedTypeNames = [types.response.options(node), types.response.responses(node)];
|
|
866
|
+
const importedZodNames = zodResolver ? [
|
|
867
|
+
resolveResponseValidator(validator) === "zod" ? zodResolver.response.response?.(node) : null,
|
|
868
|
+
resolveResponseValidator(validator) === "zod" ? buildZodErrorParse(node, zodResolver)?.expression ?? null : null,
|
|
869
|
+
resolveRequestValidator(validator) === "zod" && hasRequestBody ? zodResolver.response.body?.(node) : null
|
|
870
|
+
].filter((name) => Boolean(name)) : [];
|
|
871
|
+
const meta = {
|
|
872
|
+
name: resolver.name(node.operationId),
|
|
873
|
+
file: resolver.file({
|
|
874
|
+
...operationFileEntry(node, node.operationId),
|
|
1461
875
|
root,
|
|
1462
876
|
output,
|
|
1463
877
|
group: group ?? void 0
|
|
1464
|
-
});
|
|
1465
|
-
const client = {
|
|
1466
|
-
name: resolver.resolveName(operationNode.operationId),
|
|
1467
|
-
file: clientFile
|
|
1468
|
-
};
|
|
1469
|
-
const previous = acc.find((item) => item.file.path === file.path);
|
|
1470
|
-
if (previous) previous.clients.push(client);
|
|
1471
|
-
else acc.push({
|
|
1472
|
-
name,
|
|
1473
|
-
file,
|
|
1474
|
-
clients: [client]
|
|
1475
|
-
});
|
|
1476
|
-
}
|
|
1477
|
-
return acc;
|
|
1478
|
-
}, []).map(({ name, file, clients }) => {
|
|
1479
|
-
return /* @__PURE__ */ jsxs(File, {
|
|
1480
|
-
baseName: file.baseName,
|
|
1481
|
-
path: file.path,
|
|
1482
|
-
meta: file.meta,
|
|
1483
|
-
banner: resolver.resolveBanner(ctx.meta, {
|
|
1484
|
-
output,
|
|
1485
|
-
config,
|
|
1486
|
-
file: {
|
|
1487
|
-
path: file.path,
|
|
1488
|
-
baseName: file.baseName,
|
|
1489
|
-
isAggregation: true
|
|
1490
|
-
}
|
|
1491
878
|
}),
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
path: file.path,
|
|
1497
|
-
baseName: file.baseName,
|
|
1498
|
-
isAggregation: true
|
|
1499
|
-
}
|
|
1500
|
-
}),
|
|
1501
|
-
children: [clients.map((client) => /* @__PURE__ */ jsx(File.Import, {
|
|
1502
|
-
name: [client.name],
|
|
1503
|
-
root: file.path,
|
|
1504
|
-
path: client.file.path
|
|
1505
|
-
}, client.name)), /* @__PURE__ */ jsx(File.Source, {
|
|
1506
|
-
name,
|
|
1507
|
-
isExportable: true,
|
|
1508
|
-
isIndexable: true,
|
|
1509
|
-
children: /* @__PURE__ */ jsx(Function, {
|
|
1510
|
-
export: true,
|
|
1511
|
-
name,
|
|
1512
|
-
children: `return { ${clients.map((client) => client.name).join(", ")} }`
|
|
1513
|
-
})
|
|
1514
|
-
})]
|
|
1515
|
-
}, file.path);
|
|
1516
|
-
}) });
|
|
1517
|
-
}
|
|
1518
|
-
});
|
|
1519
|
-
//#endregion
|
|
1520
|
-
//#region src/generators/operationsGenerator.ts
|
|
1521
|
-
/**
|
|
1522
|
-
* Generates an `operations.ts` file that re-exports every operation grouped
|
|
1523
|
-
* by HTTP method. Enabled when `pluginClient({ operations: true })`. Useful
|
|
1524
|
-
* for building meta-tooling on top of the generated client (route
|
|
1525
|
-
* registries, API explorers).
|
|
1526
|
-
*/
|
|
1527
|
-
const operationsGenerator = defineGenerator({
|
|
1528
|
-
name: "client",
|
|
1529
|
-
operations(nodes, ctx) {
|
|
1530
|
-
const { config, resolver, root } = ctx;
|
|
1531
|
-
const { output, group } = ctx.options;
|
|
1532
|
-
const name = "operations";
|
|
1533
|
-
const file = resolver.resolveFile({
|
|
1534
|
-
name,
|
|
1535
|
-
extname: ".ts"
|
|
1536
|
-
}, {
|
|
1537
|
-
root,
|
|
1538
|
-
output,
|
|
1539
|
-
group: group ?? void 0
|
|
1540
|
-
});
|
|
1541
|
-
const operationsObject = {};
|
|
1542
|
-
for (const node of nodes) {
|
|
1543
|
-
if (!ast.isHttpOperationNode(node)) continue;
|
|
1544
|
-
operationsObject[node.operationId] = {
|
|
1545
|
-
path: Url$1.toPath(node.path),
|
|
1546
|
-
method: node.method.toLowerCase()
|
|
1547
|
-
};
|
|
1548
|
-
}
|
|
1549
|
-
return [ast.createFile({
|
|
1550
|
-
baseName: file.baseName,
|
|
1551
|
-
path: file.path,
|
|
1552
|
-
meta: file.meta,
|
|
1553
|
-
banner: resolver.resolveBanner(ctx.meta, {
|
|
1554
|
-
output,
|
|
1555
|
-
config,
|
|
1556
|
-
file: {
|
|
1557
|
-
path: file.path,
|
|
1558
|
-
baseName: file.baseName
|
|
1559
|
-
}
|
|
1560
|
-
}),
|
|
1561
|
-
footer: resolver.resolveFooter(ctx.meta, {
|
|
1562
|
-
output,
|
|
1563
|
-
config,
|
|
1564
|
-
file: {
|
|
1565
|
-
path: file.path,
|
|
1566
|
-
baseName: file.baseName
|
|
1567
|
-
}
|
|
1568
|
-
}),
|
|
1569
|
-
sources: [ast.createSource({
|
|
1570
|
-
name,
|
|
1571
|
-
isExportable: true,
|
|
1572
|
-
isIndexable: true,
|
|
1573
|
-
nodes: [ast.createConst({
|
|
1574
|
-
name,
|
|
1575
|
-
export: true,
|
|
1576
|
-
nodes: [ast.createText(JSON.stringify(operationsObject, void 0, 2))]
|
|
1577
|
-
})]
|
|
1578
|
-
})]
|
|
1579
|
-
})];
|
|
1580
|
-
}
|
|
1581
|
-
});
|
|
1582
|
-
//#endregion
|
|
1583
|
-
//#region src/components/StaticClassClient.tsx
|
|
1584
|
-
const declarationPrinter = functionPrinter({ mode: "declaration" });
|
|
1585
|
-
function generateMethod({ node, name, tsResolver, zodResolver, baseURL, dataReturnType, parser, paramsType, paramsCasing, pathParamsType }) {
|
|
1586
|
-
if (!ast.isHttpOperationNode(node)) return "";
|
|
1587
|
-
const { defaultContentType: contentType, isMultipleContentTypes, hasFormData } = getContentTypeInfo(node);
|
|
1588
|
-
const isFormData = !isMultipleContentTypes && contentType === "multipart/form-data";
|
|
1589
|
-
const { header: headerParams } = getOperationParameters(node);
|
|
1590
|
-
const headerParamsName = headerParams.length > 0 ? tsResolver.resolveHeaderParamsName(node, headerParams[0]) : null;
|
|
1591
|
-
const headers = isMultipleContentTypes ? headerParamsName ? ["...headers"] : [] : buildHeaders(contentType, !!headerParamsName);
|
|
1592
|
-
const generics = buildGenerics(node, tsResolver, {
|
|
1593
|
-
dataReturnType,
|
|
1594
|
-
zodResolver,
|
|
1595
|
-
parser
|
|
1596
|
-
});
|
|
1597
|
-
const paramsNode = buildClientParamsNode({
|
|
1598
|
-
paramsType,
|
|
1599
|
-
paramsCasing,
|
|
1600
|
-
pathParamsType,
|
|
1601
|
-
node,
|
|
1602
|
-
tsResolver,
|
|
1603
|
-
isConfigurable: true
|
|
1604
|
-
});
|
|
1605
|
-
const paramsSignature = declarationPrinter.print(paramsNode) ?? "";
|
|
1606
|
-
const { query: queryParams } = getOperationParameters(node);
|
|
1607
|
-
const zodQueryParamsName = zodResolver && resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null;
|
|
1608
|
-
const clientParams = buildClassClientParams({
|
|
1609
|
-
node,
|
|
1610
|
-
url: Url$1.toTemplateString(node.path, { casing: paramsCasing }),
|
|
1611
|
-
baseURL,
|
|
1612
|
-
tsResolver,
|
|
1613
|
-
isFormData,
|
|
1614
|
-
isMultipleContentTypes,
|
|
1615
|
-
hasFormData,
|
|
1616
|
-
headers,
|
|
1617
|
-
zodQueryParamsName
|
|
1618
|
-
});
|
|
1619
|
-
const jsdoc = buildJSDoc(buildOperationComments(node, {
|
|
1620
|
-
link: "urlPath",
|
|
1621
|
-
linkPosition: "beforeDeprecated",
|
|
1622
|
-
splitLines: true
|
|
1623
|
-
}));
|
|
1624
|
-
const requestDataLine = buildRequestDataLine({
|
|
1625
|
-
parser,
|
|
1626
|
-
node,
|
|
1627
|
-
zodResolver
|
|
1628
|
-
});
|
|
1629
|
-
const queryParamsLine = buildQueryParamsLine({
|
|
1630
|
-
parser,
|
|
1631
|
-
node,
|
|
1632
|
-
zodResolver
|
|
1633
|
-
});
|
|
1634
|
-
const formDataLine = buildFormDataLine(isFormData || isMultipleContentTypes && hasFormData, !!node.requestBody?.content?.[0]?.schema);
|
|
1635
|
-
const returnStatement = buildReturnStatement({
|
|
1636
|
-
dataReturnType,
|
|
1637
|
-
parser,
|
|
1638
|
-
node,
|
|
1639
|
-
zodResolver,
|
|
1640
|
-
tsResolver
|
|
1641
|
-
});
|
|
1642
|
-
return `${jsdoc} static async ${name}(${paramsSignature}) {\n${[
|
|
1643
|
-
`const { client: request = client, ${isMultipleContentTypes ? `contentType = ${stringify(contentType)}, ` : ""}...requestConfig } = mergeConfig(this.#config, config)`,
|
|
1644
|
-
"",
|
|
1645
|
-
requestDataLine,
|
|
1646
|
-
queryParamsLine,
|
|
1647
|
-
formDataLine,
|
|
1648
|
-
`const res = await request<${generics.join(", ")}>(${clientParams.toCall()})`,
|
|
1649
|
-
returnStatement
|
|
1650
|
-
].filter(Boolean).map((line) => ` ${line}`).join("\n")}\n }`;
|
|
1651
|
-
}
|
|
1652
|
-
function StaticClassClient({ name, isExportable = true, isIndexable = true, operations, baseURL, dataReturnType, parser, paramsType, paramsCasing, pathParamsType, children }) {
|
|
1653
|
-
const classCode = `export class ${name} {\n static #config: Partial<RequestConfig> & { client?: Client } = {}\n\n${operations.map(({ node, name: methodName, tsResolver, zodResolver }) => generateMethod({
|
|
1654
|
-
node,
|
|
1655
|
-
name: methodName,
|
|
1656
|
-
tsResolver,
|
|
1657
|
-
zodResolver,
|
|
1658
|
-
baseURL,
|
|
1659
|
-
dataReturnType,
|
|
1660
|
-
parser,
|
|
1661
|
-
paramsType,
|
|
1662
|
-
paramsCasing,
|
|
1663
|
-
pathParamsType
|
|
1664
|
-
})).join("\n\n")}\n}`;
|
|
1665
|
-
return /* @__PURE__ */ jsxs(File.Source, {
|
|
1666
|
-
name,
|
|
1667
|
-
isExportable,
|
|
1668
|
-
isIndexable,
|
|
1669
|
-
children: [classCode, children]
|
|
1670
|
-
});
|
|
1671
|
-
}
|
|
1672
|
-
//#endregion
|
|
1673
|
-
//#region src/generators/staticClassClientGenerator.tsx
|
|
1674
|
-
function resolveTypeImportNames(node, tsResolver) {
|
|
1675
|
-
return resolveOperationTypeNames(node, tsResolver, { order: "body-response-first" });
|
|
1676
|
-
}
|
|
1677
|
-
function resolveZodImportNames(node, zodResolver, parser) {
|
|
1678
|
-
const { query: queryParams } = getOperationParameters(node);
|
|
1679
|
-
return [
|
|
1680
|
-
resolveResponseParser(parser) === "zod" ? zodResolver.resolveResponseName?.(node) : null,
|
|
1681
|
-
resolveRequestParser(parser) === "zod" && node.requestBody?.content?.[0]?.schema ? zodResolver.resolveDataName?.(node) : null,
|
|
1682
|
-
resolveQueryParamsParser(parser) === "zod" && queryParams.length > 0 ? zodResolver.resolveQueryParamsName?.(node, queryParams[0]) : null
|
|
1683
|
-
].filter((n) => Boolean(n));
|
|
1684
|
-
}
|
|
1685
|
-
/**
|
|
1686
|
-
* Built-in `operations` generator for `@kubb/plugin-client` when
|
|
1687
|
-
* `clientType: 'staticClass'`. Emits one class per tag, with a static method
|
|
1688
|
-
* per operation so callers can use `Pet.getPetById(...)` without
|
|
1689
|
-
* instantiating the class.
|
|
1690
|
-
*/
|
|
1691
|
-
const staticClassClientGenerator = defineGenerator({
|
|
1692
|
-
name: "staticClassClient",
|
|
1693
|
-
renderer: jsxRenderer,
|
|
1694
|
-
operations(nodes, ctx) {
|
|
1695
|
-
const { config, driver, resolver, root } = ctx;
|
|
1696
|
-
const { output, group, dataReturnType, paramsCasing, paramsType, pathParamsType, parser, importPath } = ctx.options;
|
|
1697
|
-
const baseURL = ctx.options.baseURL ?? ctx.meta.baseURL;
|
|
1698
|
-
const pluginTs = driver.getPlugin(pluginTsName);
|
|
1699
|
-
if (!pluginTs) return null;
|
|
1700
|
-
const tsResolver = driver.getResolver(pluginTsName);
|
|
1701
|
-
const tsPluginOptions = pluginTs.options;
|
|
1702
|
-
const pluginZod = isParserEnabled(parser) ? driver.getPlugin(pluginZodName) : null;
|
|
1703
|
-
const zodResolver = pluginZod ? driver.getResolver(pluginZodName) : null;
|
|
1704
|
-
function buildOperationData(node) {
|
|
1705
|
-
const typeFile = tsResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1706
|
-
root,
|
|
1707
|
-
output: tsPluginOptions?.output ?? output,
|
|
1708
|
-
group: tsPluginOptions?.group
|
|
1709
|
-
});
|
|
1710
|
-
const zodFile = zodResolver && pluginZod?.options ? zodResolver.resolveFile(operationFileEntry(node, node.operationId), {
|
|
1711
|
-
root,
|
|
1712
|
-
output: pluginZod.options?.output ?? output,
|
|
1713
|
-
group: pluginZod.options?.group ?? void 0
|
|
1714
|
-
}) : null;
|
|
1715
|
-
return {
|
|
1716
|
-
node,
|
|
1717
|
-
name: resolver.resolveName(node.operationId),
|
|
1718
|
-
tsResolver,
|
|
1719
|
-
zodResolver,
|
|
1720
|
-
typeFile,
|
|
1721
|
-
zodFile
|
|
1722
|
-
};
|
|
1723
|
-
}
|
|
1724
|
-
const controllers = nodes.reduce((acc, operationNode) => {
|
|
1725
|
-
if (!ast.isHttpOperationNode(operationNode)) return acc;
|
|
1726
|
-
const tag = operationNode.tags[0];
|
|
1727
|
-
const groupName = tag ? group?.name?.({ group: camelCase(tag) }) ?? resolver.resolveGroupName(tag) : resolver.resolveClassName("Client");
|
|
1728
|
-
if (!tag && !group) {
|
|
1729
|
-
const name = resolver.resolveClassName("ApiClient");
|
|
1730
|
-
const file = resolver.resolveFile({
|
|
1731
|
-
name,
|
|
1732
|
-
extname: ".ts"
|
|
1733
|
-
}, {
|
|
879
|
+
fileTypes: resolveDependencyOperationFile({
|
|
880
|
+
cache: ctx.cache,
|
|
881
|
+
node,
|
|
882
|
+
resolver: types.resolver,
|
|
1734
883
|
root,
|
|
1735
|
-
output,
|
|
1736
|
-
group: group
|
|
1737
|
-
})
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
if (previous) previous.operations.push(operationData);
|
|
1741
|
-
else acc.push({
|
|
1742
|
-
name,
|
|
1743
|
-
file,
|
|
1744
|
-
operations: [operationData]
|
|
1745
|
-
});
|
|
1746
|
-
return acc;
|
|
1747
|
-
}
|
|
1748
|
-
if (tag) {
|
|
1749
|
-
const name = groupName;
|
|
1750
|
-
const file = resolver.resolveFile({
|
|
1751
|
-
name,
|
|
1752
|
-
extname: ".ts",
|
|
1753
|
-
tag
|
|
1754
|
-
}, {
|
|
884
|
+
output: types.output ?? output,
|
|
885
|
+
group: types.group
|
|
886
|
+
}),
|
|
887
|
+
fileZod: zodResolver && pluginZod?.options ? zodResolver.file({
|
|
888
|
+
...operationFileEntry(node, node.operationId),
|
|
1755
889
|
root,
|
|
1756
|
-
output,
|
|
1757
|
-
group: group ?? void 0
|
|
1758
|
-
})
|
|
1759
|
-
const operationData = buildOperationData(operationNode);
|
|
1760
|
-
const previous = acc.find((item) => item.file.path === file.path);
|
|
1761
|
-
if (previous) previous.operations.push(operationData);
|
|
1762
|
-
else acc.push({
|
|
1763
|
-
name,
|
|
1764
|
-
file,
|
|
1765
|
-
operations: [operationData]
|
|
1766
|
-
});
|
|
1767
|
-
}
|
|
1768
|
-
return acc;
|
|
1769
|
-
}, []);
|
|
1770
|
-
function collectTypeImports(ops) {
|
|
1771
|
-
const typeImportsByFile = /* @__PURE__ */ new Map();
|
|
1772
|
-
const typeFilesByPath = /* @__PURE__ */ new Map();
|
|
1773
|
-
ops.forEach((op) => {
|
|
1774
|
-
const names = resolveTypeImportNames(op.node, tsResolver);
|
|
1775
|
-
if (!typeImportsByFile.has(op.typeFile.path)) typeImportsByFile.set(op.typeFile.path, /* @__PURE__ */ new Set());
|
|
1776
|
-
const imports = typeImportsByFile.get(op.typeFile.path);
|
|
1777
|
-
names.forEach((n) => {
|
|
1778
|
-
imports.add(n);
|
|
1779
|
-
});
|
|
1780
|
-
typeFilesByPath.set(op.typeFile.path, op.typeFile);
|
|
1781
|
-
});
|
|
1782
|
-
return {
|
|
1783
|
-
typeImportsByFile,
|
|
1784
|
-
typeFilesByPath
|
|
890
|
+
output: pluginZod.options.output ?? output,
|
|
891
|
+
group: pluginZod.options?.group ?? void 0
|
|
892
|
+
}) : null
|
|
1785
893
|
};
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
ops.forEach((op) => {
|
|
1791
|
-
if (!op.zodFile || !zodResolver) return;
|
|
1792
|
-
const names = resolveZodImportNames(op.node, zodResolver, parser);
|
|
1793
|
-
if (!zodImportsByFile.has(op.zodFile.path)) zodImportsByFile.set(op.zodFile.path, /* @__PURE__ */ new Set());
|
|
1794
|
-
const imports = zodImportsByFile.get(op.zodFile.path);
|
|
1795
|
-
names.forEach((n) => {
|
|
1796
|
-
imports.add(n);
|
|
1797
|
-
});
|
|
1798
|
-
zodFilesByPath.set(op.zodFile.path, op.zodFile);
|
|
894
|
+
const security = getOperationSecurity({
|
|
895
|
+
document: ctx.adapter.document,
|
|
896
|
+
method: node.method,
|
|
897
|
+
path: node.path
|
|
1799
898
|
});
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
899
|
+
const customClientPath = resolveClientPath?.(ctx.options, root);
|
|
900
|
+
const clientPath = customClientPath ?? path.resolve(root, ".kubb/client.ts");
|
|
901
|
+
const clientRoot = customClientPath === void 0 ? meta.file.path : void 0;
|
|
902
|
+
const eventStream = isEventStream(node);
|
|
903
|
+
const clientValueImports = (() => {
|
|
904
|
+
if (eventStream) return ["client", "toEventStream"];
|
|
905
|
+
if (returnType === "plain") return ["client"];
|
|
906
|
+
if (returnType === "data") return ["client", "unwrapResult"];
|
|
907
|
+
return ["client", "withUnwrap"];
|
|
908
|
+
})();
|
|
909
|
+
const clientTypeImports = (() => {
|
|
910
|
+
if (eventStream) return [
|
|
911
|
+
"Options",
|
|
912
|
+
"EventStreamResult",
|
|
913
|
+
"SuccessOf"
|
|
914
|
+
];
|
|
915
|
+
if (returnType === "plain") return ["Options", "RequestResult"];
|
|
916
|
+
if (returnType === "data") return ["Options", "UnwrappedResult"];
|
|
917
|
+
return [
|
|
918
|
+
"Options",
|
|
919
|
+
"Unwrappable",
|
|
920
|
+
"RequestResult"
|
|
921
|
+
];
|
|
922
|
+
})();
|
|
1812
923
|
return /* @__PURE__ */ jsxs(File, {
|
|
1813
|
-
baseName: file.baseName,
|
|
1814
|
-
path: file.path,
|
|
1815
|
-
meta: file.meta,
|
|
1816
|
-
banner: resolver.
|
|
924
|
+
baseName: meta.file.baseName,
|
|
925
|
+
path: meta.file.path,
|
|
926
|
+
meta: meta.file.meta,
|
|
927
|
+
banner: resolver.default.banner(ctx.meta, {
|
|
1817
928
|
output,
|
|
1818
929
|
config,
|
|
1819
930
|
file: {
|
|
1820
|
-
path: file.path,
|
|
1821
|
-
baseName: file.baseName
|
|
931
|
+
path: meta.file.path,
|
|
932
|
+
baseName: meta.file.baseName
|
|
1822
933
|
}
|
|
1823
934
|
}),
|
|
1824
|
-
footer: resolver.
|
|
935
|
+
footer: resolver.default.footer(ctx.meta, {
|
|
1825
936
|
output,
|
|
1826
937
|
config,
|
|
1827
938
|
file: {
|
|
1828
|
-
path: file.path,
|
|
1829
|
-
baseName: file.baseName
|
|
939
|
+
path: meta.file.path,
|
|
940
|
+
baseName: meta.file.baseName
|
|
1830
941
|
}
|
|
1831
942
|
}),
|
|
1832
943
|
children: [
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
}),
|
|
1838
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1839
|
-
name: ["mergeConfig"],
|
|
1840
|
-
path: importPath
|
|
1841
|
-
}),
|
|
1842
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1843
|
-
name: [
|
|
1844
|
-
"Client",
|
|
1845
|
-
"RequestConfig",
|
|
1846
|
-
"ResponseErrorConfig"
|
|
1847
|
-
],
|
|
1848
|
-
path: importPath,
|
|
1849
|
-
isTypeOnly: true
|
|
1850
|
-
})
|
|
1851
|
-
] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1852
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1853
|
-
name: ["client"],
|
|
1854
|
-
root: file.path,
|
|
1855
|
-
path: path.resolve(root, ".kubb/client.ts")
|
|
1856
|
-
}),
|
|
1857
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1858
|
-
name: ["mergeConfig"],
|
|
1859
|
-
root: file.path,
|
|
1860
|
-
path: path.resolve(root, ".kubb/client.ts")
|
|
1861
|
-
}),
|
|
1862
|
-
/* @__PURE__ */ jsx(File.Import, {
|
|
1863
|
-
name: [
|
|
1864
|
-
"Client",
|
|
1865
|
-
"RequestConfig",
|
|
1866
|
-
"ResponseErrorConfig"
|
|
1867
|
-
],
|
|
1868
|
-
root: file.path,
|
|
1869
|
-
path: path.resolve(root, ".kubb/client.ts"),
|
|
1870
|
-
isTypeOnly: true
|
|
1871
|
-
})
|
|
1872
|
-
] }),
|
|
1873
|
-
hasFormData && /* @__PURE__ */ jsx(File.Import, {
|
|
1874
|
-
name: ["buildFormData"],
|
|
1875
|
-
root: file.path,
|
|
1876
|
-
path: path.resolve(root, ".kubb/config.ts")
|
|
944
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
945
|
+
name: clientValueImports,
|
|
946
|
+
root: clientRoot,
|
|
947
|
+
path: clientPath
|
|
1877
948
|
}),
|
|
1878
|
-
|
|
1879
|
-
name:
|
|
1880
|
-
|
|
949
|
+
/* @__PURE__ */ jsx(File.Import, {
|
|
950
|
+
name: clientTypeImports,
|
|
951
|
+
root: clientRoot,
|
|
952
|
+
path: clientPath,
|
|
1881
953
|
isTypeOnly: true
|
|
1882
954
|
}),
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
return /* @__PURE__ */ jsx(File.Import, {
|
|
1889
|
-
name: importNames,
|
|
1890
|
-
root: file.path,
|
|
1891
|
-
path: typeFile.path,
|
|
1892
|
-
isTypeOnly: true
|
|
1893
|
-
}, filePath);
|
|
955
|
+
meta.fileTypes && importedTypeNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
956
|
+
name: Array.from(new Set(importedTypeNames)),
|
|
957
|
+
root: meta.file.path,
|
|
958
|
+
path: meta.fileTypes.path,
|
|
959
|
+
isTypeOnly: true
|
|
1894
960
|
}),
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
if (importNames.length === 0) return null;
|
|
1900
|
-
return /* @__PURE__ */ jsx(File.Import, {
|
|
1901
|
-
name: importNames,
|
|
1902
|
-
root: file.path,
|
|
1903
|
-
path: zodFile.path
|
|
1904
|
-
}, filePath);
|
|
961
|
+
meta.fileZod && importedZodNames.length > 0 && /* @__PURE__ */ jsx(File.Import, {
|
|
962
|
+
name: importedZodNames,
|
|
963
|
+
root: meta.file.path,
|
|
964
|
+
path: meta.fileZod.path
|
|
1905
965
|
}),
|
|
1906
|
-
/* @__PURE__ */ jsx(
|
|
1907
|
-
name,
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
966
|
+
/* @__PURE__ */ jsx(Operation, {
|
|
967
|
+
name: meta.name,
|
|
968
|
+
node,
|
|
969
|
+
types,
|
|
970
|
+
zodResolver,
|
|
971
|
+
validator,
|
|
972
|
+
returnType,
|
|
973
|
+
throwOnErrorDefault,
|
|
974
|
+
security
|
|
1915
975
|
})
|
|
1916
976
|
]
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
1919
|
-
}
|
|
1920
|
-
}
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
//#endregion
|
|
982
|
+
//#region ../../internals/client/src/macros.ts
|
|
983
|
+
/**
|
|
984
|
+
* Macros the client plugins apply by default, ahead of any user macros. `macroSimplifyUnion`
|
|
985
|
+
* drops union members a broader scalar already covers, keeping the generated response and error
|
|
986
|
+
* unions tidy. A plugin wires them with `ctx.setMacros([...defaultMacros, ...userMacros])`.
|
|
987
|
+
*/
|
|
988
|
+
const defaultMacros = [macroSimplifyUnion];
|
|
1921
989
|
//#endregion
|
|
1922
|
-
//#region src/
|
|
990
|
+
//#region ../../internals/client/src/resolver.ts
|
|
1923
991
|
/**
|
|
1924
|
-
* Default resolver
|
|
1925
|
-
*
|
|
1926
|
-
* camelCase; classes and tag groups use PascalCase.
|
|
992
|
+
* Default resolver shared by the client plugins. Functions and files inherit the built-in camelCase
|
|
993
|
+
* `name` and `file`; classes and tag groups use PascalCase.
|
|
1927
994
|
*
|
|
1928
|
-
* @example
|
|
995
|
+
* @example
|
|
1929
996
|
* ```ts
|
|
1930
|
-
*
|
|
1931
|
-
*
|
|
1932
|
-
* resolverClient.default('list pets', 'function') // 'listPets'
|
|
1933
|
-
* resolverClient.resolveClassName('pet') // 'Pet'
|
|
1934
|
-
* resolverClient.resolveGroupName('pet') // 'PetClient'
|
|
1935
|
-
* resolverClient.resolveUrlName(operationNode) // 'getShowPetByIdUrl'
|
|
997
|
+
* resolverClient.name('show pet by id') // 'showPetById'
|
|
998
|
+
* resolverClient.groupName('pet') // 'PetClient'
|
|
1936
999
|
* ```
|
|
1937
1000
|
*/
|
|
1938
|
-
const resolverClient =
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
default(name, type) {
|
|
1942
|
-
if (type === "file") return toFilePath(name);
|
|
1943
|
-
return ensureValidVarName(camelCase(name));
|
|
1944
|
-
},
|
|
1945
|
-
resolveName(name) {
|
|
1946
|
-
return this.default(name, "function");
|
|
1947
|
-
},
|
|
1948
|
-
resolvePathName(name, type) {
|
|
1949
|
-
return this.default(name, type);
|
|
1950
|
-
},
|
|
1951
|
-
resolveClassName(name) {
|
|
1001
|
+
const resolverClient = createResolver({
|
|
1002
|
+
pluginName: "plugin-contract-client",
|
|
1003
|
+
className(name) {
|
|
1952
1004
|
return ensureValidVarName(pascalCase(name));
|
|
1953
1005
|
},
|
|
1954
|
-
|
|
1006
|
+
groupName(name) {
|
|
1955
1007
|
return ensureValidVarName(pascalCase(`${name} Client`));
|
|
1956
1008
|
},
|
|
1957
|
-
|
|
1009
|
+
propertyName(name) {
|
|
1958
1010
|
return ensureValidVarName(camelCase(name));
|
|
1959
|
-
},
|
|
1960
|
-
resolveUrlName(node) {
|
|
1961
|
-
const name = this.resolveName(node.operationId);
|
|
1962
|
-
return `get${name.charAt(0).toUpperCase()}${name.slice(1)}Url`;
|
|
1963
1011
|
}
|
|
1964
|
-
})
|
|
1012
|
+
});
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/generators/clientGenerator.tsx
|
|
1015
|
+
/**
|
|
1016
|
+
* Built-in operation generator for `@kubb/plugin-client`. Emits one async function per OpenAPI
|
|
1017
|
+
* operation using the shared `Operation` component: a grouped `<Name>Request` type and a function
|
|
1018
|
+
* that forwards a single `options` object to the user-provided client module and returns the `RequestResult`.
|
|
1019
|
+
*/
|
|
1020
|
+
const clientGenerator = createClientGenerator("client", (options) => options.importPath);
|
|
1965
1021
|
//#endregion
|
|
1966
1022
|
//#region src/plugin.ts
|
|
1967
1023
|
/**
|
|
1968
|
-
* Canonical plugin name for `@kubb/plugin-client`.
|
|
1969
|
-
* cross-plugin dependency references.
|
|
1024
|
+
* Canonical plugin name for `@kubb/plugin-client`.
|
|
1970
1025
|
*/
|
|
1971
1026
|
const pluginClientName = "plugin-client";
|
|
1972
1027
|
/**
|
|
1973
|
-
* Generates
|
|
1974
|
-
*
|
|
1975
|
-
*
|
|
1976
|
-
* your own by setting `importPath`.
|
|
1028
|
+
* Generates typed operations that call a client module owned by your application.
|
|
1029
|
+
* The module at `importPath` must export the runtime helpers and types used by generated operations.
|
|
1030
|
+
* Kubb does not copy or inject a transport implementation.
|
|
1977
1031
|
*
|
|
1978
1032
|
* @example
|
|
1979
1033
|
* ```ts
|
|
1980
|
-
*
|
|
1981
|
-
* import { pluginTs } from '@kubb/plugin-ts'
|
|
1982
|
-
* import { pluginClient } from '@kubb/plugin-client'
|
|
1983
|
-
*
|
|
1984
|
-
* export default defineConfig({
|
|
1985
|
-
* input: { path: './petStore.yaml' },
|
|
1986
|
-
* output: { path: './src/gen' },
|
|
1987
|
-
* plugins: [
|
|
1988
|
-
* pluginTs(),
|
|
1989
|
-
* pluginClient({
|
|
1990
|
-
* output: { path: './clients' },
|
|
1991
|
-
* client: 'fetch',
|
|
1992
|
-
* }),
|
|
1993
|
-
* ],
|
|
1994
|
-
* })
|
|
1034
|
+
* pluginClient({ importPath: '../api/client' })
|
|
1995
1035
|
* ```
|
|
1996
1036
|
*/
|
|
1997
1037
|
const pluginClient = definePlugin((options) => {
|
|
1998
1038
|
const { output = {
|
|
1999
1039
|
path: "clients",
|
|
2000
1040
|
barrel: { type: "named" }
|
|
2001
|
-
},
|
|
2002
|
-
const
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
1041
|
+
}, exclude = [], include, override = [], importPath, throwOnErrorDefault = true, validator = false, group, resolver: userResolver } = options;
|
|
1042
|
+
const resolved = {
|
|
1043
|
+
output,
|
|
1044
|
+
exclude,
|
|
1045
|
+
include,
|
|
1046
|
+
override,
|
|
1047
|
+
group: createGroupConfig(group),
|
|
1048
|
+
importPath,
|
|
1049
|
+
baseURL: void 0,
|
|
1050
|
+
throwOnErrorDefault,
|
|
1051
|
+
validator,
|
|
1052
|
+
returnType: "plain",
|
|
1053
|
+
sdk: void 0,
|
|
1054
|
+
resolver: userResolver ? Resolver.merge(resolverClient, userResolver) : resolverClient
|
|
1055
|
+
};
|
|
2009
1056
|
return {
|
|
2010
1057
|
name: pluginClientName,
|
|
2011
1058
|
options,
|
|
2012
|
-
dependencies: [pluginTsName,
|
|
1059
|
+
dependencies: [pluginTsName, pluginZodName],
|
|
2013
1060
|
hooks: { "kubb:plugin:setup"(ctx) {
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
ctx.
|
|
2019
|
-
client,
|
|
2020
|
-
clientType,
|
|
2021
|
-
bundle,
|
|
2022
|
-
output,
|
|
2023
|
-
exclude,
|
|
2024
|
-
include,
|
|
2025
|
-
override,
|
|
2026
|
-
group: groupConfig,
|
|
2027
|
-
parser,
|
|
2028
|
-
dataReturnType,
|
|
2029
|
-
importPath: resolvedImportPath,
|
|
2030
|
-
baseURL,
|
|
2031
|
-
paramsType,
|
|
2032
|
-
paramsCasing,
|
|
2033
|
-
pathParamsType,
|
|
2034
|
-
urlType,
|
|
2035
|
-
sdk,
|
|
2036
|
-
resolver
|
|
2037
|
-
});
|
|
2038
|
-
ctx.setResolver(resolver);
|
|
2039
|
-
if (userTransformer) ctx.setTransformer(userTransformer);
|
|
2040
|
-
for (const gen of selectedGenerators) ctx.addGenerator(gen);
|
|
2041
|
-
const root = path.resolve(ctx.config.root, ctx.config.output.path);
|
|
2042
|
-
if (!resolvedImportPath?.startsWith(".")) {
|
|
2043
|
-
const isInlineSource = bundle && !resolvedImportPath;
|
|
2044
|
-
ctx.injectFile({
|
|
2045
|
-
baseName: "client.ts",
|
|
2046
|
-
path: path.resolve(root, ".kubb/client.ts"),
|
|
2047
|
-
sources: [ast.createSource({
|
|
2048
|
-
name: "client",
|
|
2049
|
-
nodes: isInlineSource ? [ast.createText(client === "fetch" ? source$1 : source)] : [],
|
|
2050
|
-
isExportable: true,
|
|
2051
|
-
isIndexable: true
|
|
2052
|
-
})],
|
|
2053
|
-
exports: !isInlineSource && resolvedImportPath ? [ast.createExport({ path: resolvedImportPath })] : []
|
|
2054
|
-
});
|
|
2055
|
-
}
|
|
2056
|
-
ctx.injectFile({
|
|
2057
|
-
baseName: "config.ts",
|
|
2058
|
-
path: path.resolve(root, ".kubb/config.ts"),
|
|
2059
|
-
sources: [ast.createSource({
|
|
2060
|
-
name: "config",
|
|
2061
|
-
nodes: [ast.createText(source$2)],
|
|
2062
|
-
isExportable: false,
|
|
2063
|
-
isIndexable: false
|
|
2064
|
-
})]
|
|
2065
|
-
});
|
|
1061
|
+
if (validator && !ctx.config.plugins?.some((plugin) => plugin.name === pluginZodName)) throw new Error(`${pluginClientName}: \`validator\` needs ${pluginZodName}. Add pluginZod() to the plugins or set \`validator: false\`.`);
|
|
1062
|
+
ctx.setOptions(resolved);
|
|
1063
|
+
ctx.setResolver(resolved.resolver);
|
|
1064
|
+
ctx.setMacros([...defaultMacros, ...options.macros ?? []]);
|
|
1065
|
+
ctx.addGenerator(clientGenerator);
|
|
2066
1066
|
} }
|
|
2067
1067
|
};
|
|
2068
1068
|
});
|
|
2069
1069
|
//#endregion
|
|
2070
|
-
export {
|
|
1070
|
+
export { pluginClient as default, pluginClient, pluginClientName };
|
|
2071
1071
|
|
|
2072
1072
|
//# sourceMappingURL=index.js.map
|