@7nohe/openapi-react-query-codegen 3.1.0 → 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.
Files changed (55) hide show
  1. package/AGENTS.md +207 -0
  2. package/README.md +7 -3
  3. package/dist/check.d.mts +59 -0
  4. package/dist/check.mjs +162 -0
  5. package/dist/cli.d.mts +6 -1
  6. package/dist/cli.mjs +4 -31
  7. package/dist/client/emitSchemas.d.mts +9 -0
  8. package/dist/client/emitSchemas.mjs +130 -0
  9. package/dist/client/emitSdk.d.mts +18 -0
  10. package/dist/client/emitSdk.mjs +253 -0
  11. package/dist/client/emitTransformers.d.mts +19 -0
  12. package/dist/client/emitTransformers.mjs +556 -0
  13. package/dist/client/emitTypes.d.mts +16 -0
  14. package/dist/client/emitTypes.mjs +204 -0
  15. package/dist/client/index.d.mts +44 -0
  16. package/dist/client/index.mjs +126 -0
  17. package/dist/client/naming.d.mts +41 -0
  18. package/dist/client/naming.mjs +175 -0
  19. package/dist/client/operations.d.mts +103 -0
  20. package/dist/client/operations.mjs +352 -0
  21. package/dist/client/runtime/axios.runtime.ts +706 -0
  22. package/dist/client/runtime/fetch.runtime.ts +795 -0
  23. package/dist/client/schema.d.mts +50 -0
  24. package/dist/client/schema.mjs +648 -0
  25. package/dist/client/spec.d.mts +40 -0
  26. package/dist/client/spec.mjs +387 -0
  27. package/dist/client/tsconfig.d.mts +13 -0
  28. package/dist/client/tsconfig.mjs +56 -0
  29. package/dist/common.d.mts +0 -38
  30. package/dist/common.mjs +0 -87
  31. package/dist/constants.d.mts +0 -2
  32. package/dist/constants.mjs +0 -2
  33. package/dist/createSource.d.mts +8 -7
  34. package/dist/createSource.mjs +14 -17
  35. package/dist/errors.d.mts +43 -0
  36. package/dist/errors.mjs +61 -0
  37. package/dist/format.mjs +0 -1
  38. package/dist/generate.d.mts +25 -3
  39. package/dist/generate.mjs +83 -83
  40. package/dist/runCli.d.mts +20 -0
  41. package/dist/runCli.mjs +105 -0
  42. package/dist/tsmorph/buildQueryHooks.mjs +19 -11
  43. package/dist/tsmorph/generateFiles.mjs +105 -161
  44. package/dist/tsmorph/operationNames.d.mts +2 -13
  45. package/dist/tsmorph/operationNames.mjs +4 -24
  46. package/dist/tsmorph/projectFactory.d.mts +7 -2
  47. package/dist/tsmorph/projectFactory.mjs +16 -9
  48. package/dist/types.d.mts +14 -26
  49. package/package.json +8 -8
  50. package/dist/parseOperations.d.mts +0 -10
  51. package/dist/parseOperations.mjs +0 -164
  52. package/dist/service.d.mts +0 -8
  53. package/dist/service.mjs +0 -98
  54. package/dist/util.d.mts +0 -2
  55. package/dist/util.mjs +0 -16
