@kubb/plugin-axios 5.14.0-canary.20261109T125041 → 6.0.0

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.
@@ -20,7 +20,7 @@
20
20
  "dependencies": ["plugin-ts"],
21
21
  "optionalDependencies": ["plugin-zod"],
22
22
  "compatibility": {
23
- "kubb": ">=5.16.0",
23
+ "kubb": ">=5.18.4",
24
24
  "node": ">=22.22"
25
25
  },
26
26
  "role": "client",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-axios",
3
- "version": "5.14.0-canary.20261109T125041",
3
+ "version": "6.0.0",
4
4
  "description": "Generate a slim, type-safe HTTP client with Kubb based on axios.",
5
5
  "keywords": [
6
6
  "api-client",
@@ -39,6 +39,10 @@
39
39
  "src",
40
40
  "dist",
41
41
  "templates",
42
+ "!templates/config.ts",
43
+ "!templates/core.ts",
44
+ "!templates/serializers.ts",
45
+ "!templates/standardSchema.ts",
42
46
  "kubb-extension.json",
43
47
  "docs",
44
48
  "!/**/**.test.**",
@@ -67,8 +71,7 @@
67
71
  "./package.json": "./package.json",
68
72
  "./kubb-extension.json": "./kubb-extension.json",
69
73
  "./templates/*.ts": {
70
- "types": "./dist/templates/*.d.ts",
71
- "default": "./templates/*.ts"
74
+ "types": "./dist/templates/*.d.ts"
72
75
  },
73
76
  "./templates/*.js": {
74
77
  "types": "./dist/templates/*.d.ts"
@@ -80,15 +83,10 @@
80
83
  "registry": "https://registry.npmjs.org/"
81
84
  },
82
85
  "dependencies": {
83
- "@kubb/kit": "^5.16.0",
84
- "@kubb/plugin-client": "^5.12.0-canary.20261109T125041",
85
- "@kubb/plugin-ts": "^5.5.0-canary.20261109T125041",
86
- "@kubb/plugin-zod": "^5.9.0-canary.20261109T125041",
87
- "@kubb/renderer-jsx": "^5.16.0"
86
+ "@kubb/kit": "^5.18.6",
87
+ "@kubb/plugin-client": "^6.0.0"
88
88
  },
89
89
  "devDependencies": {
90
- "@internals/client": "0.1.0-canary.20261109T125041",
91
- "@internals/shared": "0.1.0-canary.20261109T125041",
92
90
  "axios": "^1.21.0",
93
91
  "typescript": "^7.0.2"
94
92
  },
package/src/index.ts CHANGED
@@ -1,3 +1,2 @@
1
- export { clientGenerator } from './generators/clientGenerator.tsx'
2
1
  export { default, pluginAxios, pluginAxiosName } from './plugin.ts'
3
2
  export type { Options, PluginAxios, ResolvedOptions, ResolverClient } from './types.ts'
package/src/plugin.ts CHANGED
@@ -1,14 +1,9 @@
1
- import path from 'node:path'
2
- import { createSdkGenerator, defaultMacros, isValidatorEnabled, resolverClient } from '@internals/client'
3
- import { createGroupConfig } from '@internals/shared'
4
- import { addGenerator, defineExtension, injectFile, Resolver, setMacros, setResolver, useConfig } from '@kubb/kit'
1
+ import { fileURLToPath } from 'node:url'
2
+ import { defineExtension } from '@kubb/kit'
3
+ import { clientDependencies, resolveClientOptions, setupClient } from '@kubb/plugin-client'
5
4
  import { compatibility } from '../kubb-extension.json'
6
5
  import { version } from '../package.json'
7
- import { pluginTsName } from '@kubb/plugin-ts'
8
- import { pluginZodName } from '@kubb/plugin-zod'
9
- import { clientGenerator } from './generators/clientGenerator.tsx'
10
- import { axiosClientTemplatePath, coreTemplatePath, serializersTemplatePath, sseTemplatePath, standardSchemaTemplatePath } from './templates.ts'
11
- import type { PluginAxios, ResolvedOptions, ResolverClient } from './types.ts'
6
+ import type { PluginAxios } from './types.ts'
12
7
 
13
8
  /**
14
9
  * Canonical plugin name for `@kubb/plugin-axios`. Used for driver lookups and cross-plugin
@@ -41,72 +36,10 @@ export const pluginAxiosName = 'plugin-axios' satisfies PluginAxios['name']
41
36
  export const pluginAxios = defineExtension<PluginAxios>({
42
37
  kind: 'plugin',
43
38
  meta: { name: pluginAxiosName, version, compatibility },
44
- // `plugin-ts` supplies the operation types unless it is absent, in which case `pluginZod({ inferred: true })`
45
- // does. `plugin-zod` is required once `validator` enables a direction, so a missing one fails setup instead of codegen.
46
- dependencies: (options) => ({ [pluginTsName]: { optional: true }, [pluginZodName]: { optional: !isValidatorEnabled(options.validator) } }),
39
+ dependencies: clientDependencies,
47
40
  setup(options) {
48
- const config = useConfig()
49
- const {
50
- output = { path: 'clients', barrel: { type: 'named' } },
51
- exclude = [],
52
- include,
53
- override = [],
54
- baseURL,
55
- throwOnErrorDefault = true,
56
- validator = false,
57
- returnType = 'full',
58
- group,
59
- sdk,
60
- resolver: userResolver,
61
- } = options
62
-
63
- const resolved: ResolvedOptions = {
64
- output,
65
- exclude,
66
- include,
67
- override,
68
- group: createGroupConfig(group),
69
- baseURL,
70
- throwOnErrorDefault,
71
- validator,
72
- returnType,
73
- sdk: sdk ? { mode: sdk.mode ?? 'tag', name: sdk.name } : undefined,
74
- resolver: userResolver ? Resolver.merge<ResolverClient>(resolverClient, userResolver) : resolverClient,
75
- }
76
-
77
- setResolver(resolved.resolver)
78
- setMacros([...defaultMacros, ...(options.macros ?? [])])
79
-
80
- // `sdk` swaps the per-operation functions for the class-based SDK; left unset, the standalone
81
- // functions (which query plugins consume) stay.
82
- addGenerator(resolved.sdk ? createSdkGenerator<PluginAxios>({ sse: sseTemplatePath }) : clientGenerator)
83
-
84
- const root = path.resolve(config.root, config.output.path)
85
-
86
- injectFile({
87
- baseName: 'serializers.ts',
88
- path: path.resolve(root, '.kubb/serializers.ts'),
89
- copy: serializersTemplatePath,
90
- })
91
-
92
- injectFile({
93
- baseName: 'core.ts',
94
- path: path.resolve(root, '.kubb/core.ts'),
95
- copy: coreTemplatePath,
96
- })
97
-
98
- injectFile({
99
- baseName: 'client.ts',
100
- path: path.resolve(root, '.kubb/client.ts'),
101
- copy: axiosClientTemplatePath,
102
- })
103
-
104
- injectFile({
105
- baseName: 'standardSchema.ts',
106
- path: path.resolve(root, '.kubb/standardSchema.ts'),
107
- copy: standardSchemaTemplatePath,
108
- })
109
-
41
+ const resolved = resolveClientOptions(options)
42
+ setupClient({ name: 'axios', resolved, macros: options.macros, client: fileURLToPath(new URL('../templates/client.ts', import.meta.url)) })
110
43
  return resolved
111
44
  },
112
45
  })
package/src/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { PluginType } from '@kubb/kit'
2
- import type { Options, ResolvedOptions, ResolverClient } from '@internals/client'
2
+ import type { ClientOptions as Options, ClientResolvedOptions as ResolvedOptions, ResolverClient } from '@kubb/plugin-client'
3
3
 
4
- export type { Options, ResolvedOptions, ResolverClient } from '@internals/client'
4
+ export type { ClientOptions as Options, ClientResolvedOptions as ResolvedOptions, ResolverClient } from '@kubb/plugin-client'
5
5
 
6
6
  /**
7
7
  * The plugin factory type for `@kubb/plugin-axios`. Shares the options surface, resolver, and
@@ -1,46 +1,23 @@
1
1
  import axios from 'axios'
2
- import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
3
- import { getResponseContentType, isStreamed, resolveResponseType, type CallResult, type ResponseType, type ResponseTypeMap, type Transport } from './core.ts'
4
- import { isJsonMediaType } from './serializers.ts'
2
+ import type { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
3
+ import { createClientCore, createLazyClient, getHeader } from './core.ts'
4
+ import { defaultConfig } from './config.ts'
5
5
  import * as core from './core.ts'
6
6
 
7
7
  export * from './core.ts'
8
8
 
9
- /** The request and response objects of this transport, carried on every result and error. */
9
+ /**
10
+ * The native request and response that every result and error carries.
11
+ */
10
12
  export type NativeRequest = AxiosRequestConfig
11
13
  export type NativeResponse = AxiosResponse
12
14
 
13
15
  /**
14
- * Extra axios config the transport spreads onto every request, an escape hatch for per-call fields the runtime does not set itself such as `timeout`, `proxy`, and the progress callbacks.
16
+ * Extra axios config for a call or client, such as `timeout`, `proxy`, or the progress callbacks.
15
17
  */
16
- export type AxiosOptions = AxiosRequestConfig
17
-
18
- /** A transport as this client accepts it: an axios instance, which `createAxiosTransport` wraps, or a transport function. */
19
- export type AxiosTransport = AxiosInstance | Transport
18
+ export type NativeOptions = AxiosRequestConfig
20
19
 
21
- type AxiosOverrides = {
22
- options?: AxiosOptions
23
- transport?: AxiosTransport
24
- /**
25
- * @deprecated Has no effect. The client splits success from error by status, so axios never throws on a status.
26
- */
27
- validateStatus?: (status: number) => boolean
28
- }
29
-
30
- export type RequestConfig<TBody = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = Omit<
31
- core.RequestConfig<TBody, TRequest, TResponse>,
32
- 'transport' | 'client'
33
- > &
34
- AxiosOverrides & { client?: ClientInstance<TRequest, TResponse> }
35
- export type Options<TData extends core.DataShape, ThrowOnError extends boolean = true, TRequest = NativeRequest, TResponse = NativeResponse> = Omit<
36
- core.Options<TData, ThrowOnError, TRequest, TResponse>,
37
- 'transport' | 'client'
38
- > &
39
- AxiosOverrides & { client?: ClientInstance<TRequest, TResponse> }
40
- export type ClientConfig<TRequest = NativeRequest, TResponse = NativeResponse> = Omit<core.ClientConfig<TRequest, TResponse>, 'transport'> & AxiosOverrides
41
- export type ResolvedRequest = core.ResolvedRequest & { options?: AxiosOptions }
42
20
  export type ResponseError<TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.ResponseError<TError, TRequest, TResponse>
43
- /** The core's `ResponseError` class, typed with this transport's request and response. `instanceof` and `ResponseError.is` both match what the client throws. */
44
21
  export const ResponseError = core.ResponseError as {
45
22
  new <TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse>(
46
23
  config: ConstructorParameters<typeof core.ResponseError<TError, TRequest, TResponse>>[0],
@@ -49,35 +26,55 @@ export const ResponseError = core.ResponseError as {
49
26
  prototype: core.ResponseError<unknown, NativeRequest, NativeResponse>
50
27
  }
51
28
 
52
- /** An interceptor handler. It receives the native axios object; the second argument is kept for handlers written against earlier versions and is always `undefined`. */
53
- export type InterceptorFn<T> = (value: T, requestConfig?: RequestConfig) => T | Promise<T>
54
-
55
- /** Registers, removes, or replaces handlers on axios's own interceptor managers. */
56
- export type InterceptorChannel<T> = {
57
- use: (fn: InterceptorFn<T>) => number
58
- eject: (id: number) => void
59
- update: (id: number, fn: InterceptorFn<T>) => void
60
- }
61
-
62
- /** The interceptors of `defaultTransport`: request handlers see the `InternalAxiosRequestConfig`, response handlers the `AxiosResponse`, error handlers the `AxiosError`. */
63
- export type Interceptors = {
64
- request: InterceptorChannel<InternalAxiosRequestConfig>
65
- response: InterceptorChannel<AxiosResponse>
66
- error: InterceptorChannel<AxiosError>
67
- }
68
-
69
- export type ClientInstance<TRequest = NativeRequest, TResponse = NativeResponse> = {
70
- <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>): Promise<CallResult<TRequest, TResponse>>
71
- getConfig: () => ClientConfig<TRequest, TResponse>
72
- setConfig: (config: ClientConfig<TRequest, TResponse>) => ClientConfig<TRequest, TResponse>
73
- getUrl: core.ClientInstance<TRequest, TResponse>['getUrl']
74
- interceptors: Interceptors
75
- createClient: (config?: ClientConfig<TRequest, TResponse>) => ClientInstance<TRequest, TResponse>
76
- }
29
+ export type RequestConfig<TBody = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.RequestConfig<TBody, TRequest, TResponse> & {
30
+ options?: NativeOptions
31
+ }
32
+ export type Options<TData extends core.DataShape, ThrowOnError extends boolean = true, TRequest = NativeRequest, TResponse = NativeResponse> = core.Options<
33
+ TData,
34
+ ThrowOnError,
35
+ TRequest,
36
+ TResponse
37
+ > & { options?: NativeOptions }
38
+ export type ClientConfig<TRequest = NativeRequest, TResponse = NativeResponse> = core.ClientConfig<TRequest, TResponse> & { options?: NativeOptions }
39
+ export type ResolvedRequest = core.ResolvedRequest & { options?: NativeOptions }
40
+ export type RequestResult<
41
+ TResponses,
42
+ ThrowOnError extends boolean = true,
43
+ TRequest = NativeRequest,
44
+ TResponse = NativeResponse,
45
+ THeaders = unknown,
46
+ > = core.RequestResult<TResponses, ThrowOnError, TRequest, TResponse, THeaders>
47
+ export type UnwrappedResult<
48
+ TResponses,
49
+ ThrowOnError extends boolean = true,
50
+ TRequest = NativeRequest,
51
+ TResponse = NativeResponse,
52
+ THeaders = unknown,
53
+ > = core.UnwrappedResult<TResponses, ThrowOnError, TRequest, TResponse, THeaders>
54
+ export type ResponseErrorConfig<TError = unknown> = core.ResponseError<TError, NativeRequest, NativeResponse>
55
+ export type TransportResult<TRequest = NativeRequest, TResponse = NativeResponse> = core.TransportResult<TRequest, TResponse>
56
+ export type DecodedResponse<TData = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.DecodedResponse<TData, TRequest, TResponse>
57
+ export type Transport<TRequest = NativeRequest, TResponse = NativeResponse> = core.Transport<TRequest, TResponse>
58
+ export type Interceptors<TRequest = NativeRequest, TResponse = NativeResponse> = core.Interceptors<TRequest, TResponse>
59
+ export type ClientInstance<TRequest = NativeRequest, TResponse = NativeResponse> = core.ClientInstance<TRequest, TResponse>
60
+ export type StreamResult<
61
+ TResponses,
62
+ ThrowOnError extends boolean = true,
63
+ TEvent = core.ServerSentEvent<core.SuccessOf<TResponses>>,
64
+ TRequest = NativeRequest,
65
+ TResponse = NativeResponse,
66
+ THeaders = unknown,
67
+ > = core.StreamResult<TResponses, ThrowOnError, TEvent, TRequest, TResponse, THeaders>
68
+ export type ResponseErrorOf<TResponses, TRequest = NativeRequest, TResponse = NativeResponse, THeaders = unknown> = core.ResponseErrorOf<
69
+ TResponses,
70
+ TRequest,
71
+ TResponse,
72
+ THeaders
73
+ >
74
+ export const isResponseError = core.isResponseError as <TResponses = unknown, TRequest = NativeRequest, TResponse = NativeResponse, THeaders = unknown>(
75
+ error: unknown,
76
+ ) => error is ResponseErrorOf<TResponses, TRequest, TResponse, THeaders>
77
77
 
78
- /**
79
- * Collects the headers axios read into a `Headers`, so the core and the interceptors see one shape for every transport.
80
- */
81
78
  function toHeaders(raw: AxiosResponse['headers']): Headers {
82
79
  const headers = new Headers()
83
80
  for (const [name, value] of Object.entries(raw ?? {})) {
@@ -87,225 +84,117 @@ function toHeaders(raw: AxiosResponse['headers']): Headers {
87
84
  return headers
88
85
  }
89
86
 
90
- async function readStreamedText(data: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>): Promise<string> {
91
- if (data instanceof ReadableStream) return new Response(data).text()
92
- const decoder = new TextDecoder()
93
- let text = ''
94
- for await (const chunk of data) text += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })
95
- return text + decoder.decode()
87
+ // The Node adapter rejects a typed array, and labels a Blob with its own type over the `Content-Type` header.
88
+ function toAxiosData(body: unknown, contentType: string | undefined): unknown {
89
+ if (ArrayBuffer.isView(body)) return body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)
90
+ if (body instanceof Blob && contentType && body.type !== contentType) return new Blob([body], { type: contentType })
91
+ return body
96
92
  }
97
93
 
98
- /**
99
- * Reads a streamed JSON body, or any streamed error body, back into its value, because every adapter streams a
100
- * `responseType: 'stream'` answer: the fetch adapter as a `ReadableStream`, the Node adapter as a readable. Any other
101
- * streamed success body stays a stream.
102
- */
103
- async function readStreamedBody({ data, contentType, status }: { data: unknown; contentType: string | undefined; status: number }): Promise<unknown> {
104
- if (!isStreamed(data) || !(status >= 300 || isJsonMediaType(contentType))) return data
105
- const text = await readStreamedText(data)
106
- if (!text) return undefined
94
+ function resolveAdapter(adapter: AxiosRequestConfig['adapter']): unknown {
107
95
  try {
108
- return JSON.parse(text)
96
+ return axios.getAdapter(adapter)
109
97
  } catch {
110
- return text
98
+ return undefined
111
99
  }
112
100
  }
113
101
 
114
- async function readStreamedBytes(data: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>): Promise<Uint8Array> {
115
- if (data instanceof ReadableStream) return new Uint8Array(await new Response(data).arrayBuffer())
116
- const chunks: Array<Uint8Array> = []
117
- for await (const chunk of data) chunks.push(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk)
118
- return new Uint8Array(await new Blob(chunks as Array<BlobPart>).arrayBuffer())
102
+ // FormData, URLSearchParams, and a typed Blob set their own `Content-Type`, as they do on fetch.
103
+ function hasOwnContentType(body: unknown): boolean {
104
+ return body instanceof FormData || body instanceof URLSearchParams || (body instanceof Blob && body.type !== '')
119
105
  }
120
106
 
121
- function toBytes(data: unknown): Uint8Array | undefined {
122
- if (data instanceof ArrayBuffer) return new Uint8Array(data)
123
- if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
124
- return undefined
107
+ // A stream aborted mid-read rejects with axios's `CanceledError`, so rethrow the signal's reason, as fetch does.
108
+ function rethrowAbort(source: AsyncIterable<Uint8Array>, signal: AbortSignal): ReadableStream<Uint8Array> {
109
+ const iterator = source[Symbol.asyncIterator]()
110
+ return new ReadableStream({
111
+ async pull(controller) {
112
+ try {
113
+ const { done, value } = await iterator.next()
114
+ if (done) controller.close()
115
+ else controller.enqueue(value)
116
+ } catch (error) {
117
+ controller.error(signal.aborted && axios.isCancel(error) ? signal.reason : error)
118
+ }
119
+ },
120
+ async cancel(reason) {
121
+ await iterator.return?.(reason)
122
+ },
123
+ })
125
124
  }
126
125
 
127
- /** Decodes raw bytes with the parser a `responseType` map picked for the response content type. */
128
- function decodeBytes(bytes: Uint8Array, responseType: ResponseType | undefined, contentType: string | undefined): unknown {
129
- switch (responseType) {
130
- case 'blob':
131
- return new Blob([bytes as BlobPart], { type: contentType ?? '' })
132
- case 'arraybuffer':
133
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
134
- case 'stream':
135
- return new Blob([bytes as BlobPart]).stream()
136
- case 'text':
137
- case 'document':
138
- return new TextDecoder().decode(bytes)
139
- }
140
- const text = new TextDecoder().decode(bytes)
141
- if (!text) return undefined
142
- try {
143
- return JSON.parse(text)
144
- } catch {
145
- return text
146
- }
147
- }
126
+ let axiosFetchAdapter: unknown
148
127
 
149
- /**
150
- * Decodes a body read for a `responseType` map. Bytes are decoded by the mapped parser. A streamed body stays a stream
151
- * when the map picks `'stream'` for a success, and is read and decoded otherwise. Anything else was already decoded.
152
- */
153
- async function decodeMappedBody({
154
- data,
155
- responseTypeMap,
156
- contentType,
157
- status,
158
- }: {
159
- data: unknown
160
- responseTypeMap: ResponseTypeMap
161
- contentType: string | undefined
162
- status: number
163
- }): Promise<unknown> {
164
- const responseType = resolveResponseType(responseTypeMap, contentType)
165
- if (isStreamed(data)) {
166
- if (responseType === 'stream' && status < 300) return data
167
- return decodeBytes(await readStreamedBytes(data), responseType, contentType)
168
- }
169
- const bytes = toBytes(data)
170
- return bytes ? decodeBytes(bytes, responseType, contentType) : data
171
- }
128
+ // A mock such as `axios-mock-adapter` replaces the default adapter list, so the axios 1.x list is the fallback.
129
+ let axiosDefaultAdapters: string | undefined
172
130
 
173
131
  /**
174
- * Turns an axios instance into a transport: each resolved request becomes one `instance.request` with the instance's
175
- * defaults, adapter, and axios interceptors. Every status resolves, because the core splits success from error itself.
132
+ * Turns an axios instance into a transport that keeps its defaults, adapter, and interceptors.
176
133
  */
177
- export function createAxiosTransport(instance: AxiosInstance): Transport {
134
+ export function createAxiosTransport(instance: AxiosInstance): (request: core.ResolvedRequest) => Promise<TransportResult> {
178
135
  return async (request) => {
136
+ axiosFetchAdapter ??= resolveAdapter('fetch')
137
+ axiosDefaultAdapters ??= Array.isArray(axios.defaults.adapter) ? String(axios.defaults.adapter) : 'xhr,http,fetch'
138
+ const contentType = getHeader(request.headers, 'content-type')
179
139
  const config: AxiosRequestConfig = {
180
140
  ...request.options,
181
141
  url: request.url,
182
142
  method: request.method,
183
- headers: request.headers,
184
- data: request.body,
185
- // Kubb already serialized the body; only URLSearchParams needs a string, since axios's Node adapter rejects it.
143
+ // axios labels a body without a content type as a form, so `false` leaves the header off, as fetch does. Bodies
144
+ // that carry their own type keep it.
145
+ headers: contentType === undefined && !hasOwnContentType(request.body) ? { ...request.headers, 'Content-Type': false } : request.headers,
146
+ data: toAxiosData(request.body, contentType),
147
+ // The body is already encoded. Only `URLSearchParams` needs a string, since the Node adapter rejects it.
186
148
  transformRequest: (data) => (data instanceof URLSearchParams ? data.toString() : data),
187
- signal: request.signal,
188
- responseType: typeof request.responseType === 'object' ? undefined : request.responseType,
149
+ responseType: request.stream ? 'stream' : 'arraybuffer',
150
+ transformResponse: (data) => data,
189
151
  validateStatus: () => true,
190
152
  }
191
-
192
- // Axios picks how to read the body before the Content-Type is known, so a map reads raw bytes and decodes them once it
193
- // is. A map with a stream entry reads a stream, so an event stream still arrives incrementally. Bytes are decoded in
194
- // `transformResponse`, before the axios interceptors run, so they see the parsed body.
195
- const responseTypeMap = typeof request.responseType === 'object' ? request.responseType : undefined
196
- if (responseTypeMap) {
197
- config.responseType = Object.values(responseTypeMap).includes('stream') ? 'stream' : 'arraybuffer'
198
- config.transformResponse = (data, headers) => {
199
- const bytes = toBytes(data)
200
- if (!bytes) return data
201
- const contentType = getResponseContentType(toHeaders(headers))
202
- return decodeBytes(bytes, resolveResponseType(responseTypeMap, contentType), contentType)
203
- }
153
+ if (request.signal) config.signal = request.signal
154
+
155
+ // XHR buffers the body and cannot omit same-origin cookies, so a stream or `credentials: 'omit'` uses fetch in the browser.
156
+ const instanceAdapter = instance.defaults?.adapter
157
+ const defaultAdapter = !instanceAdapter || String(instanceAdapter) === axiosDefaultAdapters
158
+ const needsFetch = request.stream || request.credentials === 'omit'
159
+ if (needsFetch && !config.adapter && defaultAdapter && typeof XMLHttpRequest !== 'undefined') config.adapter = 'fetch'
160
+ // The Node and XHR adapters cannot send a web `ReadableStream`, so it goes through fetch everywhere.
161
+ if (request.body instanceof ReadableStream && !config.adapter && defaultAdapter) config.adapter = 'fetch'
162
+
163
+ // The fetch adapter takes `credentials` as is. The other adapters only know a boolean.
164
+ const adapter = resolveAdapter(config.adapter ?? instanceAdapter)
165
+ const fetchAdapter = adapter !== undefined && adapter === axiosFetchAdapter
166
+ if (request.credentials) {
167
+ config.withCredentials = fetchAdapter ? (request.credentials as unknown as boolean) : request.credentials === 'include'
204
168
  }
205
169
 
206
- // In the browser the default adapters pick XHR, which buffers the whole body, so a stream switches to fetch. An adapter set
207
- // on the call or the instance, and the Node http adapter with its proxy and agent, are kept.
208
- const defaultAdapter = !instance.defaults?.adapter || String(instance.defaults.adapter) === String(axios.defaults.adapter)
209
- if (config.responseType === 'stream' && !config.adapter && defaultAdapter && typeof XMLHttpRequest !== 'undefined') config.adapter = 'fetch'
210
-
211
- const response = await instance.request<unknown>(config)
212
- const headers = toHeaders(response.headers)
213
- const contentType = getResponseContentType(headers)
214
-
215
- return {
216
- data: responseTypeMap
217
- ? await decodeMappedBody({ data: response.data, responseTypeMap, contentType, status: response.status })
218
- : await readStreamedBody({ data: response.data, contentType, status: response.status }),
219
- status: response.status,
220
- statusText: response.statusText,
221
- headers,
222
- contentType,
223
- request: response.config,
224
- response,
225
- }
170
+ // Rethrow the signal's reason, as fetch does, instead of axios's `CanceledError`.
171
+ const response = await instance.request<unknown>(config).catch((error: unknown) => {
172
+ throw request.signal?.aborted && axios.isCancel(error) ? request.signal.reason : error
173
+ })
174
+ const { data, status, statusText } = response
175
+ // A null-body status cannot carry a body, and an adapter may read a missing body as ''.
176
+ const raw = [204, 205, 304].includes(status) || data === '' || data == null ? null : (data as BodyInit)
177
+ const body =
178
+ request.stream && request.signal && Symbol.asyncIterator in Object(raw) ? rethrowAbort(raw as unknown as AsyncIterable<Uint8Array>, request.signal) : raw
179
+ return { webResponse: new Response(body, { status, statusText, headers: toHeaders(response.headers) }), request: response.config, response }
226
180
  }
227
181
  }
228
182
 
229
- function isAxiosInstance(value: unknown): value is AxiosInstance {
230
- return typeof value === 'function' && 'request' in value && 'interceptors' in value
231
- }
232
-
233
- function toTransport<T extends { transport?: AxiosTransport }>(config: T): Omit<T, 'transport'> & { transport?: Transport } {
234
- return { ...config, transport: isAxiosInstance(config.transport) ? createAxiosTransport(config.transport) : config.transport }
235
- }
236
-
237
- /**
238
- * Maps the kubb interceptor API onto the native managers of `instance`, keeping one id per handler so `eject` and `update`
239
- * keep working after an `update`.
240
- */
241
- function nativeInterceptors(instance: AxiosInstance): Interceptors {
242
- const channel = <T>(eject: (nativeId: number) => void, register: (fn: InterceptorFn<T>) => number): InterceptorChannel<T> => {
243
- const nativeIds = new Map<number, number>()
244
- let counter = 0
245
- return {
246
- use(fn) {
247
- const id = ++counter
248
- nativeIds.set(id, register(fn))
249
- return id
250
- },
251
- eject(id) {
252
- const nativeId = nativeIds.get(id)
253
- if (nativeId !== undefined) eject(nativeId)
254
- nativeIds.delete(id)
255
- },
256
- update(id, fn) {
257
- const nativeId = nativeIds.get(id)
258
- if (nativeId === undefined) return
259
- eject(nativeId)
260
- nativeIds.set(id, register(fn))
261
- },
262
- }
263
- }
264
- const ejectRequest = (id: number) => instance.interceptors.request.eject(id)
265
- const ejectResponse = (id: number) => instance.interceptors.response.eject(id)
266
- return {
267
- request: channel(ejectRequest, (fn) => instance.interceptors.request.use((config) => fn(config))),
268
- response: channel(ejectResponse, (fn) => instance.interceptors.response.use((response) => fn(response))),
269
- error: channel(ejectResponse, (fn) =>
270
- instance.interceptors.response.use(undefined, async (error: AxiosError) => {
271
- throw (await fn(error)) ?? error
272
- }),
273
- ),
274
- }
275
- }
183
+ let instance: AxiosInstance | undefined
276
184
 
277
185
  /**
278
- * Wraps a core client for axios callers: an `AxiosInstance` passed as `transport` is wrapped by `createAxiosTransport`,
279
- * `client.interceptors` registers on `instance`, and `createClient` gives the child its own instance.
186
+ * The axios instance `defaultTransport` sends through, created on first use.
280
187
  */
281
- function createAxiosClient(instance: AxiosInstance, config: ClientConfig = {}, defaultTransport: Transport = createAxiosTransport(instance)): ClientInstance {
282
- const inner = core.createClientCore<NativeRequest, NativeResponse>({ defaultTransport, ...toTransport(config) })
283
- // `client` never reaches the core: the generated operation destructures it before the call.
284
- const client = ((requestConfig) => inner(toTransport(requestConfig) as core.RequestConfig<unknown, NativeRequest, NativeResponse>)) as ClientInstance
285
- client.getConfig = inner.getConfig
286
- client.setConfig = (next) => inner.setConfig(toTransport(next))
287
- client.getUrl = inner.getUrl
288
- client.interceptors = nativeInterceptors(instance)
289
- client.createClient = (next = {}) => createAxiosClient(axios.create(), { ...inner.getConfig(), ...next })
290
- return client
188
+ export function getAxiosInstance(): AxiosInstance {
189
+ return (instance ??= axios.create())
291
190
  }
292
191
 
293
- /**
294
- * The axios instance the generated `client` sends through when no transport is set. Set its defaults or register axios
295
- * interceptors on it. Instances from `createClient()` get their own.
296
- */
297
- export const defaultTransport = axios.create()
192
+ export const defaultTransport: Transport = (request) => createAxiosTransport(getAxiosInstance())(request)
298
193
 
299
194
  /**
300
- * Creates an isolated client. `defaultTransport` is the axios instance to send through, a transport function, or left out
301
- * for a new `axios.create()`.
195
+ * The client every generated operation uses unless a call passes its own. It is created on first use.
302
196
  */
303
- export function createClientCore(options: { defaultTransport?: AxiosTransport } & ClientConfig = {}): ClientInstance {
304
- const { defaultTransport: transport, ...config } = options
305
- const instance = isAxiosInstance(transport) ? transport : axios.create()
306
- return createAxiosClient(instance, config, transport && !isAxiosInstance(transport) ? transport : createAxiosTransport(instance))
307
- }
308
-
309
- export const client = createAxiosClient(defaultTransport)
197
+ export const client: ClientInstance = createLazyClient((config) => createClientCore({ defaultTransport, ...config }))
198
+ client.setConfig(defaultConfig)
310
199
 
311
- export const createClient = (config?: ClientConfig) => client.createClient(config)
200
+ export const createClient: ClientInstance['createClient'] = client.createClient