@kubb/plugin-axios 6.0.2 → 6.0.4

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.
@@ -1,41 +1,26 @@
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 `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.
3
+ Stream a `text/event-stream` or JSON Lines response as typed items, then stop, resume, and handle errors.
4
4
 
5
- Each event on the wire has up to four fields, and a blank line ends it:
5
+ Kubb types the items from the OpenAPI document, and `.kubb/sse.ts` parses events as the WHATWG event stream specification does.
6
6
 
7
- | Field | Meaning |
8
- | ------- | -------------------------------------------------------------------------------- |
9
- | `event` | The event name. `message` when the server sends none. |
10
- | `data` | The payload. Parsed as JSON when it is valid JSON, and kept as text otherwise. |
11
- | `id` | The last event ID. It carries over to later events and resumes a dropped stream. |
12
- | `retry` | The reconnect delay in milliseconds. |
7
+ ## How Kubb detects a stream
13
8
 
14
- ## Pick a shape
9
+ Kubb generates a stream call when the success response declares only a stream content type:
15
10
 
16
- Kubb reads the stream's item schema in one of two shapes, and the item's properties decide which:
11
+ | The success response declares | Each item |
12
+ | ------------------------------------------------------------------------------------------ | ---------------------------------------------- |
13
+ | `text/event-stream`, and the item schema declares `event` or `data` | `TypedEvent<Item>`, narrowed by `event.event` |
14
+ | `text/event-stream`, with any other item schema | `ServerSentEvent<Item>`, with `Item` in `data` |
15
+ | `application/jsonl`, `application/x-ndjson`, `application/json-seq`, or a `+json-seq` type | `Item`, one per line |
17
16
 
18
- ::field-group
17
+ With `text/event-stream` next to another content type, Kubb generates a normal call instead. See [JSON or an event stream](#json-or-an-event-stream).
19
18
 
20
- :::field{name="event"}
21
- For several named events, such as `message_delta` and `ping`. The item declares `event` or `data`, and the stream yields `TypedEvent<Item>`. See [Typed events](#typed-events).
22
- :::
19
+ The item schema is `itemSchema` in OpenAPI 3.2. In OpenAPI 3.0 and 3.1, `schema` describes one event or one line:
23
20
 
24
- :::field{name="data"}
25
- For one payload on every event, such as a feed of pet changes. The item declares neither, and the stream yields `ServerSentEvent<Item>`. See [Payload only](#payload-only).
26
- :::
21
+ ::code-group
27
22
 
28
- ::
29
-
30
- `examples/advanced` shows both shapes: `streamOrderEvents` is typed by event, and `streamPetEvents` is typed by payload.
31
-
32
- ## Typed events
33
-
34
- ### Describe it
35
-
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
-
38
- ```yaml
23
+ ```yaml [Typed events]
39
24
  /chat:
40
25
  post:
41
26
  operationId: streamChat
@@ -65,45 +50,65 @@ In OpenAPI 3.2, put one `oneOf` member per event name on `itemSchema`, with a `c
65
50
  data: { type: string }
66
51
  ```
67
52
 
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.
53
+ ```yaml [Payload only]
54
+ /pet/{petId}/events:
55
+ get:
56
+ operationId: streamPetEvents
57
+ responses:
58
+ '200':
59
+ description: One PetEvent per event
60
+ content:
61
+ text/event-stream:
62
+ schema: { type: string } # for OpenAPI 3.0 and 3.1 tools
63
+ itemSchema: { $ref: '#/components/schemas/PetEvent' }
64
+ ```
69
65
 
70
- ### The stream
66
+ ```yaml [JSON Lines]
67
+ /logs:
68
+ get:
69
+ operationId: streamLogs
70
+ responses:
71
+ '200':
72
+ description: One LogEntry per line
73
+ content:
74
+ application/jsonl:
75
+ itemSchema: { $ref: '#/components/schemas/LogEntry' }
76
+ ```
71
77
 
72
- ```text
73
- event: message_delta
74
- id: 1
75
- data: {"text": "Hel"}
78
+ ::
76
79
 
77
- event: ping
78
- data: keep-alive
80
+ For typed events in OpenAPI 3.0 and 3.1, put the same `oneOf` on `schema`, with a `discriminator` on `event`.
79
81
 
