@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.
- package/dist/index.cjs +11 -1771
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -238
- package/dist/index.d.ts +3 -238
- package/dist/index.js +12 -1749
- package/dist/index.js.map +1 -1
- package/dist/templates/client.d.ts +54 -2
- package/docs/guides/authentication.md +29 -2
- package/docs/guides/base-url.md +44 -2
- package/docs/guides/error-handling.md +31 -8
- package/docs/guides/interceptors.md +54 -19
- package/docs/guides/migrate-to-v6.md +287 -0
- package/docs/guides/serialization.md +117 -63
- package/docs/guides/server-sent-events.md +130 -29
- package/docs/guides/transport.md +17 -21
- package/docs/options.md +14 -4
- package/docs/overview.md +1 -1
- package/kubb-extension.json +1 -1
- package/package.json +8 -10
- package/src/index.ts +0 -1
- package/src/plugin.ts +7 -74
- package/src/types.ts +2 -2
- package/templates/client.ts +133 -244
- package/dist/client-B1OgL91n.d.ts +0 -81
- package/dist/core-D6FAGTsL.d.ts +0 -2
- package/dist/templates/axios.d.ts +0 -6
- package/dist/templates/core.d.ts +0 -2
- package/dist/templates/serializers.d.ts +0 -1
- package/dist/templates/standardSchema.d.ts +0 -1
- package/src/generators/clientGenerator.tsx +0 -10
- package/src/templates.ts +0 -16
- package/templates/axios.ts +0 -2
- package/templates/core.ts +0 -2
- package/templates/serializers.ts +0 -2
- package/templates/standardSchema.ts +0 -2
|
@@ -1,12 +1,57 @@
|
|
|
1
1
|
# Configure serialization
|
|
2
2
|
|
|
3
|
-
The generated client encodes parameters
|
|
3
|
+
The generated client encodes parameters by their OpenAPI `style` and `explode`, and encodes and decodes bodies by their media type. Each generated operation carries its parameter styles and content types, so most requests need no extra setup.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Parameter styles
|
|
6
|
+
|
|
7
|
+
A parameter without `style` or `explode` in the spec uses the default for its location.
|
|
8
|
+
|
|
9
|
+
### Query
|
|
10
|
+
|
|
11
|
+
Query parameters default to the `form` style. Arrays explode into repeated keys unless the spec
|
|
12
|
+
says otherwise, and `spaceDelimited`, `pipeDelimited`, and `deepObject` change how arrays and
|
|
13
|
+
objects collapse.
|
|
14
|
+
|
|
15
|
+
| Style | `explode` | Input | Result |
|
|
16
|
+
| ---------------- | --------- | ------------------- | ---------------- |
|
|
17
|
+
| `form` (default) | `true` | `{ id: [3, 4, 5] }` | `id=3&id=4&id=5` |
|
|
18
|
+
| `form` | `false` | `{ id: [3, 4, 5] }` | `id=3,4,5` |
|
|
19
|
+
| `spaceDelimited` | `false` | `{ id: [3, 4, 5] }` | `id=3%204%205` |
|
|
20
|
+
| `pipeDelimited` | `false` | `{ id: [3, 4, 5] }` | `id=3\|4\|5` |
|
|
21
|
+
| `deepObject` | `n/a` | `{ a: { b: 1 } }` | `a%5Bb%5D=1` |
|
|
22
|
+
|
|
23
|
+
With `explode: true`, `spaceDelimited` and `pipeDelimited` fall back to repeated keys like `form`,
|
|
24
|
+
so the delimiter only shows with `explode: false`.
|
|
25
|
+
|
|
26
|
+
### Path
|
|
27
|
+
|
|
28
|
+
Path parameters default to the `simple` style, which emits the bare value. `label` prefixes a
|
|
29
|
+
`.` and `matrix` prefixes a `;name=` segment. The results below are the serialized segment for a
|
|
30
|
+
parameter named `id`.
|
|
31
|
+
|
|
32
|
+
| Style | `explode` | Input | Result |
|
|
33
|
+
| ------------------ | --------- | ---------------- | ----------------- |
|
|
34
|
+
| `simple` (default) | `false` | `[3, 4, 5]` | `3,4,5` |
|
|
35
|
+
| `label` | `true` | `[3, 4, 5]` | `.3.4.5` |
|
|
36
|
+
| `matrix` | `true` | `[3, 4, 5]` | `;id=3;id=4;id=5` |
|
|
37
|
+
| `simple` | `false` | `{ x: 1, y: 2 }` | `x,1,y,2` |
|
|
6
38
|
|
|
7
|
-
|
|
39
|
+
### Header and cookie
|
|
8
40
|
|
|
9
|
-
|
|
41
|
+
Header parameters use the `simple` style and cookie parameters use the `form` style. Both fix the
|
|
42
|
+
style and only let `explode` vary, so the metadata for these locations carries `explode` alone.
|
|
43
|
+
Header values are sent as-is, and cookie values are URL-encoded into a single `Cookie` header.
|
|
44
|
+
|
|
45
|
+
| Location | `explode` | Input | Result |
|
|
46
|
+
| -------- | --------- | --------------------------------- | ---------------------- |
|
|
47
|
+
| header | `false` | `[3, 4]` | `X-Ids: 3,4` |
|
|
48
|
+
| header | `true` | `{ role: 'admin' }` | `X-Filter: role=admin` |
|
|
49
|
+
| cookie | `false` | `{ session: 'abc', ids: [1, 2] }` | `session=abc; ids=1,2` |
|
|
50
|
+
| cookie | `true` | `{ ids: [1, 2] }` | `ids=1; ids=2` |
|
|
51
|
+
|
|
52
|
+
## Override parameter serialization
|
|
53
|
+
|
|
54
|
+
To replace these defaults, override `serializer.query` or `serializer.path` on the client. Omitted functions keep their defaults:
|
|
10
55
|
|
|
11
56
|
```typescript
|
|
12
57
|
import { client } from './gen/.kubb/client'
|
|
@@ -19,89 +64,102 @@ client.setConfig({
|
|
|
19
64
|
})
|
|
20
65
|
```
|
|
21
66
|
|
|
22
|
-
A serializer set this way runs for every call
|
|
23
|
-
|
|
67
|
+
A serializer set this way runs for every call. Pass `serializer` on a single call to override only that request.
|
|
68
|
+
|
|
69
|
+
Kubb writes each serializer a spec needs into `.kubb/serializers/` and lists it in `.kubb/config.ts`, which `.kubb/client.ts` passes to `setConfig`. The core has no serializer of its own.
|
|
70
|
+
|
|
71
|
+
| Key in `serializer` | File | Written for |
|
|
72
|
+
| ------------------- | ------------------------------------------------------------------------------------ | ------------------------------ |
|
|
73
|
+
| `query` | `query.ts`, or `queryStyles.ts` for a spec with a styled query parameter | every spec |
|
|
74
|
+
| `path` | `path.ts`, plus `pathStyles.ts` for a spec with a `label` or `matrix` path parameter | every spec |
|
|
75
|
+
| `header` | `headers.ts` | a spec with a header parameter |
|
|
76
|
+
| `cookie` | `cookies.ts` | a spec with a cookie parameter |
|
|
77
|
+
|
|
78
|
+
A call that needs a serializer the spec did not register throws a `TypeError` that names the key, such as `serializer.cookie`. Set it on the client to send such a call. Without `serializer.header`, an array or object header value is sent as JSON.
|
|
79
|
+
|
|
80
|
+
## Built-in media types
|
|
81
|
+
|
|
82
|
+
| Keys | Encodes | Decodes |
|
|
83
|
+
| ---------------------------------------------------------------------------------------- | ------------------------------------------------- | ------------------------------------------ |
|
|
84
|
+
| `application/json`, `application/*+json`, `text/json` | JSON | JSON |
|
|
85
|
+
| `text/*` | a string | text |
|
|
86
|
+
| `multipart/form-data`, `application/x-www-form-urlencoded` | `FormData` or `URLSearchParams` from an object | `FormData` |
|
|
87
|
+
| `application/octet-stream`, `application/pdf`, `image/*`, `audio/*`, `video/*` | a `Blob` as is | `Blob` |
|
|
88
|
+
| `text/event-stream`, `application/jsonl`, `application/x-ndjson`, `application/json-seq` | | text, or item by item with `client.stream` |
|
|
89
|
+
| `*/*` | JSON for objects, strings and binary bodies as is | JSON, or text when the body is not JSON |
|
|
90
|
+
|
|
91
|
+
`.kubb/client.ts` registers a form media type only when the document has a body of that type, and the stream media types only when it streams. `multipartFormData` is in `.kubb/mediaTypes/formData.ts` and `urlencoded` in `.kubb/mediaTypes/urlencoded.ts`. The stream media types are `streamMediaTypes` in `.kubb/sse.ts`.
|
|
92
|
+
|
|
93
|
+
A key can be a pattern. The runtime lower-cases the type, drops its parameters, and tries the exact type, then a suffix such as `application/*+json`, then a wildcard such as `text/*`, then `*/*`. Write your own keys in lower case.
|
|
24
94
|
|
|
25
95
|
## Encode request bodies
|
|
26
96
|
|
|
27
|
-
|
|
28
|
-
common types: a plain object becomes JSON, `multipart/form-data` becomes `FormData`, and
|
|
29
|
-
`application/x-www-form-urlencoded` becomes `URLSearchParams`. Binary and already-encoded bodies
|
|
30
|
-
(`FormData`, `URLSearchParams`, `Blob`, `ArrayBuffer`, typed arrays, and strings) pass through
|
|
31
|
-
untouched.
|
|
97
|
+
When an operation declares one request content type, Kubb sets it on the generated function, so you pass only the body. For an operation that accepts more than one, set `contentType` on the call. A body without a content type is sent as `application/json`, unless it is already encoded.
|
|
32
98
|
|
|
33
|
-
|
|
34
|
-
so you pass only the body. For an operation that accepts more than one, set `contentType` on the
|
|
35
|
-
call.
|
|
99
|
+
Bodies that are already encoded (`FormData`, `URLSearchParams`, `Blob`, `ArrayBuffer`, typed arrays, streams, and strings) pass through every built-in media type as they are. A string under a JSON media type is JSON-encoded.
|
|
36
100
|
|
|
37
101
|
> [!NOTE]
|
|
38
|
-
> When the body is `FormData`, the runtime removes any `Content-Type` header so the transport sets
|
|
39
|
-
|
|
40
|
-
|
|
102
|
+
> When the body is `FormData`, the runtime removes any `Content-Type` header so the transport sets it with the multipart boundary.
|
|
103
|
+
|
|
104
|
+
An XML, YAML, or CSV media type has no built-in handler, so an object sent under one throws a `TypeError`. Pass the encoded body as a string, or register a media type. The generated body type is the schema, such as `Pet`, so a string body needs a cast: `body: xml as unknown as AddPetBodyXml`.
|
|
41
105
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
`
|
|
106
|
+
## Add a media type
|
|
107
|
+
|
|
108
|
+
Register a handler under its media type with `mediaTypes`. `encode` gets the body and a context with the full `contentType`, and returns a body axios can send. `decode` gets the `Response`, so a binary format can read bytes:
|
|
45
109
|
|
|
46
110
|
```typescript
|
|
47
111
|
import { client } from './gen/.kubb/client'
|
|
48
|
-
import {
|
|
112
|
+
import { XMLBuilder, XMLParser } from 'fast-xml-parser'
|
|
49
113
|
|
|
50
114
|
client.setConfig({
|
|
51
|
-
|
|
52
|
-
'application/
|
|
115
|
+
mediaTypes: {
|
|
116
|
+
'application/xml': {
|
|
117
|
+
encode: (body) => new XMLBuilder().build(body),
|
|
118
|
+
decode: async (response) => new XMLParser().parse(await response.text()),
|
|
119
|
+
},
|
|
53
120
|
},
|
|
54
121
|
})
|
|
55
122
|
```
|
|
56
123
|
|
|
57
|
-
|
|
124
|
+
Handlers merge per key over the built-ins, over earlier `setConfig` calls, and, when passed on a single call, over the client ones. An entry with only `decode` still encodes through the next match, such as `*/*`.
|
|
58
125
|
|
|
59
|
-
|
|
60
|
-
stays a string, and a binary type becomes a `Blob`. The negotiated media type is on the result as
|
|
61
|
-
`contentType`, so a `switch (result.contentType)` narrows `data` for an operation that returns
|
|
62
|
-
more than one.
|
|
63
|
-
|
|
64
|
-
When that success response declares several content types that do not share one parser, the
|
|
65
|
-
generated call sets `responseType` to a map from content type to parser, for example
|
|
66
|
-
`{ 'audio/mpeg': 'blob', 'text/event-stream': 'stream' }`. Axios reads the raw body, then the
|
|
67
|
-
runtime matches the response `Content-Type` against the map, including a `type/*` wildcard,
|
|
68
|
-
before the media-type heuristic. A schema with `format: binary` is a blob even when the media
|
|
69
|
-
type is not a well-known binary type.
|
|
70
|
-
|
|
71
|
-
Axios response interceptors see the decoded body: parsed JSON, a string, or a `Blob`. A map with
|
|
72
|
-
a `'stream'` entry reads the body as a stream, the same way as `responseType: 'stream'`, so an
|
|
73
|
-
event stream arrives as it is sent. Interceptors then see the stream, and the runtime reads any
|
|
74
|
-
other content type from it afterwards.
|
|
75
|
-
|
|
76
|
-
To decode a media type the runtime does not handle, register a codec's `deserialize` for it.
|
|
77
|
-
`deserialize` receives the raw body and the content type and returns the parsed value. It runs
|
|
78
|
-
before validation, so the schema checks the parsed value:
|
|
126
|
+
A streaming format adds `stream`, which reads the 2xx body item by item. The runtime validates each item:
|
|
79
127
|
|
|
80
128
|
```typescript
|
|
81
|
-
import { client } from './gen/.kubb/client'
|
|
82
|
-
|
|
83
129
|
client.setConfig({
|
|
84
|
-
|
|
85
|
-
'
|
|
130
|
+
mediaTypes: {
|
|
131
|
+
'multipart/mixed': { stream: (body, { contentType }) => readParts(body, boundaryOf(contentType)) },
|
|
86
132
|
},
|
|
87
133
|
})
|
|
88
134
|
```
|
|
89
135
|
|
|
90
|
-
|
|
91
|
-
|
|
136
|
+
## Decode responses
|
|
137
|
+
|
|
138
|
+
The runtime decodes each body by the response `Content-Type`, after axios reads it as bytes. Native axios response interceptors on `getAxiosInstance()` see those bytes, so use `client.interceptors.response` to see the decoded body. The media type is on the result as `contentType`, so a `switch (result.contentType)` narrows `data` for an operation that returns more than one.
|
|
92
139
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
140
|
+
- A 2xx response without a `Content-Type` is decoded as the media type the call asked for in `contentType.response`, then as `*/*`.
|
|
141
|
+
- A 204, 205, or 304 response, a `HEAD` request, and an empty body give `data: undefined`.
|
|
142
|
+
- Invalid JSON under a JSON media type throws a `ParseError`. Catch it, or register a lenient `application/json` handler.
|
|
143
|
+
|
|
144
|
+
To skip the lookup for one call, set `parseAs` to `'json'`, `'text'`, `'blob'`, `'arrayBuffer'`, or `'stream'`. It applies to a 2xx body only. Kubb sets `parseAs: 'blob'` on an operation with only binary success content:
|
|
96
145
|
|
|
97
146
|
```typescript
|
|
98
|
-
const { data } = await
|
|
99
|
-
// data is a Blob even when the server leaves Content-Type unset
|
|
147
|
+
const { data } = await getReport({ path: { id: '123' }, parseAs: 'text' })
|
|
100
148
|
```
|
|
101
149
|
|
|
102
|
-
|
|
150
|
+
The generated types follow what the built-in media types return. A response read as text, such as `application/xml`, `application/yaml`, or `text/csv`, is typed `string`, even when the document gives it an object schema. A vendor type such as `application/vnd.github.object` keeps its schema type, because the client parses its JSON body. A media type you register changes the value but not that type, so narrow or cast `data` to what it returns:
|
|
103
151
|
|
|
104
|
-
|
|
152
|
+
```typescript
|
|
153
|
+
const result = await getPetById({ path: { petId: 1 }, contentType: { response: 'application/xml' } })
|
|
154
|
+
if (result.contentType === 'application/xml') {
|
|
155
|
+
const pet = result.data as unknown as Pet
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
[Server-sent events](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/server-sent-events) covers stream media types and `client.stream`.
|
|
160
|
+
|
|
161
|
+
> [!NOTE]
|
|
162
|
+
> With the adapter's default [`integerType: 'bigint'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype), a `format: int64` field is typed `bigint`, but `JSON.parse` returns a `number`. Set `integerType: 'number'` on `adapterOas`, or turn on [`validator: 'zod'`](#validate-responses), which converts the field to `bigint`. Either way, `JSON.parse` loses precision above `Number.MAX_SAFE_INTEGER`, so declare an exact 64-bit ID as a string in the document.
|
|
105
163
|
|
|
106
164
|
## Validate responses
|
|
107
165
|
|
|
@@ -113,14 +171,10 @@ import { pluginAxios } from '@kubb/plugin-axios'
|
|
|
113
171
|
pluginAxios({ validator: 'zod' })
|
|
114
172
|
```
|
|
115
173
|
|
|
116
|
-
`'zod'` validates the success response body
|
|
117
|
-
throw. Use the object form to opt in per direction, where `request` validates the request
|
|
118
|
-
body before the call goes out:
|
|
174
|
+
`'zod'` validates the success response body and the error body. Use the object form to opt in per direction, where `request` validates the request body before the call goes out:
|
|
119
175
|
|
|
120
176
|
```typescript
|
|
121
177
|
pluginAxios({ validator: { request: 'zod', response: 'zod' } })
|
|
122
178
|
```
|
|
123
179
|
|
|
124
|
-
With a validator set, Kubb passes the matching schema to each generated call, and the runtime
|
|
125
|
-
parses the body through it. A body that does not match throws a `ParseError` with the schema's
|
|
126
|
-
`issues`.
|
|
180
|
+
With a validator set, Kubb passes the matching schema to each generated call, and the runtime parses the decoded body through it. A body that does not match throws a `ParseError` with the schema's `issues`.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# Server-sent events
|
|
2
2
|
|
|
3
|
-
An operation that returns `text/event-stream` gives you a typed stream of events instead of a `RequestResult`. In the browser, stream calls use the axios fetch adapter, because the default XHR adapter buffers the whole body. An `adapter` set on the call or on `
|
|
3
|
+
An operation that returns `text/event-stream` gives you a typed stream of events instead of a `RequestResult`. In the browser, stream calls use the axios fetch adapter, because the default XHR adapter buffers the whole body. An `adapter` set on the call or on `getAxiosInstance()` is kept, and in Node the http adapter streams with its proxy and agent settings. Kubb takes the event types from the OpenAPI document. The runtime in `.kubb/sse.ts` parses the stream the way the WHATWG event stream specification does.
|
|
4
4
|
|
|
5
5
|
Each event on the wire has up to four fields, and a blank line ends it:
|
|
6
6
|
|
|
7
7
|
| Field | Meaning |
|
|
8
8
|
| ------- | -------------------------------------------------------------------------------- |
|
|
9
9
|
| `event` | The event name. `message` when the server sends none. |
|
|
10
|
-
| `data` | The payload. Parsed as JSON
|
|
10
|
+
| `data` | The payload. Parsed as JSON when it is valid JSON, and kept as text otherwise. |
|
|
11
11
|
| `id` | The last event ID. It carries over to later events and resumes a dropped stream. |
|
|
12
12
|
| `retry` | The reconnect delay in milliseconds. |
|
|
13
13
|
|
|
@@ -33,7 +33,7 @@ For one payload on every event, such as a feed of pet changes. The item declares
|
|
|
33
33
|
|
|
34
34
|
### Describe it
|
|
35
35
|
|
|
36
|
-
In OpenAPI 3.2, put one `oneOf` member per event name on `itemSchema`, with a `const` on `event`.
|
|
36
|
+
In OpenAPI 3.2, put one `oneOf` member per event name on `itemSchema`, with a `const` on `event`. Point `data` at the payload schema with `$ref`. A `data` string described with `contentMediaType: application/json` and `contentSchema` is typed and parsed as that schema too:
|
|
37
37
|
|
|
38
38
|
```yaml
|
|
39
39
|
/chat:
|
|
@@ -53,13 +53,16 @@ In OpenAPI 3.2, put one `oneOf` member per event name on `itemSchema`, with a `c
|
|
|
53
53
|
id: { type: string }
|
|
54
54
|
retry: { type: integer, minimum: 0 }
|
|
55
55
|
oneOf:
|
|
56
|
-
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
-
|
|
62
|
-
|
|
56
|
+
- type: object
|
|
57
|
+
required: [event, data]
|
|
58
|
+
properties:
|
|
59
|
+
event: { type: string, const: message_delta }
|
|
60
|
+
data: { $ref: '#/components/schemas/MessageDelta' }
|
|
61
|
+
- type: object
|
|
62
|
+
required: [event]
|
|
63
|
+
properties:
|
|
64
|
+
event: { type: string, const: ping }
|
|
65
|
+
data: { type: string }
|
|
63
66
|
```
|
|
64
67
|
|
|
65
68
|
In OpenAPI 3.0 and 3.1, put the same `oneOf` on `schema`, with a `discriminator` on `event`. Kubb reads `schema` as one event.
|
|
@@ -173,16 +176,63 @@ for await (const { data } of stream) {
|
|
|
173
176
|
}
|
|
174
177
|
```
|
|
175
178
|
|
|
179
|
+
## JSON Lines
|
|
180
|
+
|
|
181
|
+
An operation whose only success content type is a JSON sequence, such as `application/jsonl`, `application/x-ndjson`, or `application/json-seq`, streams one item per line. Each line is parsed as JSON, so the loop gets each item as soon as its line arrives instead of waiting for the whole body. An `application/json-seq` record must fit on one line; a record that spans several lines fails to parse.
|
|
182
|
+
|
|
183
|
+
### Describe it
|
|
184
|
+
|
|
185
|
+
Point `itemSchema` at the schema of one line:
|
|
186
|
+
|
|
187
|
+
```yaml
|
|
188
|
+
/logs:
|
|
189
|
+
get:
|
|
190
|
+
operationId: streamLogs
|
|
191
|
+
responses:
|
|
192
|
+
'200':
|
|
193
|
+
description: One LogEntry per line
|
|
194
|
+
content:
|
|
195
|
+
application/jsonl:
|
|
196
|
+
itemSchema:
|
|
197
|
+
$ref: '#/components/schemas/LogEntry'
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
In OpenAPI 3.0 and 3.1, `schema` on one of these media types describes one line.
|
|
201
|
+
|
|
202
|
+
### The stream
|
|
203
|
+
|
|
204
|
+
```text
|
|
205
|
+
{"level": "info", "message": "started"}
|
|
206
|
+
{"level": "warn", "message": "slow"}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
The call asks for the declared media type in `Accept`. A line may end with CRLF, CR, or LF, blank lines are skipped, and a last line without a line break still counts. A line that is not valid JSON throws a `SyntaxError` from the loop.
|
|
210
|
+
|
|
211
|
+
### Use it
|
|
212
|
+
|
|
213
|
+
Each item is a `LogEntry`, with no event wrapper:
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { streamLogs } from './gen/clients/streamLogs'
|
|
217
|
+
|
|
218
|
+
for await (const entry of await streamLogs()) {
|
|
219
|
+
console.info(entry.level, entry.message) // LogEntry
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`terminator`, `maxEventSize`, and `signal` work per line. `transform` only applies to Server-Sent Events. With `validator: 'zod'`, the validator runs on each line. `lastEventId` stays empty, since JSON Lines has no event IDs.
|
|
224
|
+
|
|
176
225
|
## Stream options
|
|
177
226
|
|
|
178
227
|
Pass these on the call, next to its request params:
|
|
179
228
|
|
|
180
|
-
| Option | What it does
|
|
181
|
-
| -------------- |
|
|
182
|
-
| `terminator` | Ends the stream when `data` equals this value, such as `[DONE]`. Without it, the sentinel reaches your loop.
|
|
183
|
-
| `transform` | Maps each event before validation, for example to camelCase its keys.
|
|
184
|
-
| `maxEventSize` | Largest event in characters. A larger one throws a `RangeError`. Defaults to `16 * 1024 * 1024`. Set `Infinity` to turn it off.
|
|
185
|
-
| `signal` | An `AbortSignal` that ends the request and the loop.
|
|
229
|
+
| Option | What it does |
|
|
230
|
+
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
231
|
+
| `terminator` | Ends the stream when `data` equals this value, such as `[DONE]`. Without it, the sentinel reaches your loop, or fails the `validator` when it does not match the event schema. |
|
|
232
|
+
| `transform` | Maps each event before validation, for example to camelCase its keys. |
|
|
233
|
+
| `maxEventSize` | Largest event in characters. A larger one throws a `RangeError`. Defaults to `16 * 1024 * 1024`. Set `Infinity` to turn it off. |
|
|
234
|
+
| `signal` | An `AbortSignal` that ends the request and the loop. |
|
|
235
|
+
| `eventShape` | What the validator checks: `data` for the payload, `event` for the whole event. Generated calls set it. |
|
|
186
236
|
|
|
187
237
|
To stop reading, `break` out of the loop. The runtime then cancels the reader and releases the connection.
|
|
188
238
|
|
|
@@ -202,6 +252,16 @@ const { stream } = await streamChat({
|
|
|
202
252
|
|
|
203
253
|
Set `validate: false` on the call or the client to skip it. See [Handle errors](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/error-handling) for the validation options.
|
|
204
254
|
|
|
255
|
+
## Read the response headers
|
|
256
|
+
|
|
257
|
+
A stream result carries the response `headers`, as a regular result does. When the response declares headers, such as an `X-Request-ID`, the call returns `StreamResultWithHeaders`, so `headers.get` suggests their names for the narrowed `status`:
|
|
258
|
+
|
|
259
|
+
```typescript
|
|
260
|
+
const result = await streamChat({ body: { prompt: 'Hi' } })
|
|
261
|
+
|
|
262
|
+
console.info(result.headers.get('X-Request-ID'))
|
|
263
|
+
```
|
|
264
|
+
|
|
205
265
|
## Resume after a drop
|
|
206
266
|
|
|
207
267
|
A dropped connection ends the loop with the transport's error. The result's `lastEventId` is the `id` of the last event the server completed, so a new call with a `Last-Event-ID` header continues where the stream stopped. The runtime does not reconnect by itself, because many streams, such as a chat completion, end on purpose, and the retry policy belongs to your app:
|
|
@@ -239,7 +299,7 @@ try {
|
|
|
239
299
|
}
|
|
240
300
|
```
|
|
241
301
|
|
|
242
|
-
With `throwOnError: false`, the call resolves instead of throwing, as a regular call does. The result then carries the `status` and the `error` body, its `data` is `undefined`, and its stream yields nothing. Check `data`
|
|
302
|
+
With `throwOnError: false`, the call resolves instead of throwing, as a regular call does. The result then carries the `status` and the `error` body, its `data` is `undefined`, and its stream yields nothing. Check `data` to tell the two apart. An empty error body sets `error` to `{ status, statusText }`. Checking `status` narrows `error` to the body the document declares for that status:
|
|
243
303
|
|
|
244
304
|
```typescript
|
|
245
305
|
const result = await streamChat({ body, throwOnError: false })
|
|
@@ -253,10 +313,51 @@ As on a regular call, `.unwrap()` resolves to the events. A failed call rejects
|
|
|
253
313
|
for await (const event of await streamChat({ body }).unwrap()) render(event)
|
|
254
314
|
```
|
|
255
315
|
|
|
256
|
-
A stream call that gets a JSON
|
|
316
|
+
A stream call that gets a JSON error body parses it like any other call. A 2xx answer that is not an event stream, such as a JSON body, throws a `TypeError` with the body as its `cause`, and an empty 2xx answer ends as an empty stream. An operation that declares another content type next to `text/event-stream` or a JSON Lines type is a normal call. See [JSON or an event stream](#json-or-an-event-stream).
|
|
257
317
|
|
|
258
318
|
Declare heartbeat and `error` events in the document, so each has a `case` in your `switch`.
|
|
259
319
|
|
|
320
|
+
## JSON or an event stream
|
|
321
|
+
|
|
322
|
+
Some APIs, such as Wikimedia EventStreams, declare the same response as `application/json` and as `text/event-stream`. Kubb generates a normal call for it, which returns a `RequestResult`. The call sends `Accept: text/event-stream`, so the server streams events. To ask for JSON, pass `contentType: { response: 'application/json' }`. Wikimedia answers JSON with an endless JSON Lines body, so also pass `parseAs: 'stream'` and read `result.data` with `parseJsonLines({ stream: result.data })` from `.kubb/client`. Without it, the call waits for a body that never ends.
|
|
323
|
+
|
|
324
|
+
Check `contentType` on the result. For `text/event-stream`, `data` is the raw `ReadableStream<Uint8Array>`. Pass it to `parseEventStream` from `.kubb/client` to read the events:
|
|
325
|
+
|
|
326
|
+
```typescript
|
|
327
|
+
import { parseEventStream } from './gen/.kubb/client'
|
|
328
|
+
import { getV2StreamRecentchange } from './gen/clients/getV2StreamRecentchange'
|
|
329
|
+
|
|
330
|
+
const result = await getV2StreamRecentchange({ signal })
|
|
331
|
+
|
|
332
|
+
if (result.contentType === 'text/event-stream') {
|
|
333
|
+
for await (const { data } of parseEventStream(result.data)) render(data)
|
|
334
|
+
} else {
|
|
335
|
+
render(result.data) // the JSON body
|
|
336
|
+
}
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
To get a stream result with `lastEventId`, send the same request with `client.stream`. It throws a `TypeError` when the server answers with JSON:
|
|
340
|
+
|
|
341
|
+
```typescript
|
|
342
|
+
import { client } from './gen/.kubb/client'
|
|
343
|
+
|
|
344
|
+
const result = await client.stream({ method: 'GET', url: '/v2/stream/recentchange', eventShape: 'data', signal })
|
|
345
|
+
for await (const event of result) render(event.data)
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
## Stream with the client
|
|
349
|
+
|
|
350
|
+
`client.stream(config)` runs the same interceptors and transport as `client(config)`. On a 2xx answer, it reads the body item by item and validates each item with `validator.response`. A non-2xx body is decoded whole, so `error` stays a value. Type it with the responses record, `ThrowOnError`, and the item type, which defaults to `ServerSentEvent` around the success body:
|
|
351
|
+
|
|
352
|
+
```typescript
|
|
353
|
+
import { client, type SuccessOf } from './gen/.kubb/client'
|
|
354
|
+
import type { StreamLogsResponses } from './gen/models/StreamLogs'
|
|
355
|
+
|
|
356
|
+
const result = await client.stream<StreamLogsResponses, true, SuccessOf<StreamLogsResponses>>({ method: 'GET', url: '/logs' })
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
To stream another format, register a `stream` handler, as [Configure serialization](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/serialization#add-a-media-type) shows.
|
|
360
|
+
|
|
260
361
|
## Return only the events
|
|
261
362
|
|
|
262
363
|
With `returnType: 'data'` in the plugin options, a stream call returns its events, as a regular call returns only its body:
|
|
@@ -269,16 +370,16 @@ pluginAxios({ returnType: 'data' })
|
|
|
269
370
|
|
|
270
371
|
Both modes read the same events. The table compares them for one call:
|
|
271
372
|
|
|
272
|
-
|
|
|
273
|
-
|
|
|
274
|
-
| The call returns
|
|
275
|
-
| Call it
|
|
276
|
-
| Loop over the events
|
|
277
|
-
| Other ways to loop
|
|
278
|
-
| `event.data`
|
|
279
|
-
| A failed call, by default
|
|
280
|
-
| With `throwOnError: false`
|
|
281
|
-
| `status`, `response`, `lastEventId` | available | only with `throwOnError: false` |
|
|
373
|
+
| | `returnType: 'full'` (default) | `returnType: 'data'` |
|
|
374
|
+
| ---------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
|
|
375
|
+
| The call returns | `Unwrappable<StreamResult<…>>` | `Promise<UnwrappedStreamResult<…>>` |
|
|
376
|
+
| Call it | `const result = await streamPetEvents({ path: { petId: 1 } })` | `const events = await streamPetEvents({ path: { petId: 1 } })` |
|
|
377
|
+
| Loop over the events | `for await (const event of result.stream)` | `for await (const event of events)` |
|
|
378
|
+
| Other ways to loop | `result`, `result.data`, or `.unwrap()` | none |
|
|
379
|
+
| `event.data` | `PetEvent` | `PetEvent` |
|
|
380
|
+
| A failed call, by default | throws a `ResponseError` | throws a `ResponseError` |
|
|
381
|
+
| With `throwOnError: false` | the full result | the full result, as in `'full'` |
|
|
382
|
+
| `status`, `headers`, `response`, `lastEventId` | available | only with `throwOnError: false` |
|
|
282
383
|
|
|
283
384
|
Loop over the events the call resolves to:
|
|
284
385
|
|
|
@@ -323,7 +424,7 @@ The events alone carry no `response` or `lastEventId`. To resume a dropped strea
|
|
|
323
424
|
|
|
324
425
|
## The runtime files
|
|
325
426
|
|
|
326
|
-
`.kubb/sse.ts` holds the
|
|
427
|
+
`.kubb/sse.ts` holds `parseEventStream`, `parseJsonLines`, and the `eventStream`, `jsonLines`, and `streamMediaTypes` media types. The `ServerSentEvent`, `TypedEvent`, `EventStreamOptions`, `StreamOptions`, `StreamResult`, and `StreamResultWithHeaders` types live in `.kubb/core.ts`. A stream operation takes `StreamOptions` and returns `StreamResult`, or `StreamResultWithHeaders` when the response declares headers, the stream versions of `Options`, `RequestResult`, and `RequestResultWithHeaders`. `.kubb/client.ts` re-exports `sse.ts`, so everything imports from the client. Kubb regenerates these files on each run, so do not edit them:
|
|
327
428
|
|
|
328
429
|
```typescript
|
|
329
430
|
import type { ServerSentEvent } from './gen/.kubb/client'
|
package/docs/guides/transport.md
CHANGED
|
@@ -2,24 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
Set a transport at runtime to replace the network send. The client still builds URLs, serializes parameters, resolves authentication, and handles results.
|
|
4
4
|
|
|
5
|
-
The transport is
|
|
5
|
+
The transport is a function that takes the resolved request and returns a web `Response` with the native axios config and response, as in `@kubb/plugin-fetch`. The default is `defaultTransport`, which sends through `getAxiosInstance()`. `createAxiosTransport(instance)` turns any axios instance into a transport.
|
|
6
6
|
|
|
7
7
|
```typescript
|
|
8
8
|
type ClientConfig = {
|
|
9
9
|
// ...
|
|
10
|
-
transport?:
|
|
10
|
+
transport?: Transport
|
|
11
11
|
}
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
## Send through a pre-configured instance
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
Give the client an instance with a timeout, default headers, and a logging interceptor:
|
|
16
|
+
Wrap an instance with a timeout, default headers, and a logging interceptor:
|
|
19
17
|
|
|
20
18
|
```typescript
|
|
21
19
|
import axios from 'axios'
|
|
22
|
-
import { client } from './gen/.kubb/client'
|
|
20
|
+
import { client, createAxiosTransport } from './gen/.kubb/client'
|
|
23
21
|
|
|
24
22
|
const instance = axios.create({
|
|
25
23
|
timeout: 10_000,
|
|
@@ -31,29 +29,29 @@ instance.interceptors.response.use((response) => {
|
|
|
31
29
|
return response
|
|
32
30
|
})
|
|
33
31
|
|
|
34
|
-
client.setConfig({ transport: instance })
|
|
32
|
+
client.setConfig({ transport: createAxiosTransport(instance) })
|
|
35
33
|
```
|
|
36
34
|
|
|
37
|
-
Every generated function now sends through your instance, so its timeout, headers, and interceptors apply to each call. Handlers registered through `client.interceptors`
|
|
35
|
+
Every generated function now sends through your instance, so its timeout, headers, and axios interceptors apply to each call. Handlers registered through `client.interceptors` keep running, whatever the transport.
|
|
38
36
|
|
|
39
37
|
> [!NOTE]
|
|
40
|
-
> Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `responseType`, and `validateStatus`
|
|
38
|
+
> Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `transformResponse`, `responseType`, and `validateStatus` for its own serialization and status handling, so leave those fields alone. Set timeouts, retries, and interceptors on the instance. For one call, pass `options`, such as `{ timeout }` or `{ onUploadProgress }`, instead of building a new instance.
|
|
41
39
|
|
|
42
|
-
##
|
|
40
|
+
## Configure the default instance
|
|
43
41
|
|
|
44
|
-
The generated client exports `
|
|
42
|
+
The generated client exports `getAxiosInstance()`, which returns the instance `defaultTransport` sends through. Configure it directly to add tracing or headers without replacing the transport:
|
|
45
43
|
|
|
46
44
|
```typescript
|
|
47
|
-
import {
|
|
45
|
+
import { getAxiosInstance } from './gen/.kubb/client'
|
|
48
46
|
|
|
49
|
-
|
|
50
|
-
|
|
47
|
+
getAxiosInstance().defaults.timeout = 10_000
|
|
48
|
+
getAxiosInstance().interceptors.request.use((config) => {
|
|
51
49
|
config.headers.set('traceparent', currentTraceparent())
|
|
52
50
|
return config
|
|
53
51
|
})
|
|
54
52
|
```
|
|
55
53
|
|
|
56
|
-
|
|
54
|
+
An instance from `createClient()` copies the `transport` of `client` when you create it, unless you pass its own. A later `client.setConfig({ transport })` does not reach it. Without a `transport` on either, it sends through `getAxiosInstance()`.
|
|
57
55
|
|
|
58
56
|
## Where to set it
|
|
59
57
|
|
|
@@ -61,14 +59,12 @@ Use `client.setConfig({ transport })` for shared configuration, `createClient({
|
|
|
61
59
|
|
|
62
60
|
## Write a transport function
|
|
63
61
|
|
|
64
|
-
A function
|
|
62
|
+
A custom function can wrap `defaultTransport`, or the transport of any instance:
|
|
65
63
|
|
|
66
64
|
```typescript
|
|
67
|
-
import { client,
|
|
68
|
-
|
|
69
|
-
const send = createAxiosTransport(defaultTransport)
|
|
65
|
+
import { client, defaultTransport } from './gen/.kubb/client'
|
|
70
66
|
|
|
71
67
|
client.setConfig({
|
|
72
|
-
transport: (request) => withSpan(request, () =>
|
|
68
|
+
transport: (request) => withSpan(request, () => defaultTransport(request)),
|
|
73
69
|
})
|
|
74
70
|
```
|
package/docs/options.md
CHANGED
|
@@ -23,7 +23,7 @@ Pass these options to `pluginAxios()`. Shared options link to [Shared plugin opt
|
|
|
23
23
|
|
|
24
24
|
### baseURL
|
|
25
25
|
|
|
26
|
-
Base URL prepended to every request. When omitted, each request uses the operation's relative path from the spec, with no server
|
|
26
|
+
Base URL prepended to every request. When omitted, each request uses the operation's relative path from the spec, with no fallback to the top-level server URL. A path or operation that declares its own `servers` uses that URL instead. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/base-url). A value with a `${...}` interpolation is emitted as a template literal, so `baseURL: '${process.env.API_URL}'` reads the environment variable at runtime.
|
|
27
27
|
|
|
28
28
|
| | |
|
|
29
29
|
| -------- | -------- |
|
|
@@ -63,7 +63,7 @@ Default value. Skips validation and casts the response to the generated type.
|
|
|
63
63
|
:::
|
|
64
64
|
|
|
65
65
|
:::field{name="'zod'"}
|
|
66
|
-
Validates the success response body and
|
|
66
|
+
Validates the success response body, and the error body against the schema of its status.
|
|
67
67
|
:::
|
|
68
68
|
|
|
69
69
|
:::field{name="{ request?: 'zod', params?: 'zod', response?: 'zod' }"}
|
|
@@ -107,7 +107,7 @@ Generates a class-based SDK. Each instance takes its own client config, so envir
|
|
|
107
107
|
::field-group
|
|
108
108
|
|
|
109
109
|
:::field{name="'tag'"}
|
|
110
|
-
Default value for `sdk.mode`. Generates one class per tag, such as `PetClient`. Set `sdk.name` to also get a root class that shares one
|
|
110
|
+
Default value for `sdk.mode`. Generates one class per tag, such as `PetClient`. Set `sdk.name` to also get a root class that shares one client with every tag, used as `new PetStore(config).pet.getPetById(...)`.
|
|
111
111
|
:::
|
|
112
112
|
|
|
113
113
|
:::field{name="'flat'"}
|
|
@@ -125,6 +125,16 @@ const pet = new PetClient({ baseURL: 'https://petstore.swagger.io/v2' })
|
|
|
125
125
|
const { data } = await pet.getPetById({ path: { petId: 1 } })
|
|
126
126
|
```
|
|
127
127
|
|
|
128
|
+
Each SDK class exposes its client as the read-only `client` field. Interceptors on the root class's `client` apply to every tag:
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
|
|
132
|
+
api.client.interceptors.request.use((request) => request)
|
|
133
|
+
await api.pet.getPetById({ path: { petId: 1 } })
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
A tag class also accepts an existing client, as in `new PetClient(api.client)`.
|
|
137
|
+
|
|
128
138
|
### returnType
|
|
129
139
|
|
|
130
140
|
Shape of the value a generated call resolves to.
|
|
@@ -138,7 +148,7 @@ Shape of the value a generated call resolves to.
|
|
|
138
148
|
::field-group
|
|
139
149
|
|
|
140
150
|
:::field{name="'full'"}
|
|
141
|
-
Default value. Returns `{ status, data, error, contentType, request, response }`.
|
|
151
|
+
Default value. Returns `{ status, data, error, contentType, headers, request, response }`. `headers` is the response's `Headers`. For an operation whose responses declare `headers`, its `get` suggests those names once `status` is narrowed, and the values stay strings.
|
|
142
152
|
:::
|
|
143
153
|
|
|
144
154
|
:::field{name="'data'"}
|
package/docs/overview.md
CHANGED
|
@@ -12,7 +12,7 @@ The query plugins (`@kubb/plugin-react-query`, `@kubb/plugin-vue-query`, and `@k
|
|
|
12
12
|
|
|
13
13
|
## Options worth knowing
|
|
14
14
|
|
|
15
|
-
- `baseURL` is prepended to every request. The spec's `servers` URL is not used, so without `baseURL` you set one at runtime with `client.setConfig({ baseURL })`.
|
|
15
|
+
- `baseURL` is prepended to every request. The spec's top-level `servers` URL is not used, so without `baseURL` you set one at runtime with `client.setConfig({ baseURL })`. Operations with their own `servers`, on the path or the operation, call that URL instead.
|
|
16
16
|
- `validator: 'zod'` validates response bodies with the schemas from `@kubb/plugin-zod`. Use `{ request: 'zod', response: 'zod' }` to also validate request bodies.
|
|
17
17
|
- `throwOnErrorDefault: false` returns non-2xx responses as values instead of throwing. A single call can still pass `throwOnError`.
|
|
18
18
|
- `returnType: 'data'` makes a call resolve to the success body instead of the full result. With `throwOnError: false`, the call still returns the full result.
|