@7nohe/openapi-react-query-codegen 3.2.1 → 4.0.0-beta.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/AGENTS.md +22 -19
- package/README.md +3 -3
- package/dist/cli.d.mts +6 -1
- package/dist/client/emitSchemas.d.mts +9 -0
- package/dist/client/emitSchemas.mjs +130 -0
- package/dist/client/emitSdk.d.mts +18 -0
- package/dist/client/emitSdk.mjs +253 -0
- package/dist/client/emitTransformers.d.mts +19 -0
- package/dist/client/emitTransformers.mjs +556 -0
- package/dist/client/emitTypes.d.mts +16 -0
- package/dist/client/emitTypes.mjs +204 -0
- package/dist/client/index.d.mts +44 -0
- package/dist/client/index.mjs +126 -0
- package/dist/client/naming.d.mts +41 -0
- package/dist/client/naming.mjs +175 -0
- package/dist/client/operations.d.mts +103 -0
- package/dist/client/operations.mjs +352 -0
- package/dist/client/runtime/axios.runtime.ts +706 -0
- package/dist/client/runtime/fetch.runtime.ts +795 -0
- package/dist/client/schema.d.mts +50 -0
- package/dist/client/schema.mjs +648 -0
- package/dist/client/spec.d.mts +40 -0
- package/dist/client/spec.mjs +387 -0
- package/dist/client/tsconfig.d.mts +13 -0
- package/dist/client/tsconfig.mjs +56 -0
- package/dist/common.d.mts +0 -38
- package/dist/common.mjs +0 -87
- package/dist/constants.d.mts +0 -2
- package/dist/constants.mjs +0 -2
- package/dist/createSource.d.mts +8 -7
- package/dist/createSource.mjs +14 -17
- package/dist/format.mjs +0 -1
- package/dist/generate.d.mts +9 -9
- package/dist/generate.mjs +45 -107
- package/dist/runCli.mjs +7 -2
- package/dist/tsmorph/buildQueryHooks.mjs +19 -11
- package/dist/tsmorph/generateFiles.mjs +105 -161
- package/dist/tsmorph/operationNames.d.mts +2 -13
- package/dist/tsmorph/operationNames.mjs +4 -24
- package/dist/tsmorph/projectFactory.d.mts +7 -2
- package/dist/tsmorph/projectFactory.mjs +16 -9
- package/dist/types.d.mts +14 -26
- package/package.json +6 -6
- package/dist/parseOperations.d.mts +0 -10
- package/dist/parseOperations.mjs +0 -164
- package/dist/service.d.mts +0 -8
- package/dist/service.mjs +0 -98
- package/dist/util.d.mts +0 -2
- package/dist/util.mjs +0 -16
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
// This file is auto-generated by @7nohe/openapi-react-query-codegen. Do not edit.
|
|
2
|
+
|
|
3
|
+
import axios, {
|
|
4
|
+
type AxiosError,
|
|
5
|
+
type AxiosInstance,
|
|
6
|
+
type AxiosRequestConfig,
|
|
7
|
+
type AxiosResponse,
|
|
8
|
+
type AxiosStatic,
|
|
9
|
+
type CreateAxiosDefaults,
|
|
10
|
+
} from "axios";
|
|
11
|
+
|
|
12
|
+
export interface ClientOptions {
|
|
13
|
+
baseURL?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type BodyType = "json" | "form-data" | "urlencoded";
|
|
17
|
+
|
|
18
|
+
export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
|
|
19
|
+
export type ObjectStyle = "form" | "deepObject";
|
|
20
|
+
|
|
21
|
+
export interface ParameterSerializer {
|
|
22
|
+
/** Leave reserved characters in values as they are. */
|
|
23
|
+
allowReserved?: boolean;
|
|
24
|
+
array?: { style?: ArrayStyle; explode?: boolean };
|
|
25
|
+
object?: { style?: ObjectStyle; explode?: boolean };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface QueryParameterSerializer extends ParameterSerializer {
|
|
29
|
+
/** Send the value as a JSON text (a parameter declared with `content`). */
|
|
30
|
+
json?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface QuerySerializerOptions extends ParameterSerializer {
|
|
34
|
+
/** Per-parameter overrides, keyed by the parameter name. */
|
|
35
|
+
parameters?: Record<string, QueryParameterSerializer>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface PathParameterSerializer {
|
|
39
|
+
style?: "simple" | "label" | "matrix";
|
|
40
|
+
explode?: boolean;
|
|
41
|
+
/** Send the value as a JSON text (a parameter declared with `content`). */
|
|
42
|
+
json?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface PathSerializerOptions {
|
|
46
|
+
/** Per-parameter settings, keyed by the parameter name. */
|
|
47
|
+
parameters?: Record<string, PathParameterSerializer>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface Auth {
|
|
51
|
+
in?: "header" | "query" | "cookie";
|
|
52
|
+
/** The scheme's name, when another scheme would look the same at runtime. */
|
|
53
|
+
key?: string;
|
|
54
|
+
name?: string;
|
|
55
|
+
scheme?: "basic" | "bearer";
|
|
56
|
+
type: "apiKey" | "http";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
type HeaderValue = string | number | boolean | null | undefined | unknown;
|
|
60
|
+
|
|
61
|
+
export interface Config<T extends ClientOptions = ClientOptions>
|
|
62
|
+
extends Omit<
|
|
63
|
+
CreateAxiosDefaults,
|
|
64
|
+
"auth" | "baseURL" | "data" | "headers" | "method" | "params" | "url"
|
|
65
|
+
> {
|
|
66
|
+
/** Token (or a function returning one) used for operations with `security`. */
|
|
67
|
+
auth?:
|
|
68
|
+
| string
|
|
69
|
+
| undefined
|
|
70
|
+
| ((auth: Auth) => string | undefined | Promise<string | undefined>);
|
|
71
|
+
/** Axios instance (or static) used to send requests. */
|
|
72
|
+
axios?: AxiosStatic | AxiosInstance;
|
|
73
|
+
baseURL?: T["baseURL"];
|
|
74
|
+
body?: unknown;
|
|
75
|
+
/** Replaces the default body serialization. */
|
|
76
|
+
bodySerializer?: ((body: unknown) => unknown) | null;
|
|
77
|
+
bodyType?: BodyType;
|
|
78
|
+
/** Headers to send as a JSON text (declared with `content`). */
|
|
79
|
+
jsonHeaders?: ReadonlyArray<string>;
|
|
80
|
+
headers?: Record<string, HeaderValue>;
|
|
81
|
+
method?:
|
|
82
|
+
| "connect"
|
|
83
|
+
| "delete"
|
|
84
|
+
| "get"
|
|
85
|
+
| "head"
|
|
86
|
+
| "options"
|
|
87
|
+
| "patch"
|
|
88
|
+
| "post"
|
|
89
|
+
| "put"
|
|
90
|
+
| "trace";
|
|
91
|
+
pathSerializer?: PathSerializerOptions;
|
|
92
|
+
querySerializer?:
|
|
93
|
+
| QuerySerializerOptions
|
|
94
|
+
| ((query: Record<string, unknown>) => string);
|
|
95
|
+
/**
|
|
96
|
+
* Called with the body of a successful response; what it returns becomes
|
|
97
|
+
* `data`. `--useDateType` sets it to turn date strings into `Date` objects.
|
|
98
|
+
*/
|
|
99
|
+
responseTransformer?: (data: unknown) => unknown;
|
|
100
|
+
/**
|
|
101
|
+
* Ways to authenticate. Each one that has a token for every scheme it lists
|
|
102
|
+
* is applied, as an API that takes either of two schemes may only look at one
|
|
103
|
+
* of them. An array lists schemes needed together.
|
|
104
|
+
*/
|
|
105
|
+
security?: ReadonlyArray<Auth | ReadonlyArray<Auth>>;
|
|
106
|
+
/** Throw the error instead of returning it. */
|
|
107
|
+
throwOnError?: boolean;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface RequestOptions<ThrowOnError extends boolean = boolean>
|
|
111
|
+
extends Config {
|
|
112
|
+
path?: Record<string, unknown>;
|
|
113
|
+
query?: Record<string, unknown>;
|
|
114
|
+
throwOnError?: ThrowOnError;
|
|
115
|
+
url: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
|
119
|
+
|
|
120
|
+
export type TDataShape = {
|
|
121
|
+
body?: unknown;
|
|
122
|
+
headers?: unknown;
|
|
123
|
+
path?: unknown;
|
|
124
|
+
query?: unknown;
|
|
125
|
+
url: string;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export type Options<
|
|
129
|
+
TData extends TDataShape = TDataShape,
|
|
130
|
+
ThrowOnError extends boolean = boolean,
|
|
131
|
+
> = OmitKeys<RequestOptions<ThrowOnError>, "body" | "path" | "query" | "url"> &
|
|
132
|
+
Omit<TData, "url">;
|
|
133
|
+
|
|
134
|
+
type Unwrap<T> = T extends Record<string, unknown> ? T[keyof T] : T;
|
|
135
|
+
|
|
136
|
+
export type RequestResult<
|
|
137
|
+
TData = unknown,
|
|
138
|
+
TError = unknown,
|
|
139
|
+
ThrowOnError extends boolean = boolean,
|
|
140
|
+
> = ThrowOnError extends true
|
|
141
|
+
? Promise<AxiosResponse<Unwrap<TData>>>
|
|
142
|
+
: Promise<
|
|
143
|
+
| (AxiosResponse<Unwrap<TData>> & { error: undefined })
|
|
144
|
+
| (AxiosError<Unwrap<TError>> & {
|
|
145
|
+
data: undefined;
|
|
146
|
+
error: Unwrap<TError>;
|
|
147
|
+
})
|
|
148
|
+
>;
|
|
149
|
+
|
|
150
|
+
type MethodFn = <
|
|
151
|
+
TData = unknown,
|
|
152
|
+
TError = unknown,
|
|
153
|
+
ThrowOnError extends boolean = false,
|
|
154
|
+
>(
|
|
155
|
+
options: Omit<RequestOptions<ThrowOnError>, "method">,
|
|
156
|
+
) => RequestResult<TData, TError, ThrowOnError>;
|
|
157
|
+
|
|
158
|
+
export interface Client {
|
|
159
|
+
buildUrl: (
|
|
160
|
+
options: Pick<
|
|
161
|
+
RequestOptions,
|
|
162
|
+
| "baseURL"
|
|
163
|
+
| "path"
|
|
164
|
+
| "pathSerializer"
|
|
165
|
+
| "query"
|
|
166
|
+
| "querySerializer"
|
|
167
|
+
| "url"
|
|
168
|
+
>,
|
|
169
|
+
) => string;
|
|
170
|
+
connect: MethodFn;
|
|
171
|
+
delete: MethodFn;
|
|
172
|
+
get: MethodFn;
|
|
173
|
+
getConfig: () => Config;
|
|
174
|
+
head: MethodFn;
|
|
175
|
+
/** The underlying axios instance. Use it to register interceptors. */
|
|
176
|
+
instance: AxiosInstance;
|
|
177
|
+
options: MethodFn;
|
|
178
|
+
patch: MethodFn;
|
|
179
|
+
post: MethodFn;
|
|
180
|
+
put: MethodFn;
|
|
181
|
+
request: <
|
|
182
|
+
TData = unknown,
|
|
183
|
+
TError = unknown,
|
|
184
|
+
ThrowOnError extends boolean = false,
|
|
185
|
+
>(
|
|
186
|
+
options: RequestOptions<ThrowOnError>,
|
|
187
|
+
) => RequestResult<TData, TError, ThrowOnError>;
|
|
188
|
+
setConfig: (config: Config) => Config;
|
|
189
|
+
trace: MethodFn;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
|
193
|
+
override?: Config<ClientOptions & T>,
|
|
194
|
+
) => Config<Required<ClientOptions> & T>;
|
|
195
|
+
|
|
196
|
+
const encode = (value: string): string => encodeURIComponent(value);
|
|
197
|
+
|
|
198
|
+
function primitive(value: unknown): string {
|
|
199
|
+
if (value instanceof Date) return value.toISOString();
|
|
200
|
+
if (typeof value === "object" && value !== null) return JSON.stringify(value);
|
|
201
|
+
return String(value);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function serializePathValue(
|
|
205
|
+
name: string,
|
|
206
|
+
value: unknown,
|
|
207
|
+
{ style = "simple", explode = false, json }: PathParameterSerializer = {},
|
|
208
|
+
): string {
|
|
209
|
+
if (json) return encode(JSON.stringify(value));
|
|
210
|
+
const key = encode(name);
|
|
211
|
+
const prefix = style === "label" ? "." : style === "matrix" ? ";" : "";
|
|
212
|
+
if (Array.isArray(value)) {
|
|
213
|
+
const items = value.map((item) => encode(primitive(item)));
|
|
214
|
+
if (style === "matrix") {
|
|
215
|
+
return explode
|
|
216
|
+
? items.map((item) => `;${key}=${item}`).join("")
|
|
217
|
+
: `;${key}=${items.join(",")}`;
|
|
218
|
+
}
|
|
219
|
+
return `${prefix}${items.join(explode && style === "label" ? "." : ",")}`;
|
|
220
|
+
}
|
|
221
|
+
if (typeof value === "object" && value !== null && !(value instanceof Date)) {
|
|
222
|
+
const entries = Object.entries(value).filter(
|
|
223
|
+
([, item]) => item !== undefined && item !== null,
|
|
224
|
+
);
|
|
225
|
+
if (explode) {
|
|
226
|
+
const pairs = entries.map(
|
|
227
|
+
([prop, item]) => `${encode(prop)}=${encode(primitive(item))}`,
|
|
228
|
+
);
|
|
229
|
+
return `${prefix}${pairs.join(prefix || ",")}`;
|
|
230
|
+
}
|
|
231
|
+
const flat = entries
|
|
232
|
+
.flatMap(([prop, item]) => [encode(prop), encode(primitive(item))])
|
|
233
|
+
.join(",");
|
|
234
|
+
return style === "matrix" ? `;${key}=${flat}` : `${prefix}${flat}`;
|
|
235
|
+
}
|
|
236
|
+
const text = encode(primitive(value));
|
|
237
|
+
return style === "matrix" ? `;${key}=${text}` : `${prefix}${text}`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function serializePath(
|
|
241
|
+
url: string,
|
|
242
|
+
path: Record<string, unknown> | undefined,
|
|
243
|
+
serializer?: PathSerializerOptions,
|
|
244
|
+
): string {
|
|
245
|
+
if (!path) return url;
|
|
246
|
+
return url.replace(/\{([^{}]+)\}/g, (match, name: string) => {
|
|
247
|
+
const value = path[name];
|
|
248
|
+
const settings = serializer?.parameters?.[name];
|
|
249
|
+
return value === undefined || (value === null && !settings?.json)
|
|
250
|
+
? match
|
|
251
|
+
: serializePathValue(name, value, settings);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function serializeQuery(
|
|
256
|
+
query: Record<string, unknown>,
|
|
257
|
+
options: QuerySerializerOptions = {},
|
|
258
|
+
): string {
|
|
259
|
+
const parts: string[] = [];
|
|
260
|
+
for (const [name, value] of Object.entries(query)) {
|
|
261
|
+
if (value === undefined) continue;
|
|
262
|
+
const override = options.parameters?.[name];
|
|
263
|
+
const key = encode(name);
|
|
264
|
+
const encodeValue =
|
|
265
|
+
(override?.allowReserved ?? options.allowReserved) ? String : encode;
|
|
266
|
+
if (override?.json) {
|
|
267
|
+
parts.push(`${key}=${encodeValue(JSON.stringify(value))}`);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (value === null) continue;
|
|
271
|
+
if (Array.isArray(value)) {
|
|
272
|
+
const style = override?.array?.style ?? options.array?.style ?? "form";
|
|
273
|
+
const explode =
|
|
274
|
+
override?.array?.explode ?? options.array?.explode ?? true;
|
|
275
|
+
const items = value.filter((item) => item !== undefined && item !== null);
|
|
276
|
+
if (explode) {
|
|
277
|
+
for (const item of items)
|
|
278
|
+
parts.push(`${key}=${encodeValue(primitive(item))}`);
|
|
279
|
+
} else {
|
|
280
|
+
const separator =
|
|
281
|
+
style === "spaceDelimited"
|
|
282
|
+
? "%20"
|
|
283
|
+
: style === "pipeDelimited"
|
|
284
|
+
? "|"
|
|
285
|
+
: ",";
|
|
286
|
+
parts.push(
|
|
287
|
+
`${key}=${items.map((item) => encodeValue(primitive(item))).join(separator)}`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
} else if (value instanceof Date) {
|
|
291
|
+
parts.push(`${key}=${encodeValue(value.toISOString())}`);
|
|
292
|
+
} else if (typeof value === "object") {
|
|
293
|
+
const style =
|
|
294
|
+
override?.object?.style ?? options.object?.style ?? "deepObject";
|
|
295
|
+
const explode =
|
|
296
|
+
override?.object?.explode ?? options.object?.explode ?? true;
|
|
297
|
+
const entries = Object.entries(value).filter(
|
|
298
|
+
([, item]) => item !== undefined && item !== null,
|
|
299
|
+
);
|
|
300
|
+
if (style === "deepObject") {
|
|
301
|
+
for (const [prop, item] of entries) {
|
|
302
|
+
parts.push(`${key}[${encode(prop)}]=${encodeValue(primitive(item))}`);
|
|
303
|
+
}
|
|
304
|
+
} else if (explode) {
|
|
305
|
+
for (const [prop, item] of entries) {
|
|
306
|
+
parts.push(`${encode(prop)}=${encodeValue(primitive(item))}`);
|
|
307
|
+
}
|
|
308
|
+
} else {
|
|
309
|
+
parts.push(
|
|
310
|
+
`${key}=${entries.flatMap(([prop, item]) => [encode(prop), encodeValue(primitive(item))]).join(",")}`,
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
} else {
|
|
314
|
+
parts.push(`${key}=${encodeValue(String(value))}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return parts.join("&");
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Encode the headers an operation declares as JSON, whatever their type. */
|
|
321
|
+
function encodeJsonHeaders<T>(
|
|
322
|
+
headers: T,
|
|
323
|
+
names: ReadonlyArray<string> | undefined,
|
|
324
|
+
): T {
|
|
325
|
+
if (!names || !headers || Array.isArray(headers)) return headers;
|
|
326
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
327
|
+
return headers;
|
|
328
|
+
}
|
|
329
|
+
const encoded = { ...headers } as Record<string, unknown>;
|
|
330
|
+
for (const name of names) {
|
|
331
|
+
if (encoded[name] !== undefined) {
|
|
332
|
+
encoded[name] = JSON.stringify(encoded[name]);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return encoded as T;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Keys of an axios `headers` object that hold the headers of a method. */
|
|
339
|
+
const HEADER_GROUPS = [
|
|
340
|
+
"common",
|
|
341
|
+
"delete",
|
|
342
|
+
"get",
|
|
343
|
+
"head",
|
|
344
|
+
"patch",
|
|
345
|
+
"post",
|
|
346
|
+
"put",
|
|
347
|
+
];
|
|
348
|
+
|
|
349
|
+
function mergeHeaders(
|
|
350
|
+
...sources: Array<Record<string, HeaderValue> | undefined>
|
|
351
|
+
): Record<string, unknown> {
|
|
352
|
+
const merged: Record<string, unknown> = {};
|
|
353
|
+
const names = new Map<string, string>();
|
|
354
|
+
for (const source of sources) {
|
|
355
|
+
if (!source) continue;
|
|
356
|
+
for (const [key, value] of Object.entries(source)) {
|
|
357
|
+
if (value === undefined) continue;
|
|
358
|
+
const lower = key.toLowerCase();
|
|
359
|
+
if (
|
|
360
|
+
HEADER_GROUPS.includes(lower) &&
|
|
361
|
+
typeof value === "object" &&
|
|
362
|
+
value !== null
|
|
363
|
+
) {
|
|
364
|
+
merged[key] = { ...(merged[key] as object | undefined), ...value };
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const existing = names.get(lower);
|
|
368
|
+
if (existing !== undefined) delete merged[existing];
|
|
369
|
+
if (value === null) {
|
|
370
|
+
names.delete(lower);
|
|
371
|
+
} else {
|
|
372
|
+
names.set(lower, key);
|
|
373
|
+
merged[key] = Array.isArray(value)
|
|
374
|
+
? value.map(String)
|
|
375
|
+
: typeof value === "object"
|
|
376
|
+
? JSON.stringify(value)
|
|
377
|
+
: value;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return merged;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function toFormData(body: unknown): FormData {
|
|
385
|
+
if (body instanceof FormData) return body;
|
|
386
|
+
const data = new FormData();
|
|
387
|
+
const append = (key: string, value: unknown) => {
|
|
388
|
+
if (value === undefined || value === null) return;
|
|
389
|
+
if (typeof value === "string" || value instanceof Blob)
|
|
390
|
+
data.append(key, value);
|
|
391
|
+
else if (value instanceof Date) data.append(key, value.toISOString());
|
|
392
|
+
else if (typeof value === "object") data.append(key, JSON.stringify(value));
|
|
393
|
+
else data.append(key, String(value));
|
|
394
|
+
};
|
|
395
|
+
for (const [key, value] of Object.entries(
|
|
396
|
+
(body ?? {}) as Record<string, unknown>,
|
|
397
|
+
)) {
|
|
398
|
+
if (Array.isArray(value)) for (const item of value) append(key, item);
|
|
399
|
+
else append(key, value);
|
|
400
|
+
}
|
|
401
|
+
return data;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function toSearchParams(body: unknown): URLSearchParams {
|
|
405
|
+
if (body instanceof URLSearchParams) return body;
|
|
406
|
+
const params = new URLSearchParams();
|
|
407
|
+
for (const [key, value] of Object.entries(
|
|
408
|
+
(body ?? {}) as Record<string, unknown>,
|
|
409
|
+
)) {
|
|
410
|
+
if (value === undefined || value === null) continue;
|
|
411
|
+
if (Array.isArray(value))
|
|
412
|
+
for (const item of value) params.append(key, primitive(item));
|
|
413
|
+
else params.append(key, primitive(value));
|
|
414
|
+
}
|
|
415
|
+
return params;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function serializeBody(options: Config): unknown {
|
|
419
|
+
const { body, bodySerializer, bodyType } = options;
|
|
420
|
+
if (body === undefined) return undefined;
|
|
421
|
+
if (bodySerializer) return bodySerializer(body);
|
|
422
|
+
// `null` means the caller serialized the body already.
|
|
423
|
+
if (bodySerializer === null) return body;
|
|
424
|
+
if (bodyType === "form-data") return toFormData(body);
|
|
425
|
+
if (bodyType === "urlencoded") return toSearchParams(body);
|
|
426
|
+
// Axios sends a string that already parses as JSON as it is, so `"true"`
|
|
427
|
+
// would arrive as a boolean unless it is encoded here.
|
|
428
|
+
if (bodyType === "json" && typeof body === "string") {
|
|
429
|
+
return JSON.stringify(body);
|
|
430
|
+
}
|
|
431
|
+
return body;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async function getAuthToken(
|
|
435
|
+
auth: Auth,
|
|
436
|
+
callback: Config["auth"],
|
|
437
|
+
): Promise<string | undefined> {
|
|
438
|
+
const token =
|
|
439
|
+
typeof callback === "function" ? await callback(auth) : callback;
|
|
440
|
+
if (!token) return undefined;
|
|
441
|
+
if (auth.scheme === "bearer") return `Bearer ${token}`;
|
|
442
|
+
if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
|
|
443
|
+
return token;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** True when the caller already supplied this API key on the request. */
|
|
447
|
+
function isProvided(
|
|
448
|
+
auth: Auth,
|
|
449
|
+
query: Record<string, unknown> | undefined,
|
|
450
|
+
headers: Record<string, unknown>,
|
|
451
|
+
): boolean {
|
|
452
|
+
const { name } = auth;
|
|
453
|
+
if (!name) return false;
|
|
454
|
+
if (auth.in === "query") return query?.[name] != null;
|
|
455
|
+
const lower = (auth.in === "cookie" ? "Cookie" : name).toLowerCase();
|
|
456
|
+
const key = Object.keys(headers).find((item) => item.toLowerCase() === lower);
|
|
457
|
+
if (!key) return false;
|
|
458
|
+
return (
|
|
459
|
+
auth.in !== "cookie" ||
|
|
460
|
+
String(headers[key])
|
|
461
|
+
.split(";")
|
|
462
|
+
.some((cookie) => cookie.trim().startsWith(`${name}=`))
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function applySecurity(
|
|
467
|
+
options: RequestOptions,
|
|
468
|
+
headers: Record<string, unknown>,
|
|
469
|
+
): Promise<void> {
|
|
470
|
+
for (const requirement of options.security ?? []) {
|
|
471
|
+
const schemes = (
|
|
472
|
+
Array.isArray(requirement) ? requirement : [requirement]
|
|
473
|
+
) as ReadonlyArray<Auth>;
|
|
474
|
+
const missing = schemes.filter(
|
|
475
|
+
(auth) => !isProvided(auth, options.query, headers),
|
|
476
|
+
);
|
|
477
|
+
const tokens = await Promise.all(
|
|
478
|
+
missing.map((auth) => getAuthToken(auth, options.auth)),
|
|
479
|
+
);
|
|
480
|
+
if (tokens.some((token) => !token)) continue;
|
|
481
|
+
missing.forEach((auth, index) => {
|
|
482
|
+
const name = auth.name ?? "Authorization";
|
|
483
|
+
const token = tokens[index] as string;
|
|
484
|
+
if (auth.in === "query") {
|
|
485
|
+
options.query = { ...options.query, [name]: token };
|
|
486
|
+
} else if (auth.in === "cookie") {
|
|
487
|
+
headers.Cookie = headers.Cookie
|
|
488
|
+
? `${headers.Cookie}; ${name}=${token}`
|
|
489
|
+
: `${name}=${token}`;
|
|
490
|
+
} else {
|
|
491
|
+
headers[name] = token;
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function buildUrl(
|
|
498
|
+
options: Pick<
|
|
499
|
+
RequestOptions,
|
|
500
|
+
"baseURL" | "path" | "pathSerializer" | "query" | "querySerializer" | "url"
|
|
501
|
+
>,
|
|
502
|
+
): string {
|
|
503
|
+
const path = serializePath(options.url, options.path, options.pathSerializer);
|
|
504
|
+
const isAbsolute = /^[a-z][a-z0-9+.-]*:\/\//i.test(path);
|
|
505
|
+
const base = isAbsolute ? "" : (options.baseURL ?? "").replace(/\/+$/, "");
|
|
506
|
+
let url = `${base}${isAbsolute || path.startsWith("/") || path === "" ? path : `/${path}`}`;
|
|
507
|
+
if (options.query) {
|
|
508
|
+
const search =
|
|
509
|
+
typeof options.querySerializer === "function"
|
|
510
|
+
? options.querySerializer(options.query).replace(/^\?/, "")
|
|
511
|
+
: serializeQuery(options.query, options.querySerializer);
|
|
512
|
+
if (search) url += `${url.includes("?") ? "&" : "?"}${search}`;
|
|
513
|
+
}
|
|
514
|
+
return url;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
|
518
|
+
override: Config<ClientOptions & T> = {},
|
|
519
|
+
): Config<Required<ClientOptions> & T> =>
|
|
520
|
+
({
|
|
521
|
+
...override,
|
|
522
|
+
}) as Config<Required<ClientOptions> & T>;
|
|
523
|
+
|
|
524
|
+
const mergeConfigs = (base: Config, override: Config): Config => ({
|
|
525
|
+
...base,
|
|
526
|
+
...override,
|
|
527
|
+
headers: mergeHeaders(base.headers, override.headers),
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
const NON_AXIOS_KEYS = [
|
|
531
|
+
"auth",
|
|
532
|
+
"axios",
|
|
533
|
+
"body",
|
|
534
|
+
"bodySerializer",
|
|
535
|
+
"bodyType",
|
|
536
|
+
"path",
|
|
537
|
+
"pathSerializer",
|
|
538
|
+
"query",
|
|
539
|
+
"querySerializer",
|
|
540
|
+
"responseTransformer",
|
|
541
|
+
"security",
|
|
542
|
+
"throwOnError",
|
|
543
|
+
"url",
|
|
544
|
+
"baseURL",
|
|
545
|
+
"headers",
|
|
546
|
+
"jsonHeaders",
|
|
547
|
+
"client",
|
|
548
|
+
] as const;
|
|
549
|
+
|
|
550
|
+
/** The options axios itself understands; everything else is ours. */
|
|
551
|
+
const pickAxiosSettings = (config: Config): Record<string, unknown> => {
|
|
552
|
+
const settings: Record<string, unknown> = {};
|
|
553
|
+
for (const [key, value] of Object.entries(config)) {
|
|
554
|
+
if (!(NON_AXIOS_KEYS as readonly string[]).includes(key)) {
|
|
555
|
+
settings[key] = value;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return settings;
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
export const createClient = (config: Config = {}): Client => {
|
|
562
|
+
let currentConfig: Config = mergeConfigs(createConfig(), config);
|
|
563
|
+
// The default export belongs to the whole application, so a client given it
|
|
564
|
+
// makes an instance of its own, and its interceptors stay its own too.
|
|
565
|
+
const given = currentConfig.axios;
|
|
566
|
+
const shared = given && "Axios" in given ? given : undefined;
|
|
567
|
+
const instance: AxiosInstance =
|
|
568
|
+
given && !shared
|
|
569
|
+
? (given as AxiosInstance)
|
|
570
|
+
: (shared ?? axios).create(
|
|
571
|
+
pickAxiosSettings(currentConfig) as CreateAxiosDefaults,
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
// Every request gets `baseURL` and the headers from the current config. The
|
|
575
|
+
// instance's defaults follow the config as well, for a request made on
|
|
576
|
+
// `client.instance` itself.
|
|
577
|
+
let defaultHeaders: string[] = [];
|
|
578
|
+
const syncDefaults = (settings: Config) => {
|
|
579
|
+
Object.assign(instance.defaults, pickAxiosSettings(settings));
|
|
580
|
+
if (currentConfig.baseURL !== undefined) {
|
|
581
|
+
instance.defaults.baseURL = currentConfig.baseURL;
|
|
582
|
+
}
|
|
583
|
+
const defaults = instance.defaults.headers as Record<string, unknown>;
|
|
584
|
+
for (const key of defaultHeaders) delete defaults[key];
|
|
585
|
+
defaultHeaders = [];
|
|
586
|
+
for (const [key, value] of Object.entries(
|
|
587
|
+
mergeHeaders(currentConfig.headers),
|
|
588
|
+
)) {
|
|
589
|
+
if (HEADER_GROUPS.includes(key.toLowerCase())) {
|
|
590
|
+
defaults[key] = { ...(defaults[key] as object), ...(value as object) };
|
|
591
|
+
} else {
|
|
592
|
+
defaults[key] = value;
|
|
593
|
+
defaultHeaders.push(key);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
// An instance the caller made keeps its defaults until `setConfig` is called.
|
|
598
|
+
if (instance !== given) syncDefaults({});
|
|
599
|
+
|
|
600
|
+
const getConfig = (): Config => ({ ...currentConfig });
|
|
601
|
+
const setConfig = (next: Config): Config => {
|
|
602
|
+
currentConfig = mergeConfigs(currentConfig, next);
|
|
603
|
+
syncDefaults(next);
|
|
604
|
+
return getConfig();
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
const request = async (userOptions: RequestOptions) => {
|
|
608
|
+
const options: RequestOptions = {
|
|
609
|
+
...currentConfig,
|
|
610
|
+
...userOptions,
|
|
611
|
+
} as RequestOptions;
|
|
612
|
+
const client =
|
|
613
|
+
!options.axios || options.axios === shared
|
|
614
|
+
? instance
|
|
615
|
+
: (options.axios as AxiosInstance);
|
|
616
|
+
try {
|
|
617
|
+
const headers = mergeHeaders(
|
|
618
|
+
currentConfig.headers,
|
|
619
|
+
encodeJsonHeaders(userOptions.headers, options.jsonHeaders),
|
|
620
|
+
);
|
|
621
|
+
await applySecurity(options, headers);
|
|
622
|
+
|
|
623
|
+
const data = serializeBody(options);
|
|
624
|
+
const hasContentType = Object.keys(headers).some(
|
|
625
|
+
(key) => key.toLowerCase() === "content-type",
|
|
626
|
+
);
|
|
627
|
+
if (
|
|
628
|
+
data !== undefined &&
|
|
629
|
+
options.bodyType === "json" &&
|
|
630
|
+
!hasContentType
|
|
631
|
+
) {
|
|
632
|
+
headers["Content-Type"] = "application/json";
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// A header this request removed must not come back from the defaults.
|
|
636
|
+
if (client === instance) {
|
|
637
|
+
const sent = Object.keys(headers).map((key) => key.toLowerCase());
|
|
638
|
+
for (const key of defaultHeaders) {
|
|
639
|
+
if (!sent.includes(key.toLowerCase())) headers[key] = null;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const axiosSettings = pickAxiosSettings(options);
|
|
644
|
+
|
|
645
|
+
const querySerializer = options.querySerializer;
|
|
646
|
+
const finalConfig = {
|
|
647
|
+
...axiosSettings,
|
|
648
|
+
data,
|
|
649
|
+
headers,
|
|
650
|
+
params: options.query,
|
|
651
|
+
// A serializer set on the client or on its instance is the caller's choice.
|
|
652
|
+
paramsSerializer: options.paramsSerializer ??
|
|
653
|
+
client.defaults?.paramsSerializer ?? {
|
|
654
|
+
serialize: (params: Record<string, unknown>) =>
|
|
655
|
+
typeof querySerializer === "function"
|
|
656
|
+
? querySerializer(params).replace(/^\?/, "")
|
|
657
|
+
: serializeQuery(params, querySerializer),
|
|
658
|
+
},
|
|
659
|
+
url: serializePath(options.url, options.path, options.pathSerializer),
|
|
660
|
+
} as AxiosRequestConfig;
|
|
661
|
+
if (options.baseURL !== undefined) finalConfig.baseURL = options.baseURL;
|
|
662
|
+
|
|
663
|
+
const response = await client.request(finalConfig);
|
|
664
|
+
if (options.responseTransformer) {
|
|
665
|
+
response.data = await options.responseTransformer(response.data);
|
|
666
|
+
}
|
|
667
|
+
return { ...response, error: undefined };
|
|
668
|
+
} catch (error) {
|
|
669
|
+
if (options.throwOnError ?? currentConfig.throwOnError) throw error;
|
|
670
|
+
if (!axios.isAxiosError(error)) return { data: undefined, error };
|
|
671
|
+
// The error itself, so that it stays an `AxiosError` for the caller.
|
|
672
|
+
return Object.assign(error, {
|
|
673
|
+
data: undefined,
|
|
674
|
+
error: error.response?.data ?? error,
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
const method =
|
|
680
|
+
(name: NonNullable<Config["method"]>): MethodFn =>
|
|
681
|
+
(options) =>
|
|
682
|
+
request({ ...options, method: name } as RequestOptions) as never;
|
|
683
|
+
|
|
684
|
+
return {
|
|
685
|
+
buildUrl: (options) =>
|
|
686
|
+
buildUrl({
|
|
687
|
+
...currentConfig,
|
|
688
|
+
...options,
|
|
689
|
+
baseURL:
|
|
690
|
+
options.baseURL ?? currentConfig.baseURL ?? instance.defaults.baseURL,
|
|
691
|
+
}),
|
|
692
|
+
connect: method("connect"),
|
|
693
|
+
delete: method("delete"),
|
|
694
|
+
get: method("get"),
|
|
695
|
+
getConfig,
|
|
696
|
+
head: method("head"),
|
|
697
|
+
instance,
|
|
698
|
+
options: method("options"),
|
|
699
|
+
patch: method("patch"),
|
|
700
|
+
post: method("post"),
|
|
701
|
+
put: method("put"),
|
|
702
|
+
request: request as never,
|
|
703
|
+
setConfig,
|
|
704
|
+
trace: method("trace"),
|
|
705
|
+
};
|
|
706
|
+
};
|