@kubb/plugin-ky 0.0.0-stage → 0.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.
@@ -0,0 +1,197 @@
1
+ # Configure requests
2
+
3
+ Set the base URL, credentials, shared headers, and interceptors on the generated Ky client, for every call or for one.
4
+
5
+ ## Where settings apply
6
+
7
+ Every generated function sends through the shared `client` from `.kubb/client.ts`, unless a call passes its own:
8
+
9
+ | Scope | How | Effect |
10
+ | ----------------- | --------------------------- | --------------------------------------------------------------------------------------- |
11
+ | Every call | `client.setConfig({ ... })` | Merges into the shared config. `headers`, `mediaTypes`, and `serializer` merge per key. |
12
+ | A separate client | `createClient({ ... })` | Copies the shared config at creation, without its interceptors. |
13
+ | A child client | `client.extend({ ... })` | Copies the shared config and runs the parent's interceptors first. |
14
+ | One call | The same key on the call | Wins over the client for that call. |
15
+
16
+ The client takes `baseURL`, `headers`, `auth`, `credentials`, `options`, `transport`, `serializer`, `mediaTypes`, `validate`, and `onValidationError`:
17
+
18
+ ```typescript
19
+ import { client, createClient } from './gen/.kubb/client'
20
+ import { getPetById } from './gen/clients/getPetById'
21
+
22
+ client.setConfig({ baseURL: import.meta.env.VITE_API_URL, headers: { 'X-Client': 'web' } })
23
+
24
+ const tenant = createClient({ baseURL: 'https://tenant.example.com', auth: () => tenantToken })
25
+ await getPetById({ path: { petId: 1 }, client: tenant })
26
+
27
+ await getPetById({ path: { petId: 1 }, baseURL: 'http://localhost:3000' })
28
+ ```
29
+
30
+ ## Set the base URL
31
+
32
+ A call uses the first base URL it finds:
33
+
34
+ | Order | Source |
35
+ | ----- | ------------------------------------------------------------------------------------------------- |
36
+ | 1 | `baseURL` on the call. |
37
+ | 2 | The operation's own `servers`, then its path's `servers`. |
38
+ | 3 | The client passed as `client`. |
39
+ | 4 | `client.setConfig({ baseURL })`. |
40
+ | 5 | The plugin's [`baseURL`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#baseurl) option. |
41
+
42
+ > [!NOTE]
43
+ > The spec's top-level `servers` URL is never used, even with the `server` option of `adapterOas`.
44
+
45
+ See [Which server a call picks](#which-server-a-call-picks) and [Named servers](#named-servers).
46
+
47
+ ## Authenticate requests
48
+
49
+ Set `auth` to a token, or to a sync or async function that gets each [security scheme](https://spec.openapis.org/oas/v3.1.0#security-scheme-object) of the call. It returns the token, or `undefined` to skip the scheme:
50
+
51
+ ```typescript
52
+ client.setConfig({
53
+ auth: (auth) => (auth.type === 'apiKey' ? apiKey : localStorage.getItem('token') ?? undefined),
54
+ })
55
+ ```
56
+
57
+ By default, `auth` adds no credentials. The scheme decides where the token goes:
58
+
59
+ | Scheme in the spec | `auth` gets | The token goes to |
60
+ | ------------------ | ---------------------------------------- | ------------------------------- |
61
+ | `http` bearer | `{ type: 'http', scheme: 'bearer' }` | `Authorization: Bearer <token>` |
62
+ | `http` basic | `{ type: 'http', scheme: 'basic' }` | `Authorization: Basic <base64>` |
63
+ | `apiKey` in header | `{ type: 'apiKey', name, in: 'header' }` | the header named `name` |
64
+ | `apiKey` in query | `{ type: 'apiKey', name, in: 'query' }` | the query parameter `name` |
65
+ | `apiKey` in cookie | `{ type: 'apiKey', name, in: 'cookie' }` | the `Cookie` header |
66
+ | `oauth2` | `{ type: 'oauth2', scopes, flows }` | `Authorization: Bearer <token>` |
67
+ | `openIdConnect` | `{ type: 'openIdConnect', scopes, url }` | `Authorization: Bearer <token>` |
68
+
69
+ > [!NOTE]
70
+ > For basic auth, return the raw `username:password`. The runtime base64-encodes it and adds the `Basic` prefix.
71
+
72
+ For a credential that no security scheme describes, such as a request signature, add a request interceptor. See [Several security schemes](#several-security-schemes) and [Mutual TLS](#mutual-tls).
73
+
74
+ ## Add interceptors
75
+
76
+ `client.interceptors` has three stacks. Each handler gets the value the one before it returned:
77
+
78
+ | Stack | Runs | Gets | Returns |
79
+ | ---------- | ----------------------------------------------------------------------- | ----------------- | ---------------------------------------------- |
80
+ | `request` | After the URL, body, and auth are built, before the send. | `ResolvedRequest` | The request. |
81
+ | `response` | After the body is decoded, before the status check and validator. | `DecodedResponse` | The result. |
82
+ | `error` | When a call fails: `ResponseError`, network error, abort, `ParseError`. | The error | Another error to throw, or nothing to keep it. |
83
+
84
+ ::code-group
85
+
86
+ ```typescript [request]
87
+ client.interceptors.request.use((request) => {
88
+ request.headers['X-Request-ID'] = crypto.randomUUID()
89
+ return request
90
+ })
91
+ ```
92
+
93
+ ```typescript [response]
94
+ client.interceptors.response.use((result) => {
95
+ console.info(`${result.status} ${result.contentType}`)
96
+ return result
97
+ })
98
+ ```
99
+
100
+ ```typescript [error]
101
+ import { client, ResponseError } from './gen/.kubb/client'
102
+
103
+ class NotFoundError extends Error {}
104
+
105
+ client.interceptors.error.use((error) => {
106
+ if (ResponseError.is(error) && error.status === 401) scheduleTokenRefresh()
107
+ if (ResponseError.is(error) && error.status === 404) return new NotFoundError(error.message)
108
+ })
109
+ ```
110
+
111
+ ::
112
+
113
+ `ResolvedRequest` has `url`, `method`, `headers`, `body`, `signal`, `credentials`, `options`, and `stream`. `DecodedResponse` has `data`, `status`, `statusText`, `headers`, `contentType`, `request`, and `response`.
114
+
115
+ Handlers run in the order you register them. `use` returns an id for `eject` and `update`:
116
+
117
+ ```typescript
118
+ const id = client.interceptors.request.use((request) => request)
119
+ client.interceptors.request.update(id, (request) => ({ ...request, headers: { ...request.headers, 'X-Trace': 'on' } }))
120
+ client.interceptors.request.eject(id)
121
+ ```
122
+
123
+ > [!NOTE]
124
+ > With `throwOnError: false`, a non-2xx response resolves, so no error handler runs for it. An error thrown while a stream is read, in the `for await` loop, does not reach the error handlers either.
125
+
126
+ ### Native Ky hooks
127
+
128
+ For the native `Request` and `Response`, pass [Ky hooks](https://github.com/sindresorhus/ky#hooks) in `options`. An `afterResponse` hook sees the response before Kubb decodes it:
129
+
130
+ ```typescript
131
+ import { client } from './gen/.kubb/client'
132
+
133
+ client.setConfig({
134
+ options: {
135
+ hooks: { beforeRequest: [({ request }) => request.headers.set('traceparent', currentTraceparent())] },
136
+ },
137
+ })
138
+ ```
139
+
140
+ For the order hooks and core handlers run in, see [Hook order](#hook-order).
141
+
142
+ Next, [use a custom transport](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/transport).
143
+
144
+ ## Less common cases
145
+
146
+ ### Which server a call picks
147
+
148
+ When an operation or path has its own `servers`, the [`server.index`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#server) of `adapterOas` picks the entry, falling back to the first. A relative URL such as `/v2`, or one with `{variable}` placeholders, is skipped, so the call uses the next source in [Set the base URL](#set-the-base-url).
149
+
150
+ The plugin's [`baseURL`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#baseurl) option is written into `.kubb/config.ts`, which `.kubb/client.ts` passes to `setConfig`.
151
+
152
+ ### Named servers
153
+
154
+ When an OpenAPI 3.2 server has a `name`, `.kubb/client.ts` exports its URL in `servers`:
155
+
156
+ ::code-group
157
+
158
+ ```yaml [petStore.yaml]
159
+ servers:
160
+ - url: https://api.example.com
161
+ name: production
162
+ - url: https://staging.example.com
163
+ name: staging
164
+ ```
165
+
166
+ ```typescript [src/api.ts]
167
+ import { client, servers } from './gen/.kubb/client'
168
+
169
+ client.setConfig({ baseURL: servers.staging })
170
+ ```
171
+
172
+ ::
173
+
174
+ ### Several security schemes
175
+
176
+ When an operation lists several security requirements, the runtime sends the first one whose schemes all get a token. A requirement that needs an API key and a session cookie sends both. A header or query key you set yourself wins over the token. An `oauth2` scheme also passes `metadataUrl` to `auth` when the spec has one.
177
+
178
+ `.kubb/client.ts` exports the spec's schemes by name as `securitySchemes`, and each generated call points at its own, with the scopes it needs:
179
+
180
+ ```typescript
181
+ security: [{ ...securitySchemes.petstore_auth, scopes: ['write:pets'] }]
182
+ ```
183
+
184
+ ### Mutual TLS
185
+
186
+ When the spec has a `mutualTLS` scheme, `securitySchemes` leaves it out, because its credential is a client certificate on the connection, not on the request. In Node.js, send through an undici `Agent` that holds the certificate, with a [custom transport](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/transport).
187
+
188
+ In the browser, the browser picks the client certificate itself.
189
+
190
+ ### Hook order
191
+
192
+ When you register [native Ky hooks](#native-ky-hooks) next to `client.interceptors`:
193
+
194
+ - `beforeRequest` hooks run after the `client.interceptors.request` handlers.
195
+ - `afterResponse` hooks see the raw response, before Kubb decodes it and before the `client.interceptors.response` handlers.
196
+ - `hooks` in the `options` of a call replace the `hooks` in the client's `options`. They do not merge.
197
+ - An instance you pass to `createKyTransport` keeps its own hooks, which run before the ones in `options`.
@@ -0,0 +1,155 @@
1
+ # Handle errors
2
+
3
+ Handle HTTP and network errors in the generated Ky client with `ResponseError`, or return errors as values with `throwOnError: false`.
4
+
5
+ ## What a call does
6
+
7
+ Only a non-2xx response depends on `throwOnError`:
8
+
9
+ | What happens | Result |
10
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------- |
11
+ | 2xx response | Resolves with `data`. |
12
+ | Non-2xx response | Throws a `ResponseError`. With `throwOnError: false`, resolves with `error` and `status`. |
13
+ | A body fails its schema (`validator` on) | Throws a `ParseError`. |
14
+ | Invalid JSON under a JSON media type | Throws a `ParseError`. |
15
+ | Network or DNS failure | Rejects with the `NetworkError` from Ky. |
16
+ | No response headers within `timeout` | Rejects with the `TimeoutError` from Ky. |
17
+ | Aborted `signal` | Rejects with the signal's reason. |
18
+
19
+ Every failure that rejects with an `Error` also reaches [`client.interceptors.error`](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/configure-requests#add-interceptors). An abort whose reason is not an `Error`, such as `abort('canceled')`, skips it.
20
+
21
+ ## Catch a ResponseError
22
+
23
+ Narrow with `ResponseError.is(error)` instead of `instanceof`, because each generated package bundles its own `ResponseError` class:
24
+
25
+ ```typescript
26
+ import { getPetById } from './gen/clients/getPetById'
27
+ import { ResponseError } from './gen/.kubb/client'
28
+
29
+ try {
30
+ const { data } = await getPetById({ path: { petId: 1 } })
31
+ } catch (error) {
32
+ if (ResponseError.is(error)) console.error(error.status, error.data) // 404, the parsed error body
33
+ }
34
+ ```
35
+
36
+ ```typescript
37
+ class ResponseError extends Error {
38
+ data: TError // the parsed error body
39
+ status: number
40
+ statusText: string
41
+ contentType: string | undefined
42
+ headers: Headers // such as error.headers.get('Retry-After')
43
+ request: Request
44
+ response: Response
45
+ }
46
+ ```
47
+
48
+ The `message` leaves out the query string: `GET https://api.example.com/pets/1 failed with status 404 Not Found`. `request` and `response` keep the full URL, so redact them before you log the whole error.
49
+
50
+ > [!NOTE]
51
+ > The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype). With the default `bigint`, an `int64` id takes `1n`.
52
+
53
+ ## Narrow a thrown error by status
54
+
55
+ `isResponseError<Responses>(error)` narrows a caught error to one operation's `ResponseError`. A check on `status` then narrows `data`. For range keys such as `4xx`, see [Status ranges](#status-ranges):
56
+
57
+ ```typescript
58
+ import { isResponseError } from './gen/.kubb/client'
59
+ import type { GetPetByIdResponses } from './gen/types/GetPetById'
60
+
61
+ try {
62
+ await getPetById({ path: { petId: 7 } })
63
+ } catch (error) {
64
+ if (isResponseError<GetPetByIdResponses>(error) && error.status === 404) {
65
+ console.error(error.data) // GetPetById404
66
+ }
67
+ }
68
+ ```
69
+
70
+ > [!WARNING]
71
+ > The type argument is not checked at runtime, so keep the `try` around one operation.
72
+
73
+ ## Return the error instead
74
+
75
+ With `throwOnError: false`, the call resolves for every status. `data` is set on success and `error` on failure, and a check on `status` narrows both:
76
+
77
+ ```typescript
78
+ const result = await getPetById({ path: { petId: 1 }, throwOnError: false })
79
+
80
+ if (result.error !== undefined) console.error(result.status, result.error)
81
+ else console.info(result.data)
82
+ ```
83
+
84
+ See [Empty error bodies and default responses](#empty-error-bodies-and-default-responses).
85
+
86
+ ## Set the generated default
87
+
88
+ [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#throwonerrordefault) on the plugin sets what a call does when it leaves `throwOnError` out. `client.setConfig({ throwOnError })` does not change it:
89
+
90
+ ```typescript
91
+ pluginKy({ throwOnErrorDefault: false })
92
+
93
+ const list = await searchPets({ query: { status: 'available' } }) // resolves with an error result
94
+ const pet = await getPetById({ path: { petId: 1 }, throwOnError: true }) // throws
95
+ ```
96
+
97
+ ## Validation failures
98
+
99
+ With [`validator`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#validator) on, a body that does not match its Zod schema throws a `ParseError` with the schema's `issues`:
100
+
101
+ ```typescript
102
+ import { ParseError } from './gen/.kubb/standardSchema'
103
+
104
+ try {
105
+ await getPetById({ path: { petId: 1 } })
106
+ } catch (error) {
107
+ if (error instanceof ParseError) console.error(error.issues) // [{ message, path }]
108
+ }
109
+ ```
110
+
111
+ To recover, pass `onValidationError` on the call or the client. Return `{ value }` to use that value, or nothing to throw the `ParseError`:
112
+
113
+ ```typescript
114
+ client.setConfig({
115
+ onValidationError: (error, { direction, source, value }) => {
116
+ console.warn(direction, source, error.issues)
117
+ return { value }
118
+ },
119
+ })
120
+ ```
121
+
122
+ For which schema checks an error body, see [Error body validation](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/serialization#error-body-validation).
123
+
124
+ ## Turn validation off at runtime
125
+
126
+ `validator` decides at generation time which schemas a call carries. `validate` skips them at runtime, for example in production or in tests with partial fixtures:
127
+
128
+ ```typescript
129
+ client.setConfig({ validate: import.meta.env.DEV })
130
+ client.setConfig({ validate: { response: false } }) // skip one direction
131
+ ```
132
+
133
+ The default is `true`. The object form skips each direction set to `false`: `request` (the body), `params`, `response`, or `error`. A per-call `validate` overrides the client.
134
+
135
+ ## Less common cases
136
+
137
+ ### Status ranges
138
+
139
+ When an operation declares a range key such as `4xx`, the range covers its statuses that have no entry of their own, and `default` covers the rest.
140
+
141
+ ### Empty error bodies and default responses
142
+
143
+ When a failed call has an empty body, `error` is `{ status, statusText }`.
144
+
145
+ When the operation declares a `default` response, a check on `status` does not narrow `data` and `error`, because a `default` status can be any number. To get the success body with the default `returnType: 'full'`, call `.unwrap()`, which turns `error` into a rejection. With `returnType: 'data'`, the call returns a plain promise without `.unwrap()`.
146
+
147
+ ### Where the `throwOnError` default comes from
148
+
149
+ When you set `client.setConfig({ throwOnError })`, generated calls ignore it, because each generated function passes its own value: the call's `throwOnError`, or else [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#throwonerrordefault). That value is also the default of the function's `ThrowOnError` type parameter.
150
+
151
+ ### Read headers with `returnType: 'data'`
152
+
153
+ When the plugin sets [`returnType: 'data'`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#returntype), a call resolves to the success body alone. To read a header such as `ETag`, pass `throwOnError: false` and call `result.headers.get('etag')`. For a stream call, see [Event IDs when you resume](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/server-sent-events#event-ids-when-you-resume).
154
+
155
+ The query plugins and `@kubb/plugin-mcp` read `returnType` too, including a per-operation value from [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override).
@@ -0,0 +1,226 @@
1
+ # Configure serialization
2
+
3
+ Configure how the generated Ky client serializes OpenAPI parameters and encodes request and response bodies by media type.
4
+
5
+ Each generated call carries its parameter styles and content types, so most specs need no setup.
6
+
7
+ ## Parameter styles
8
+
9
+ A parameter without `style` or `explode` in the spec uses its location's default.
10
+
11
+ ::tabs
12
+
13
+ :::tabs-item{label="Query"}
14
+
15
+ For a query parameter named `id`:
16
+
17
+ | Style | `explode` | Input | Sent |
18
+ | ---------------- | --------- | ---------------- | ---------------- |
19
+ | `form` (default) | `true` | `[3, 4, 5]` | `id=3&id=4&id=5` |
20
+ | `form` | `false` | `[3, 4, 5]` | `id=3,4,5` |
21
+ | `form` (default) | `true` | `{ a: 1, b: 2 }` | `a=1&b=2` |
22
+ | `spaceDelimited` | `false` | `[3, 4, 5]` | `id=3%204%205` |
23
+ | `pipeDelimited` | `false` | `[3, 4, 5]` | `id=3%7C4%7C5` |
24
+ | `deepObject` | n/a | `{ a: 1 }` | `id%5Ba%5D=1` |
25
+
26
+ `spaceDelimited` and `pipeDelimited` default `explode` to `false`. A space in a value goes out as `%20`.
27
+
28
+ :::
29
+
30
+ :::tabs-item{label="Path"}
31
+
32
+ For a path parameter named `id`, the segment that replaces `{id}`:
33
+
34
+ | Style | `explode` | Input | Sent |
35
+ | ------------------ | --------- | ---------------- | ----------------- |
36
+ | `simple` (default) | `false` | `[3, 4, 5]` | `3,4,5` |
37
+ | `simple` (default) | `false` | `{ x: 1, y: 2 }` | `x,1,y,2` |
38
+ | `label` | `true` | `[3, 4, 5]` | `.3.4.5` |
39
+ | `matrix` | `true` | `[3, 4, 5]` | `;id=3;id=4;id=5` |
40
+
41
+ :::
42
+
43
+ :::tabs-item{label="Header"}
44
+
45
+ Headers always use the `simple` style. Only `explode` varies, and values are sent as they are.
46
+
47
+ | `explode` | Input | Sent |
48
+ | ----------------- | ------------------------------- | ---------------------- |
49
+ | `false` (default) | `'X-Ids': [3, 4]` | `X-Ids: 3,4` |
50
+ | `false` (default) | `'X-Filter': { role: 'admin' }` | `X-Filter: role,admin` |
51
+ | `true` | `'X-Filter': { role: 'admin' }` | `X-Filter: role=admin` |
52
+
53
+ :::
54
+
55
+ :::tabs-item{label="Cookie"}
56
+
57
+ Cookies use the `form` style, or the OpenAPI 3.2 `cookie` style, joined into one `Cookie` header.
58
+
59
+ | Style | `explode` | Input | Sent |
60
+ | ---------------- | --------- | --------------------------------- | ---------------------- |
61
+ | `form` (default) | `false` | `{ session: 'abc', ids: [1, 2] }` | `session=abc; ids=1,2` |
62
+ | `form` | `true` | `{ ids: [1, 2] }` | `ids=1; ids=2` |
63
+ | `cookie` | `true` | `{ ids: [1, 2] }` | `ids=1; ids=2` |
64
+
65
+ `form` percent-encodes values. `cookie` sends them as they are, and a value it cannot send, such as one with `;`, throws a `TypeError`.
66
+
67
+ :::
68
+
69
+ ::
70
+
71
+ For `allowReserved` and `explode: true` on delimited styles, see [Delimited styles and allowReserved](#delimited-styles-and-allowreserved).
72
+
73
+ ## Override parameter serialization
74
+
75
+ Set a `serializer` key on the client to replace that serializer for every call, or on one call. The keys are `query`, `path`, `header`, and `cookie`, and the other keys keep theirs:
76
+
77
+ ```typescript
78
+ import qs from 'qs'
79
+ import { client } from './gen/.kubb/client'
80
+
81
+ client.setConfig({
82
+ serializer: { query: (params) => qs.stringify(params, { arrayFormat: 'brackets' }) },
83
+ })
84
+ ```
85
+
86
+ Kubb writes only the serializers a spec needs. See [Serializer files](#serializer-files) for which files it writes.
87
+
88
+ ## Built-in media types
89
+
90
+ | Keys | Encodes | Decodes |
91
+ | ---------------------------------------------------------------------------------------- | ------------------------------------------------- | ------------------------------------------ |
92
+ | `application/json`, `application/*+json`, `text/json` | JSON | JSON |
93
+ | `text/*` | a string as is | text |
94
+ | `multipart/form-data`, `application/x-www-form-urlencoded` | `FormData` or `URLSearchParams` from an object | `FormData` |
95
+ | `application/octet-stream`, `application/pdf`, `image/*`, `audio/*`, `video/*` | a `Blob` as is | `Blob` |
96
+ | `text/event-stream`, `application/jsonl`, `application/x-ndjson`, `application/json-seq` | | text, or item by item with `client.stream` |
97
+ | `*/*` | JSON for objects, strings and binary bodies as is | JSON, or text when the body is not JSON |
98
+
99
+ The runtime matches the lower-cased type without its parameters: the exact type, then a suffix such as `application/*+json`, then a wildcard such as `text/*`, then `*/*`. Write your own keys in lower case.
100
+
101
+ ## Encode request bodies
102
+
103
+ For an operation with several request content types, set `contentType` on the call. A body without a content type goes out as `application/json`, unless it is already encoded.
104
+
105
+ - An encoded body passes every built-in media type as is: `FormData`, `URLSearchParams`, `Blob`, `ArrayBuffer`, typed arrays, streams, and strings. Under a JSON media type, a string is JSON-encoded.
106
+ - For a `FormData` body, the runtime removes `Content-Type`, so the transport sets it with the multipart boundary.
107
+ - XML, YAML, and CSV have no built-in encoder, so an object under one throws a `TypeError`. Pass the encoded string, cast to the body type (`body: xml as unknown as AddPetBodyXml`), or add a media type.
108
+
109
+ For `bigint` bodies, see [`bigint` request bodies](#bigint-request-bodies).
110
+
111
+ ## Add a media type
112
+
113
+ Register a handler under its media type in `mediaTypes`. `encode` gets the body and a context with the full `contentType`, and returns what `fetch` can send. `decode` gets the `Response`, so a binary format can read bytes:
114
+
115
+ ```typescript
116
+ import { XMLBuilder, XMLParser } from 'fast-xml-parser'
117
+ import { client } from './gen/.kubb/client'
118
+
119
+ client.setConfig({
120
+ mediaTypes: {
121
+ 'application/xml': {
122
+ encode: (body) => new XMLBuilder().build(body),
123
+ decode: async (response) => new XMLParser().parse(await response.text()),
124
+ },
125
+ },
126
+ })
127
+ ```
128
+
129
+ Handlers merge per key over the built-ins. For the merge order, see [Media type merge order](#media-type-merge-order). A streaming format adds `stream`, which reads a 2xx body item by item, and the runtime validates each item:
130
+
131
+ ```typescript
132
+ client.setConfig({
133
+ mediaTypes: { 'multipart/mixed': { stream: (body, { contentType }) => readParts(body, boundaryOf(contentType)) } },
134
+ })
135
+ ```
136
+
137
+ ## Decode responses
138
+
139
+ The runtime decodes each body by the response `Content-Type`. A `switch (result.contentType)` narrows `data` for an operation that returns several media types.
140
+
141
+ | Response | `data` |
142
+ | ---------------------------------------------------- | ---------------------------------------------------------------------------------- |
143
+ | 204, 205, or 304, a `HEAD` request, or an empty body | `undefined` |
144
+ | Invalid JSON under a JSON media type | Throws a `ParseError`. Catch it, or register a lenient `application/json` handler. |
145
+ | 2xx with `parseAs` set on the call | Read as `'json'`, `'text'`, `'blob'`, `'arrayBuffer'`, or `'stream'`. |
146
+
147
+ For a 2xx without a `Content-Type`, see [Default content types](#default-content-types). For binary downloads and vendor types, see [Binary and vendor responses](#binary-and-vendor-responses).
148
+
149
+ XML, YAML, and CSV responses are typed `string`, even with an object schema. A media type you register changes the value but not the type, so cast `data`:
150
+
151
+ ```typescript
152
+ const result = await getPetById({ path: { petId: 1 }, contentType: { response: 'application/xml' } })
153
+ if (result.contentType === 'application/xml') {
154
+ const pet = result.data as unknown as Pet
155
+ }
156
+ ```
157
+
158
+ > [!NOTE]
159
+ > With the adapter's default [`integerType: 'bigint'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype), an `int64` field is typed `bigint`, but `JSON.parse` returns a `number`. Set `integerType: 'number'`, or turn on [`validator: 'zod'`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#validator), which converts the field. `JSON.parse` loses precision above `Number.MAX_SAFE_INTEGER` either way, so declare an exact 64-bit ID as a string.
160
+
161
+ Next, [Server-sent events](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/server-sent-events) covers the stream media types and `client.stream`.
162
+
163
+ ## Less common cases
164
+
165
+ ### Delimited styles and allowReserved
166
+
167
+ When a [query parameter](#parameter-styles) uses `spaceDelimited` or `pipeDelimited`, or sets `allowReserved`:
168
+
169
+ - `spaceDelimited` and `pipeDelimited` default `explode` to `false`. With `explode: true`, they repeat the key, like `form`.
170
+ - With `allowReserved`, reserved characters stay as they are, except `#`, `&`, and `+`.
171
+
172
+ ### Serializer files
173
+
174
+ When you look for a serializer in `.kubb/serializers/`, Kubb writes only the ones the spec needs and registers them in `.kubb/config.ts`. Set a key from the table to replace one, as [Override parameter serialization](#override-parameter-serialization) shows.
175
+
176
+ | Key in `serializer` | File | Written for |
177
+ | ------------------- | -------------------------------------------------------------- | ------------------------------ |
178
+ | `query` | `query.ts`, or `queryStyles.ts` with a styled query parameter | every spec |
179
+ | `path` | `path.ts`, plus `pathStyles.ts` with a `label` or `matrix` one | every spec |
180
+ | `header` | `headers.ts` | a spec with a header parameter |
181
+ | `cookie` | `cookies.ts` | a spec with a cookie parameter |
182
+
183
+ A call that needs a serializer the spec did not register throws a `TypeError` that names it, such as `serializer.cookie`. Without `serializer.header`, an array or object header value goes out as JSON.
184
+
185
+ ### Form and stream media types
186
+
187
+ When a form or stream type from [Built-in media types](#built-in-media-types) has no handler, the spec does not use it:
188
+
189
+ - `.kubb/config.ts` registers each form type only when the spec has a body of that type, from `.kubb/mediaTypes/formData.ts` and `.kubb/mediaTypes/urlencoded.ts`.
190
+ - It registers the stream types, `streamMediaTypes` from `.kubb/sse.ts`, only when the spec streams.
191
+ - `.kubb/client.ts` passes that config to `setConfig`.
192
+
193
+ To send a type the spec does not declare, register a handler, as [Add a media type](#add-a-media-type) shows.
194
+
195
+ ### Default content types
196
+
197
+ When a call sets no `contentType`:
198
+
199
+ - An operation with one request content type has it built in. For one with several, set `contentType` on the call.
200
+ - A 2xx response without a `Content-Type` decodes as the call's `contentType.response`, then as `*/*`.
201
+
202
+ ### `bigint` request bodies
203
+
204
+ When a request body holds a `bigint`, it goes out as a JSON number. A value outside the safe-integer range throws a `TypeError` instead of losing precision, so register a media type to send it another way.
205
+
206
+ ### Media type merge order
207
+
208
+ When you register a handler for a type that already has one, handlers merge per key over the built-ins and over earlier `setConfig` calls. A handler passed on one call merges over the client's. An entry with only `decode` still encodes through the next match, such as `*/*`.
209
+
210
+ ### Binary and vendor responses
211
+
212
+ When an operation's success content is only binary, Kubb sets `parseAs: 'blob'` on it, so `data` is a `Blob` whatever its media type. The generated types follow what the built-in media types return. A vendor type such as `application/vnd.github.object` keeps its schema type.
213
+
214
+ ### Parameter validation
215
+
216
+ When [`validator`](https://kubb.dev/extensions/kubb-labs/plugin-ky/options#validator) checks `params`, the call sends what each `<operation>PathSchema`, `QuerySchema`, `HeadersSchema`, or `CookiesSchema` returns:
217
+
218
+ - A codec param such as a `Date` goes out in its wire form.
219
+ - Path and query keys the spec does not declare are stripped, such as a cache-buster.
220
+ - Undeclared headers pass through, and declared ones match in any casing. Client-level `headers` are checked too, and `auth` values are not.
221
+
222
+ With codecs, pair `request` and `params` with [`pluginZod({ inferred: 'codec' })`](https://kubb.dev/extensions/kubb-labs/plugin-zod/options#inferred), so the request types accept domain values such as a `Date`. To skip the checks, [turn validation off at runtime](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/error-handling#turn-validation-off-at-runtime).
223
+
224
+ ### Error body validation
225
+
226
+ When `validator` is on and a non-2xx response has a body, the runtime checks it against the schema of its status, then its range such as `5xx`, then `default`. A status the document leaves out keeps its body unchecked. An error body that fails its schema throws a `ParseError` instead of the `ResponseError`, also with `throwOnError: false`. To recover, see [Validation failures](https://kubb.dev/extensions/kubb-labs/plugin-ky/guides/error-handling#validation-failures).