80
- ```
82
+ > [!NOTE]
83
+ > In the browser, a stream call switches to the axios fetch adapter, because the default XHR adapter buffers the whole body. An `adapter` you set on the call or on `getAxiosInstance()` is kept.
81
84
 
82
- This stream yields two events. The `id` carries over to the second one:
85
+ ## The generated function
83
86
 
84
87
  ```typescript
85
- { event: 'message_delta', id: '1', data: { text: 'Hel' } }
86
- { event: 'ping', id: '1', data: 'keep-alive' }
88
+ export function streamChat<ThrowOnError extends boolean = true>(
89
+ options: StreamOptions<StreamChatOptions, ThrowOnError> = {},
90
+ ): Unwrappable<StreamResult<StreamChatResponses, ThrowOnError, TypedEvent<SuccessOf<StreamChatResponses>>>>
87
91
  ```
88
92
 
89
- ### Use it
93
+ A `StreamResult` has the fields of a `RequestResult` for the first connection, plus `stream` and `lastEventId`. The result iterates its items, which are also in `stream` and `data`. With `returnType: 'data'`, the call resolves to the items.
90
94
 
91
- Kubb generates one union member per event name:
95
+ Pass these stream options next to the request params:
92
96
 
93
- ```typescript
94
- export type StreamChatStatus200 =
95
- | { data: MessageDelta; event: 'message_delta'; id?: string; retry?: number }
96
- | { data?: string; event: 'ping'; id?: string; retry?: number }
97
- ```
97
+ | Option | What it does |
98
+ | -------------- | ---------------------------------------------------------------------------------------------- |
99
+ | `terminator` | Ends the stream when an event's `data`, or a JSON line, equals this value, such as `[DONE]`. |
100
+ | `transform` | Maps each Server-Sent Event before validation, for example to camelCase its keys. |
101
+ | `maxEventSize` | The most characters in one event or line. Default `16 * 1024 * 1024`. `Infinity` turns it off. |
102
+ | `signal` | An `AbortSignal` that ends the request and the loop. |
98
103
 
99
- A `switch` on `event` narrows `data` in each `case`:
104
+ ## Consume items
100
105
 
101
- ```typescript
102
- import { streamChat } from './gen/clients/streamChat'
106
+ ::code-group
103
107
 
104
- const { stream } = await streamChat({ body: { prompt: 'Hi' } })
108
+ ```typescript [Typed events]
109
+ import { streamChat } from './gen/clients/streamChat'
105
110
 
106
- for await (const event of stream) {
111
+ for await (const event of await streamChat({ body: { prompt: 'Hi' }, terminator: '[DONE]' })) {
107
112
  switch (event.event) {
108
113
  case 'message_delta':
109
114
  render(event.data.text) // MessageDelta
@@ -114,167 +119,55 @@ for await (const event of stream) {
114
119
  }
115
120
  ```
116
121
 
117
- The stream yields every event the server sends. An event name the document does not declare reaches the `default` of your `switch`, and with `validator: 'zod'` the event schema rejects it, as it would any other response that does not match the document.
118
-
119
- ## Payload only
120
-
121
- ### Describe it
122
-
123
- Point `itemSchema` at the payload. Keep `schema: { type: string }` next to it, so tools that read OpenAPI 3.0 or 3.1 still accept the document:
124
-
125
- ```yaml
126
- /pet/{petId}/events:
127
- get:
128
- operationId: streamPetEvents
129
- responses:
130
- '200':
131
- description: Server-Sent Events stream of pet changes
132
- content:
133
- text/event-stream:
134
- schema:
135
- type: string
136
- itemSchema:
137
- $ref: '#/components/schemas/PetEvent'
138
- ```
139
-
140
- In OpenAPI 3.0 and 3.1, a `schema` without `event` or `data` properties has the same shape.
141
-
142
- ### The stream
143
-
144
- ```text
145
- data: {"type": "updated", "pet": {"id": 1, "name": "Rex"}}
146
-
147
- data: {"type": "deleted", "pet": {"id": 1, "name": "Rex"}}
148
-
149
- ```
150
-
151
- This stream yields two events. The server sends no `event`, so each one is named `message`:
152
-
153
- ```typescript
154
- { event: 'message', data: { type: 'updated', pet: { id: 1, name: 'Rex' } } }
155
- { event: 'message', data: { type: 'deleted', pet: { id: 1, name: 'Rex' } } }
156
- ```
157
-
158
- ### Use it
159
-
160
- Each event is a `ServerSentEvent<PetEvent>`:
161
-
162
- ```typescript
163
- type ServerSentEvent<TData> = { data: TData; event: string; id?: string; retry?: number }
164
- ```
165
-
166
- Read `data` straight from each event. The result also holds the native `response` of the first connection:
167
-
168
- ```typescript
122
+ ```typescript [Payload only]
169
123
  import { streamPetEvents } from './gen/clients/streamPetEvents'