@@ -0,0 +1,795 @@
1
+ // This file is auto-generated by @7nohe/openapi-react-query-codegen. Do not edit.
2
+
3
+ export interface ClientOptions {
4
+ baseUrl?: string;
5
+ }
6
+
7
+ export type BodyType = "json" | "form-data" | "urlencoded";
8
+
9
+ export type ParseAs =
10
+ | "arrayBuffer"
11
+ | "auto"
12
+ | "blob"
13
+ | "formData"
14
+ | "json"
15
+ | "stream"
16
+ | "text";
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<RequestInit, "body" | "headers" | "method"> {
63
+ /** Token (or a function returning one) used for operations with `security`. */
64
+ auth?:
65
+ | string
66
+ | undefined
67
+ | ((auth: Auth) => string | undefined | Promise<string | undefined>);
68
+ baseUrl?: T["baseUrl"];
69
+ body?: unknown;
70
+ /** Replaces the default body serialization. */
71
+ bodySerializer?: ((body: unknown) => BodyInit | null | undefined) | null;
72
+ bodyType?: BodyType;
73
+ /** Headers to send as a JSON text (declared with `content`). */
74
+ jsonHeaders?: ReadonlyArray<string>;
75
+ /** Custom fetch implementation. Defaults to `globalThis.fetch`. */
76
+ fetch?: typeof fetch;
77
+ headers?: RequestInit["headers"] | Record<string, HeaderValue>;
78
+ method?:
79
+ | "CONNECT"
80
+ | "DELETE"
81
+ | "GET"
82
+ | "HEAD"
83
+ | "OPTIONS"
84
+ | "PATCH"
85
+ | "POST"
86
+ | "PUT"
87
+ | "TRACE";
88
+ /** How the response body is parsed. `auto` follows the content type. */
89
+ parseAs?: ParseAs;
90
+ pathSerializer?: PathSerializerOptions;
91
+ querySerializer?:
92
+ | QuerySerializerOptions
93
+ | ((query: Record<string, unknown>) => string);
94
+ /**
95
+ * Called with the body of a successful response; what it returns becomes
96
+ * `data`. `--useDateType` sets it to turn date strings into `Date` objects.
97
+ */
98
+ responseTransformer?: (data: unknown) => unknown;
99
+ /**
100
+ * Ways to authenticate. Each one that has a token for every scheme it lists
101
+ * is applied, as an API that takes either of two schemes may only look at one
102
+ * of them. An array lists schemes needed together.
103
+ */
104
+ security?: ReadonlyArray<Auth | ReadonlyArray<Auth>>;
105
+ /** Throw the error instead of returning it. */
106
+ throwOnError?: boolean;
107
+ }
108
+
109
+ export interface RequestOptions<ThrowOnError extends boolean = boolean>
110
+ extends Config {
111
+ path?: Record<string, unknown>;
112
+ query?: Record<string, unknown>;
113
+ throwOnError?: ThrowOnError;
114
+ url: string;
115
+ }
116
+
117
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
118
+
119
+ export type TDataShape = {
120
+ body?: unknown;
121
+ headers?: unknown;
122
+ path?: unknown;
123
+ query?: unknown;
124
+ url: string;
125
+ };
126
+
127
+ export type Options<
128
+ TData extends TDataShape = TDataShape,
129
+ ThrowOnError extends boolean = boolean,
130
+ > = OmitKeys<RequestOptions<ThrowOnError>, "body" | "path" | "query" | "url"> &
131
+ Omit<TData, "url">;
132
+
133
+ type Unwrap<T> = T extends Record<string, unknown> ? T[keyof T] : T;
134
+
135
+ export type RequestResult<
136
+ TData = unknown,
137
+ TError = unknown,
138
+ ThrowOnError extends boolean = boolean,
139
+ > = ThrowOnError extends true
140
+ ? Promise<{
141
+ data: Unwrap<TData>;
142
+ request: Request;
143
+ response: Response;
144
+ }>
145
+ : Promise<
146
+ (
147
+ | { data: Unwrap<TData>; error: undefined }
148
+ | { data: undefined; error: Unwrap<TError> }
149
+ ) & {
150
+ request: Request;
151
+ response: Response;
152
+ }
153
+ >;
154
+
155
+ /** The options as a request uses them, with its headers merged. */
156
+ export type ResolvedRequestOptions = RequestOptions & { headers: Headers };
157
+
158
+ export type RequestInterceptor = (
159
+ request: Request,
160
+ options: ResolvedRequestOptions,
161
+ ) => Request | Promise<Request>;
162
+ export type ResponseInterceptor = (
163
+ response: Response,
164
+ request: Request,
165
+ options: ResolvedRequestOptions,
166
+ ) => Response | Promise<Response>;
167
+ /** `request` is undefined when the failure came before there was a request. */
168
+ export type ErrorInterceptor = (
169
+ error: unknown,
170
+ response: Response | undefined,
171
+ request: Request | undefined,
172
+ options: ResolvedRequestOptions,
173
+ ) => unknown | Promise<unknown>;
174
+
175
+ export class Interceptors<Fn> {
176
+ fns: Array<Fn | null> = [];
177
+
178
+ clear(): void {
179
+ this.fns = [];
180
+ }
181
+
182
+ eject(id: number | Fn): void {
183
+ const index = typeof id === "number" ? id : this.fns.indexOf(id);
184
+ if (index >= 0 && index < this.fns.length) this.fns[index] = null;
185
+ }
186
+
187
+ exists(id: number | Fn): boolean {
188
+ const index = typeof id === "number" ? id : this.fns.indexOf(id);
189
+ return Boolean(this.fns[index]);
190
+ }
191
+
192
+ update(id: number | Fn, fn: Fn): number | Fn | false {
193
+ const index = typeof id === "number" ? id : this.fns.indexOf(id);
194
+ if (!this.fns[index]) return false;
195
+ this.fns[index] = fn;
196
+ return id;
197
+ }
198
+
199
+ use(fn: Fn): number {
200
+ this.fns.push(fn);
201
+ return this.fns.length - 1;
202
+ }
203
+ }
204
+
205
+ type MethodFn = <
206
+ TData = unknown,
207
+ TError = unknown,
208
+ ThrowOnError extends boolean = false,
209
+ >(
210
+ options: Omit<RequestOptions<ThrowOnError>, "method">,
211
+ ) => RequestResult<TData, TError, ThrowOnError>;
212
+
213
+ export interface Client {
214
+ buildUrl: (
215
+ options: Pick<
216
+ RequestOptions,
217
+ | "baseUrl"
218
+ | "path"
219
+ | "pathSerializer"
220
+ | "query"
221
+ | "querySerializer"
222
+ | "url"
223
+ >,
224
+ ) => string;
225
+ connect: MethodFn;
226
+ delete: MethodFn;
227
+ get: MethodFn;
228
+ getConfig: () => Config;
229
+ head: MethodFn;
230
+ interceptors: {
231
+ error: Interceptors<ErrorInterceptor>;
232
+ request: Interceptors<RequestInterceptor>;
233
+ response: Interceptors<ResponseInterceptor>;
234
+ };
235
+ options: MethodFn;
236
+ patch: MethodFn;
237
+ post: MethodFn;
238
+ put: MethodFn;
239
+ request: <
240
+ TData = unknown,
241
+ TError = unknown,
242
+ ThrowOnError extends boolean = false,
243
+ >(
244
+ options: RequestOptions<ThrowOnError>,
245
+ ) => RequestResult<TData, TError, ThrowOnError>;
246
+ setConfig: (config: Config) => Config;
247
+ trace: MethodFn;
248
+ }
249
+
250
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
251
+ override?: Config<ClientOptions & T>,
252
+ ) => Config<Required<ClientOptions> & T>;
253
+
254
+ const REQUEST_INIT_KEYS = [
255
+ "cache",
256
+ "credentials",
257
+ "integrity",
258
+ "keepalive",
259
+ "method",
260
+ "mode",
261
+ "redirect",
262
+ "referrer",
263
+ "referrerPolicy",
264
+ "signal",
265
+ "duplex",
266
+ "priority",
267
+ ] as const;
268
+
269
+ const encode = (value: string): string => encodeURIComponent(value);
270
+
271
+ function primitive(value: unknown): string {
272
+ if (value instanceof Date) return value.toISOString();
273
+ if (typeof value === "object" && value !== null) return JSON.stringify(value);
274
+ return String(value);
275
+ }
276
+
277
+ function serializePathValue(
278
+ name: string,
279
+ value: unknown,
280
+ { style = "simple", explode = false, json }: PathParameterSerializer = {},
281
+ ): string {
282
+ if (json) return encode(JSON.stringify(value));
283
+ const key = encode(name);
284
+ const prefix = style === "label" ? "." : style === "matrix" ? ";" : "";
285
+ if (Array.isArray(value)) {
286
+ const items = value.map((item) => encode(primitive(item)));
287
+ if (style === "matrix") {
288
+ return explode
289
+ ? items.map((item) => `;${key}=${item}`).join("")
290
+ : `;${key}=${items.join(",")}`;
291
+ }
292
+ return `${prefix}${items.join(explode && style === "label" ? "." : ",")}`;
293
+ }
294
+ if (typeof value === "object" && value !== null && !(value instanceof Date)) {
295
+ const entries = Object.entries(value).filter(
296
+ ([, item]) => item !== undefined && item !== null,
297
+ );
298
+ if (explode) {
299
+ const pairs = entries.map(
300
+ ([prop, item]) => `${encode(prop)}=${encode(primitive(item))}`,
301
+ );
302
+ return `${prefix}${pairs.join(prefix || ",")}`;
303
+ }
304
+ const flat = entries
305
+ .flatMap(([prop, item]) => [encode(prop), encode(primitive(item))])
306
+ .join(",");
307
+ return style === "matrix" ? `;${key}=${flat}` : `${prefix}${flat}`;
308
+ }
309
+ const text = encode(primitive(value));
310
+ return style === "matrix" ? `;${key}=${text}` : `${prefix}${text}`;
311
+ }
312
+
313
+ function serializePath(
314
+ url: string,
315
+ path: Record<string, unknown> | undefined,
316
+ serializer?: PathSerializerOptions,
317
+ ): string {
318
+ if (!path) return url;
319
+ return url.replace(/\{([^{}]+)\}/g, (match, name: string) => {
320
+ const value = path[name];
321
+ const settings = serializer?.parameters?.[name];
322
+ return value === undefined || (value === null && !settings?.json)
323
+ ? match
324
+ : serializePathValue(name, value, settings);
325
+ });
326
+ }
327
+
328
+ export function serializeQuery(
329
+ query: Record<string, unknown>,
330
+ options: QuerySerializerOptions = {},
331
+ ): string {
332
+ const parts: string[] = [];
333
+ for (const [name, value] of Object.entries(query)) {
334
+ if (value === undefined) continue;
335
+ const override = options.parameters?.[name];
336
+ const key = encode(name);
337
+ const encodeValue =
338
+ (override?.allowReserved ?? options.allowReserved) ? String : encode;
339
+ if (override?.json) {
340
+ parts.push(`${key}=${encodeValue(JSON.stringify(value))}`);
341
+ continue;
342
+ }
343
+ if (value === null) continue;
344
+ if (Array.isArray(value)) {
345
+ const style = override?.array?.style ?? options.array?.style ?? "form";
346
+ const explode =
347
+ override?.array?.explode ?? options.array?.explode ?? true;
348
+ const items = value.filter((item) => item !== undefined && item !== null);
349
+ if (explode) {
350
+ for (const item of items)
351
+ parts.push(`${key}=${encodeValue(primitive(item))}`);
352
+ } else {
353
+ const separator =
354
+ style === "spaceDelimited"
355
+ ? "%20"
356
+ : style === "pipeDelimited"
357
+ ? "|"
358
+ : ",";
359
+ parts.push(
360
+ `${key}=${items.map((item) => encodeValue(primitive(item))).join(separator)}`,
361
+ );
362
+ }
363
+ } else if (value instanceof Date) {
364
+ parts.push(`${key}=${encodeValue(value.toISOString())}`);
365
+ } else if (typeof value === "object") {
366
+ const style =
367
+ override?.object?.style ?? options.object?.style ?? "deepObject";
368
+ const explode =
369
+ override?.object?.explode ?? options.object?.explode ?? true;
370
+ const entries = Object.entries(value).filter(
371
+ ([, item]) => item !== undefined && item !== null,
372
+ );
373
+ if (style === "deepObject") {
374
+ for (const [prop, item] of entries) {
375
+ parts.push(`${key}[${encode(prop)}]=${encodeValue(primitive(item))}`);
376
+ }
377
+ } else if (explode) {
378
+ for (const [prop, item] of entries) {
379
+ parts.push(`${encode(prop)}=${encodeValue(primitive(item))}`);
380
+ }
381
+ } else {
382
+ parts.push(
383
+ `${key}=${entries.flatMap(([prop, item]) => [encode(prop), encodeValue(primitive(item))]).join(",")}`,
384
+ );
385
+ }
386
+ } else {
387
+ parts.push(`${key}=${encodeValue(String(value))}`);
388
+ }
389
+ }
390
+ return parts.join("&");
391
+ }
392
+
393
+ const isAbsoluteUrl = (url: string): boolean =>
394
+ /^[a-z][a-z0-9+.-]*:\/\//i.test(url);
395
+
396
+ function buildUrl(
397
+ options: Pick<
398
+ RequestOptions,
399
+ "baseUrl" | "path" | "pathSerializer" | "query" | "querySerializer" | "url"
400
+ >,
401
+ ): string {
402
+ const path = serializePath(options.url, options.path, options.pathSerializer);
403
+ let url: string;
404
+ if (isAbsoluteUrl(path)) {
405
+ url = path;
406
+ } else {
407
+ const base = (options.baseUrl ?? "").replace(/\/+$/, "");
408
+ url = `${base}${path.startsWith("/") || path === "" ? path : `/${path}`}`;
409
+ }
410
+ const query = options.query;
411
+ if (query) {
412
+ const search =
413
+ typeof options.querySerializer === "function"
414
+ ? options.querySerializer(query).replace(/^\?/, "")
415
+ : serializeQuery(query, options.querySerializer);
416
+ if (search) url += `${url.includes("?") ? "&" : "?"}${search}`;
417
+ }
418
+ return url;
419
+ }
420
+
421
+ /** Encode the headers an operation declares as JSON, whatever their type. */
422
+ function encodeJsonHeaders<T>(
423
+ headers: T,
424
+ names: ReadonlyArray<string> | undefined,
425
+ ): T {
426
+ if (!names || !headers || Array.isArray(headers)) return headers;
427
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
428
+ return headers;
429
+ }
430
+ const encoded = { ...headers } as Record<string, unknown>;
431
+ for (const name of names) {
432
+ if (encoded[name] !== undefined) {
433
+ encoded[name] = JSON.stringify(encoded[name]);
434
+ }
435
+ }
436
+ return encoded as T;
437
+ }
438
+
439
+ function mergeHeaders(
440
+ ...sources: Array<Config["headers"] | undefined>
441
+ ): Headers {
442
+ const merged = new Headers();
443
+ for (const source of sources) {
444
+ if (!source) continue;
445
+ if (source instanceof Headers) {
446
+ source.forEach((value, key) => {
447
+ merged.set(key, value);
448
+ });
449
+ } else if (Array.isArray(source)) {
450
+ for (const [key, value] of source) merged.set(key, String(value));
451
+ } else {
452
+ for (const [key, value] of Object.entries(
453
+ source as Record<string, unknown>,
454
+ )) {
455
+ if (value === null) {
456
+ merged.delete(key);
457
+ } else if (Array.isArray(value)) {
458
+ for (const item of value) merged.append(key, String(item));
459
+ } else if (value !== undefined) {
460
+ merged.set(
461
+ key,
462
+ typeof value === "object" ? JSON.stringify(value) : String(value),
463
+ );
464
+ }
465
+ }
466
+ }
467
+ }
468
+ return merged;
469
+ }
470
+
471
+ function toFormData(body: unknown): FormData {
472
+ if (body instanceof FormData) return body;
473
+ const data = new FormData();
474
+ const append = (key: string, value: unknown) => {
475
+ if (value === undefined || value === null) return;
476
+ if (typeof value === "string" || value instanceof Blob)
477
+ data.append(key, value);
478
+ else if (value instanceof Date) data.append(key, value.toISOString());
479
+ else if (typeof value === "object") data.append(key, JSON.stringify(value));
480
+ else data.append(key, String(value));
481
+ };
482
+ for (const [key, value] of Object.entries(
483
+ (body ?? {}) as Record<string, unknown>,
484
+ )) {
485
+ if (Array.isArray(value)) for (const item of value) append(key, item);
486
+ else append(key, value);
487
+ }
488
+ return data;
489
+ }
490
+
491
+ function toSearchParams(body: unknown): URLSearchParams {
492
+ if (body instanceof URLSearchParams) return body;
493
+ const params = new URLSearchParams();
494
+ for (const [key, value] of Object.entries(
495
+ (body ?? {}) as Record<string, unknown>,
496
+ )) {
497
+ if (value === undefined || value === null) continue;
498
+ if (Array.isArray(value))
499
+ for (const item of value) params.append(key, primitive(item));
500
+ else params.append(key, primitive(value));
501
+ }
502
+ return params;
503
+ }
504
+
505
+ function serializeBody(options: Config): BodyInit | null | undefined {
506
+ const { body, bodySerializer, bodyType } = options;
507
+ if (body === undefined) return undefined;
508
+ if (bodySerializer) return bodySerializer(body);
509
+ // `null` means the caller serialized the body already.
510
+ if (bodySerializer === null) return body as BodyInit;
511
+ if (bodyType === "form-data") return toFormData(body);
512
+ if (bodyType === "urlencoded") return toSearchParams(body);
513
+ // A string is already a body unless the operation is JSON, where a string
514
+ // is a JSON string value and has to be quoted.
515
+ if (typeof body === "string" && bodyType !== "json") return body;
516
+ // A file stays a file, even when the operation says it holds JSON.
517
+ if (typeof body === "object" && body !== null && isBinaryBody(body)) {
518
+ return body as BodyInit;
519
+ }
520
+ if (bodyType === "json" || (typeof body === "object" && body !== null)) {
521
+ return JSON.stringify(body, (_key, value) =>
522
+ typeof value === "bigint" ? value.toString() : value,
523
+ );
524
+ }
525
+ return body as BodyInit;
526
+ }
527
+
528
+ function isBinaryBody(body: object): boolean {
529
+ return (
530
+ body instanceof Blob ||
531
+ body instanceof FormData ||
532
+ body instanceof URLSearchParams ||
533
+ body instanceof ArrayBuffer ||
534
+ ArrayBuffer.isView(body) ||
535
+ (typeof ReadableStream !== "undefined" && body instanceof ReadableStream)
536
+ );
537
+ }
538
+
539
+ function detectParseAs(contentType: string | null): Exclude<ParseAs, "auto"> {
540
+ if (!contentType) return "text";
541
+ const type = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
542
+ if (type === "application/json" || type.endsWith("+json")) return "json";
543
+ if (type === "multipart/form-data") return "formData";
544
+ if (
545
+ type.startsWith("text/") ||
546
+ type.endsWith("+xml") ||
547
+ type === "application/xml"
548
+ ) {
549
+ return "text";
550
+ }
551
+ return "blob";
552
+ }
553
+
554
+ async function getAuthToken(
555
+ auth: Auth,
556
+ callback: Config["auth"],
557
+ ): Promise<string | undefined> {
558
+ const token =
559
+ typeof callback === "function" ? await callback(auth) : callback;
560
+ if (!token) return undefined;
561
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
562
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
563
+ return token;
564
+ }
565
+
566
+ /** True when the caller already supplied this API key on the request. */
567
+ function isProvided(
568
+ auth: Auth,
569
+ query: Record<string, unknown> | undefined,
570
+ headers: Headers,
571
+ ): boolean {
572
+ const { name } = auth;
573
+ if (!name) return false;
574
+ if (auth.in === "query") return query?.[name] != null;
575
+ if (auth.in === "cookie") {
576
+ return (headers.get("Cookie") ?? "")
577
+ .split(";")
578
+ .some((cookie) => cookie.trim().startsWith(`${name}=`));
579
+ }
580
+ return headers.has(name);
581
+ }
582
+
583
+ async function applySecurity(
584
+ options: RequestOptions,
585
+ headers: Headers,
586
+ ): Promise<void> {
587
+ for (const requirement of options.security ?? []) {
588
+ const schemes = (
589
+ Array.isArray(requirement) ? requirement : [requirement]
590
+ ) as ReadonlyArray<Auth>;
591
+ const missing = schemes.filter(
592
+ (auth) => !isProvided(auth, options.query, headers),
593
+ );
594
+ const tokens = await Promise.all(
595
+ missing.map((auth) => getAuthToken(auth, options.auth)),
596
+ );
597
+ if (tokens.some((token) => !token)) continue;
598
+ missing.forEach((auth, index) => {
599
+ const name = auth.name ?? "Authorization";
600
+ const token = tokens[index] as string;
601
+ if (auth.in === "query") {
602
+ options.query = { ...options.query, [name]: token };
603
+ } else if (auth.in === "cookie") {
604
+ const cookie = headers.get("Cookie");
605
+ headers.set(
606
+ "Cookie",
607
+ cookie ? `${cookie}; ${name}=${token}` : `${name}=${token}`,
608
+ );
609
+ } else {
610
+ headers.set(name, token);
611
+ }
612
+ });
613
+ }
614
+ }
615
+
616
+ async function parseBody(
617
+ response: Response,
618
+ parseAs: ParseAs,
619
+ ): Promise<unknown> {
620
+ const mode =
621
+ parseAs === "auto"
622
+ ? detectParseAs(response.headers.get("Content-Type"))
623
+ : parseAs;
624
+ if (mode === "stream") return response.body;
625
+ if (
626
+ response.status === 204 ||
627
+ response.headers.get("Content-Length") === "0"
628
+ ) {
629
+ if (mode === "json") return {};
630
+ if (mode === "formData") return new FormData();
631
+ // TanStack Query rejects `undefined` as data.
632
+ if (parseAs === "auto" && !response.headers.has("Content-Type")) {
633
+ return null;
634
+ }
635
+ }
636
+ switch (mode) {
637
+ case "json": {
638
+ const text = await response.text();
639
+ return text ? JSON.parse(text) : {};
640
+ }
641
+ case "text":
642
+ return response.text();
643
+ case "blob":
644
+ return response.blob();
645
+ case "arrayBuffer":
646
+ return response.arrayBuffer();
647
+ case "formData":
648
+ return response.formData();
649
+ default:
650
+ return undefined;
651
+ }
652
+ }
653
+
654
+ export const createConfig = <T extends ClientOptions = ClientOptions>(
655
+ override: Config<ClientOptions & T> = {},
656
+ ): Config<Required<ClientOptions> & T> =>
657
+ ({
658
+ parseAs: "auto",
659
+ ...override,
660
+ }) as Config<Required<ClientOptions> & T>;
661
+
662
+ const mergeConfigs = (base: Config, override: Config): Config => ({
663
+ ...base,
664
+ ...override,
665
+ headers: mergeHeaders(base.headers, override.headers),
666
+ });
667
+
668
+ export const createClient = (config: Config = {}): Client => {
669
+ let currentConfig: Config = mergeConfigs(createConfig(), config);
670
+
671
+ const getConfig = (): Config => ({ ...currentConfig });
672
+ const setConfig = (next: Config): Config => {
673
+ currentConfig = mergeConfigs(currentConfig, next);
674
+ return getConfig();
675
+ };
676
+
677
+ const interceptors = {
678
+ error: new Interceptors<ErrorInterceptor>(),
679
+ request: new Interceptors<RequestInterceptor>(),
680
+ response: new Interceptors<ResponseInterceptor>(),
681
+ };
682
+
683
+ const request = async (userOptions: RequestOptions) => {
684
+ const options = {
685
+ ...currentConfig,
686
+ ...userOptions,
687
+ } as ResolvedRequestOptions;
688
+ const doFetch = options.fetch ?? currentConfig.fetch ?? globalThis.fetch;
689
+ let req: Request | undefined;
690
+ let response: Response | undefined;
691
+ let error: unknown;
692
+ try {
693
+ const headers = mergeHeaders(
694
+ currentConfig.headers,
695
+ encodeJsonHeaders(userOptions.headers, options.jsonHeaders),
696
+ );
697
+ // Interceptors read the headers the request really has.
698
+ options.headers = headers;
699
+ await applySecurity(options, headers);
700
+
701
+ const body = serializeBody(options);
702
+ // An object goes out as JSON whether or not the call says so.
703
+ const sendsJson =
704
+ options.bodyType === "json" ||
705
+ (options.bodyType === undefined &&
706
+ options.bodySerializer === undefined &&
707
+ typeof options.body === "object" &&
708
+ options.body !== null &&
709
+ !isBinaryBody(options.body));
710
+ if (body !== undefined && !headers.has("Content-Type") && sendsJson) {
711
+ headers.set("Content-Type", "application/json");
712
+ }
713
+ if (body === undefined || body === "") headers.delete("Content-Type");
714
+
715
+ const init: Record<string, unknown> = {};
716
+ for (const key of REQUEST_INIT_KEYS) {
717
+ const value = (options as unknown as Record<string, unknown>)[key];
718
+ if (value !== undefined) init[key] = value;
719
+ }
720
+ if (init.redirect === undefined) init.redirect = "follow";
721
+ if (
722
+ body !== undefined &&
723
+ body !== null &&
724
+ typeof body === "object" &&
725
+ "getReader" in body
726
+ ) {
727
+ init.duplex = "half";
728
+ }
729
+
730
+ req = new Request(buildUrl(options), {
731
+ ...init,
732
+ body: body as BodyInit | null | undefined,
733
+ headers,
734
+ });
735
+ for (const fn of interceptors.request.fns) {
736
+ if (fn) req = await fn(req, options);
737
+ }
738
+ response = await doFetch(req);
739
+ for (const fn of interceptors.response.fns) {
740
+ if (fn) response = await fn(response, req, options);
741
+ }
742
+ if (response.ok) {
743
+ const data = await parseBody(response, options.parseAs ?? "auto");
744
+ return {
745
+ data: options.responseTransformer
746
+ ? await options.responseTransformer(data)
747
+ : data,
748
+ request: req,
749
+ response,
750
+ };
751
+ }
752
+ const text = await response.text();
753
+ try {
754
+ error = JSON.parse(text);
755
+ } catch {
756
+ error = text;
757
+ }
758
+ } catch (cause) {
759
+ error = cause;
760
+ }
761
+
762
+ for (const fn of interceptors.error.fns) {
763
+ if (fn) error = await fn(error, response, req, options);
764
+ }
765
+ error = error || {};
766
+ if (options.throwOnError ?? currentConfig.throwOnError) throw error;
767
+ return {
768
+ error,
769
+ request: req as Request,
770
+ response: response as Response,
771
+ };
772
+ };
773
+
774
+ const method =
775
+ (name: NonNullable<Config["method"]>): MethodFn =>
776
+ (options) =>
777
+ request({ ...options, method: name } as RequestOptions) as never;
778
+
779
+ return {
780
+ buildUrl: (options) => buildUrl({ ...currentConfig, ...options }),
781
+ connect: method("CONNECT"),
782
+ delete: method("DELETE"),
783
+ get: method("GET"),
784
+ getConfig,
785
+ head: method("HEAD"),
786
+ interceptors,
787
+ options: method("OPTIONS"),
788
+ patch: method("PATCH"),
789
+ post: method("POST"),
790
+ put: method("PUT"),
791
+ request: request as never,
792
+ setConfig,
793
+ trace: method("TRACE"),
794
+ };
795
+ };