170
124
 
171
125
  const { stream, response } = await streamPetEvents({ path: { petId: 1 } })
172
126
  console.info(response.status) // 200
173
127
 
174
- for await (const { data } of stream) {
175
- console.info(data.type, data.pet.name) // PetEvent
176
- }
177
- ```
178
-
179
- The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
180
-
181
- ## JSON Lines
182
-
183
- 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.
184
-
185
- ### Describe it
186
-
187
- Point `itemSchema` at the schema of one line:
188
-
189
- ```yaml
190
- /logs:
191
- get:
192
- operationId: streamLogs
193
- responses:
194
- '200':
195
- description: One LogEntry per line
196
- content:
197
- application/jsonl:
198
- itemSchema:
199
- $ref: '#/components/schemas/LogEntry'
200
- ```
201
-
202
- In OpenAPI 3.0 and 3.1, `schema` on one of these media types describes one line.
203
-
204
- ### The stream
205
-
206
- ```text
207
- {"level": "info", "message": "started"}
208
- {"level": "warn", "message": "slow"}
128
+ for await (const { data } of stream) console.info(data.type) // PetEvent
209
129
  ```
210
130
 
211
- 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.
212
-
213
- ### Use it
214
-
215
- Each item is a `LogEntry`, with no event wrapper:
216
-
217
- ```typescript
131
+ ```typescript [JSON Lines]
218
132
  import { streamLogs } from './gen/clients/streamLogs'
219
133
 
220
- for await (const entry of await streamLogs()) {
221
- console.info(entry.level, entry.message) // LogEntry
222
- }
134
+ for await (const entry of await streamLogs()) console.info(entry.level, entry.message) // LogEntry
223
135
  ```
224
136
 
225
- `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.
226
-
227
- ## Stream options
137
+ ```typescript [returnType: 'data']
138
+ // with pluginAxios({ returnType: 'data' })
139
+ const events = await streamPetEvents({ path: { petId: 1 } })
228
140
 
229
- Pass these on the call, next to its request params:
230
-
231
- | Option | What it does |
232
- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
233
- | `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. |
234
- | `transform` | Maps each event before validation, for example to camelCase its keys. |
235
- | `maxEventSize` | Largest event in characters. A larger one throws a `RangeError`. Defaults to `16 * 1024 * 1024`. Set `Infinity` to turn it off. |
236
- | `signal` | An `AbortSignal` that ends the request and the loop. |
237
- | `eventShape` | What the validator checks: `data` for the payload, `event` for the whole event. Generated calls set it. |
141
+ for await (const { data } of events) console.info(data.type)
142
+ ```
238
143
 
239
- To stop reading, `break` out of the loop. The runtime then cancels the reader and releases the connection.
144
+ ::
240
145
 
241
- ## Validate events
146
+ An event the document does not declare reaches the `default` of your `switch`, so declare heartbeat and `error` events too. For event names, IDs, and JSON Lines limits, see [Event names, IDs, and JSON Lines](#event-names-ids-and-json-lines).
242
147
 
243
- With `validator: 'zod'` in the plugin options, the validator runs on each event: the whole event for typed events, `data` for a payload. A failing event calls `onValidationError`. Return `{ value }` to keep going, or the loop throws a `ParseError`:
148
+ With `validator: 'zod'`, the validator checks each item: the whole event for typed events, `data` for a payload, and each line for JSON Lines. To keep going past a failing item, return `{ value }` from `onValidationError`:
244
149
 
245
150
  ```typescript
246
- const { stream } = await streamChat({
247
- body,
248
- onValidationError: (error, { value }) => {
249
- console.warn(error.issues)
250
- return { value }
251
- },
252
- })
151
+ const { stream } = await streamChat({ body, onValidationError: (error, { value }) => ({ value }) })
253
152
  ```
254
153
 
255
- 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.
154
+ ## Stop, abort, and resume
256
155
 
257
- ## Read the response headers
156
+ - `break` out of the loop to stop. The runtime cancels the reader and releases the connection.
157
+ - Pass `signal` to stop from outside. The call or the loop rejects with the signal's reason.
158
+ - A dropped connection ends the loop with the transport's error. The runtime does not reconnect, so the retry policy is up to your app.
258
159
 
259
- 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`:
160
+ To resume, send a new call with a `Last-Event-ID` header. `lastEventId` is the `id` of the last event the server completed. Declare `Last-Event-ID` as a header parameter, so the call accepts it in `headers`:
260
161
 
261
162
  ```typescript
262
- const result = await streamChat({ body: { prompt: 'Hi' } })
263
-
264
- console.info(result.headers.get('X-Request-ID'))
265
- ```
266
-
267
- ## Resume after a drop
268
-
269
- 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. Declare `Last-Event-ID` as a header parameter of the operation, so the call accepts it in `headers`. 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:
163
+ import { ResponseError } from './gen/.kubb/client'
270
164
 
271
- ```typescript
272
165
  let lastEventId = ''
273
166
 
274
167
  for (let attempt = 0; attempt < 3; attempt++) {
275
168
  const result = await streamChat({ body, headers: lastEventId ? { 'Last-Event-ID': lastEventId } : {} })
276
169
  try {
277
- for await (const event of result.stream) render(event)
170
+ for await (const event of result) render(event)
278
171
  break
279
172
  } catch (error) {
280
173
  if (ResponseError.is(error)) throw error
@@ -283,53 +176,38 @@ for (let attempt = 0; attempt < 3; attempt++) {
283
176
  }
284
177
  ```
285
178
 
286
- `lastEventId` is empty until the server sends an `id`, and an empty `id:` field clears it. An `id` that contains a NULL character is ignored. Each event carries the server's `retry` hint as `retry`.
179
+ For cleared IDs and resuming with `returnType: 'data'`, see [Event IDs when you resume](#event-ids-when-you-resume).
287
180
 
288
181
  ## Handle errors
289
182
 
290
- A non-2xx response throws a `ResponseError`, from the call or from the loop:
291
-
292
- ```typescript
293
- import { ResponseError } from './gen/.kubb/client'
294
-
295
- try {
296
- const { stream } = await streamChat({ body })
297
- for await (const event of stream) render(event)
298
- } catch (error) {
299
- if (!ResponseError.is(error)) throw error
300
- console.error('stream rejected', error.status)
301
- }
302
- ```
303
-
304
- 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:
183
+ | What happens | Where it fails |
184
+ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
185
+ | Non-2xx response | The call throws a `ResponseError`. |
186
+ | Non-2xx response with `throwOnError: false` | The call resolves with `status` and `error`. `data` is `undefined`, and the stream yields nothing. |
187
+ | 2xx response whose body is not a stream, such as JSON | The call throws a `TypeError` with the body as its `cause`. |
188
+ | 2xx response with an empty body | No error. The stream is empty. |
189
+ | Dropped connection or abort | The loop throws. |
190
+ | An item fails its schema | The loop throws a `ParseError`, unless `onValidationError` returns `{ value }`. |
191
+ | An event is larger than `maxEventSize` | The loop throws a `RangeError`. |
192
+ | A JSON line is not valid JSON | The loop throws a `SyntaxError`. |
305
193
 
306
194
  ```typescript
307
195
  const result = await streamChat({ body, throwOnError: false })
196
+
308
197
  if (!result.data) console.error('stream rejected', result.status, result.error)
309
198
  else for await (const event of result.data) render(event)
310
199
  ```
311
200
 
312
- As on a regular call, `.unwrap()` resolves to the events. A failed call rejects with a `ResponseError` by default, and with the `error` body when the call sets `throwOnError: false`:
313
-
314
- ```typescript
315
- for await (const event of await streamChat({ body }).unwrap()) render(event)
316
- ```
317
-
318
- 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).
319
-
320
- Declare heartbeat and `error` events in the document, so each has a `case` in your `switch`.
201
+ An error thrown from the loop skips `client.interceptors.error`. `.unwrap()` resolves to the items, as on a regular call.
321
202
 
322
203
  ## JSON or an event stream
323
204
 
324
- 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.
325
-
326
- 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:
205
+ When the success response declares `text/event-stream` next to another type, such as `application/json`, Kubb generates a normal call that sends `Accept: text/event-stream`. Pass `contentType: { response: 'application/json' }` to ask for JSON. When the server streams, `data` is the raw `ReadableStream<Uint8Array>`, so read it with `parseEventStream`, or `parseJsonLines({ stream })` for JSON Lines:
327
206
 
328
207
  ```typescript
329
208
  import { parseEventStream } from './gen/.kubb/client'
330
- import { getV2StreamRecentchange } from './gen/clients/getV2StreamRecentchange'
331
209
 
332
- const result = await getV2StreamRecentchange({ signal })
210
+ const result = await getRecentChanges({ signal })
333
211
 
334
212
  if (result.contentType === 'text/event-stream') {
335
213
  for await (const { data } of parseEventStream(result.data)) render(data)
@@ -338,18 +216,9 @@ if (result.contentType === 'text/event-stream') {
338
216
  }
339
217
  ```
340
218
 
341
- To get a stream result with `lastEventId`, send the same request with `client.stream`. It throws a `TypeError` when the server answers with JSON:
342
-
343
- ```typescript
344
- import { client } from './gen/.kubb/client'
345
-
346
- const result = await client.stream({ method: 'GET', url: '/v2/stream/recentchange', eventShape: 'data', signal })
347
- for await (const event of result) render(event.data)
348
- ```
349
-
350
219
  ## Stream with the client
351
220
 
352
- `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:
221
+ `client.stream(config)` sends a stream request by hand. It runs the same interceptors and transport as `client(config)`, and validates each item with `validator.response`. Type it with the responses record, `ThrowOnError`, and the item type:
353
222
 
354
223
  ```typescript
355
224
  import { client, type SuccessOf } from './gen/.kubb/client'
@@ -358,76 +227,67 @@ import type { StreamLogsResponses } from './gen/types/StreamLogs'
358
227
  const result = await client.stream<StreamLogsResponses, true, SuccessOf<StreamLogsResponses>>({ method: 'GET', url: '/logs' })
359
228
  ```
360
229
 
361
- 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.
230
+ The item type defaults to `ServerSentEvent` around the success body. To stream another format, register a `stream` handler, as [Add a media type](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/serialization#add-a-media-type) shows.
362
231
 
363
- ## Return only the events
232
+ Import the stream helpers and types from `.kubb/client`, and do not edit the `.kubb/` files: Kubb rewrites them on each run.
364
233
 
365
- With `returnType: 'data'` in the plugin options, a stream call returns its events, as a regular call returns only its body:
234
+ ## Less common cases
366
235
 
367
- ```typescript
368
- import { pluginAxios } from '@kubb/plugin-axios'
236
+ ### JSON in a `data` string
369
237
 
370
- pluginAxios({ returnType: 'data' })
371
- ```
238
+ When an event's `data` is a string with `contentMediaType: application/json` and a `contentSchema`, Kubb types and parses it as that schema. See [How Kubb detects a stream](#how-kubb-detects-a-stream) for the item schemas.
372
239
 
373
- Both modes read the same events. The table compares them for one call:
240
+ ### Stream calls in Node.js
374
241
 
375
- | | `returnType: 'full'` (default) | `returnType: 'data'` |
376
- | ---------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
377
- | The call returns | `Unwrappable<StreamResult<…>>` | `Promise<UnwrappedStreamResult<…>>` |
378
- | Call it | `const result = await streamPetEvents({ path: { petId: 1 } })` | `const events = await streamPetEvents({ path: { petId: 1 } })` |
379
- | Loop over the events | `for await (const event of result.stream)` | `for await (const event of events)` |
380
- | Other ways to loop | `result`, `result.data`, or `.unwrap()` | none |
381
- | `event.data` | `PetEvent` | `PetEvent` |
382
- | A failed call, by default | throws a `ResponseError` | throws a `ResponseError` |
383
- | With `throwOnError: false` | the full result | the full result, as in `'full'` |
384
- | `status`, `headers`, `response`, `lastEventId` | available | only with `throwOnError: false` |
242
+ When a stream call runs in Node.js, the axios http adapter streams the body, with its proxy and agent settings. Only a browser call with the default adapters switches to the fetch adapter.
385
243
 
386
- Loop over the events the call resolves to:
244
+ ### Stream result types
387
245
 
388
- ```typescript
389
- import { streamOrderEvents } from './gen/clients/streamOrderEvents'
390
- import { streamPetEvents } from './gen/clients/streamPetEvents'
246
+ When you type a variable that holds a stream result, the type depends on the response and on `returnType`:
391
247
 
392
- const events = await streamOrderEvents({ path: { orderId: 7 } })
248
+ | Setting | The call returns |
249
+ | ------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
250
+ | Default | `Unwrappable<StreamResult<…>>` |
251
+ | The response declares headers | `Unwrappable<StreamResultWithHeaders<…>>`, so `headers.get` suggests their names |
252
+ | `returnType: 'data'` | `Promise<UnwrappedStreamResult<…>>`: the items, or the full result with `throwOnError: false` |
253
+ | `returnType: 'data'`, and the response declares headers | `Promise<UnwrappedStreamResultWithHeaders<…>>` |
393
254
 
394
- for await (const event of events) {
395
- if (event.event === 'order_placed') render(event.data) // Order
396
- }
255
+ In v5, a stream response that declared headers returned a plain `StreamResult`. [The generated function](#the-generated-function) shows the default signature.
397
256
 
398
- for await (const { data } of await streamPetEvents({ path: { petId: 1 } })) {
399
- console.info(data.type) // PetEvent
400
- }
401
- ```
257
+ ### Stream options Kubb sets
402
258
 
403
- A failed call throws a `ResponseError` before the first event, and a dropped connection throws from the loop:
259
+ When you call [`client.stream`](#stream-with-the-client) yourself, pass the options a generated stream call gets from the document:
404
260
 
405
- ```typescript
406
- import { ResponseError } from './gen/.kubb/client'
261
+ | Option | What it does |
262
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
263
+ | `eventShape` | Whether the validator checks the whole event (`'event'`) or its `data` (`'data'`). |
264
+ | `rawData` | Keeps `data` as text, for every event or for a list of event names. Kubb sets it when the document types `data` as a string. Otherwise `data` is parsed as JSON when it parses. |
407
265
 
408
- try {
409
- for await (const event of await streamPetEvents({ path: { petId: 1 } })) render(event)
410
- } catch (error) {
411
- if (!ResponseError.is(error)) throw error
412
- console.error('stream rejected', error.status)
413
- }
414
- ```
266
+ ### Event names, IDs, and JSON Lines
415
267
 
416
- With `throwOnError: false`, the call returns the full result instead, as a regular call does in this mode. The events are its `data` on a 2xx response, and checking `status` narrows `error`:
268
+ When the server leaves a field out of an event, or sends JSON Lines:
417
269
 
418
- ```typescript
419
- const result = await streamPetEvents({ path: { petId: 1 }, throwOnError: false })
270
+ - An event takes `message` as its name when the server sends none.
271
+ - The `id` carries over to later events, and `retry` holds the server's reconnect hint.
272
+ - A JSON Lines stream has no event IDs, and `transform` does not apply to it.
273
+ - An `application/json-seq` record must fit on one line.
420
274
 
421
- if (!result.data) console.error('stream rejected', result.status, result.error)
422
- else for await (const event of result.data) render(event)
423
- ```
275
+ ### Event IDs when you resume
424
276
 
425
- The events alone carry no `response` or `lastEventId`. To resume a dropped stream, use the default `returnType: 'full'`, or pass `throwOnError: false` to get the full result.
277
+ When you [resume a stream](#stop-abort-and-resume):
426
278
 
427
- ## The runtime files
279
+ - The runtime does not reconnect, because many streams end on purpose and the retry policy belongs to your app.
280
+ - `lastEventId` is empty until the server sends an `id`, and an empty `id:` clears it.
281
+ - The `||` fallback in the resume loop cannot tell a cleared ID from no ID, so after a clear the loop resends the previous ID.
282
+ - With `returnType: 'data'`, the items alone carry no `lastEventId`, so pass `throwOnError: false` to get the full result.
428
283
 
429
- `.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. These types are 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:
284
+ ### Interceptors on a stream call
430
285
 
431
- ```typescript
432
- import type { ServerSentEvent } from './gen/.kubb/client'
433
- ```
286
+ When a response interceptor runs on a stream call, `data` in its `DecodedResponse` is the raw body stream. See [Add interceptors](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/configure-requests#add-interceptors).
287
+
288
+ ### Stream runtime files
289
+
290
+ When you look for a stream helper or type, import it from `.kubb/client`:
291
+
292
+ - `.kubb/sse.ts` holds `parseEventStream`, `parseJsonLines`, and the stream media types, and `.kubb/client.ts` re-exports it.
293
+ - The stream types, such as `ServerSentEvent`, `TypedEvent`, `StreamOptions`, and `StreamResult`, live in `.kubb/core.ts`.