Open History to see the last commit
1// This file is auto-generated by @hey-api/openapi-ts
2
3import type { Config } from './types.gen'
4
5export type ServerSentEventsOptions<TData = unknown> = Omit<
6 RequestInit,
7 'method'
8> &
9 Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
10 /**
11 * Fetch API implementation. You can use this option to provide a custom
12 * fetch instance.
13 *
14 * @default globalThis.fetch
15 */
16 fetch?: typeof fetch
17 /**
18 * Implementing clients can call request interceptors inside this hook.
19 */
20 onRequest?: (url: string, init: RequestInit) => Promise<Request>
21 /**
22 * Callback invoked when a network or parsing error occurs during streaming.
23 *
24 * This option applies only if the endpoint returns a stream of events.
25 *
26 * @param error The error that occurred.
27 */
28 onSseError?: (error: unknown) => void
29 /**
30 * Callback invoked when an event is streamed from the server.
31 *
32 * This option applies only if the endpoint returns a stream of events.
33 *
34 * @param event Event streamed from the server.
35 * @returns Nothing (void).
36 */
37 onSseEvent?: (event: StreamEvent<TData>) => void
38 serializedBody?: RequestInit['body']
39 /**
40 * Default retry delay in milliseconds.
41 *
42 * This option applies only if the endpoint returns a stream of events.
43 *
44 * @default 3000
45 */
46 sseDefaultRetryDelay?: number
47 /**
48 * Maximum number of retry attempts before giving up.
49 */
50 sseMaxRetryAttempts?: number
51 /**
52 * Maximum retry delay in milliseconds.
53 *
54 * Applies only when exponential backoff is used.
55 *
56 * This option applies only if the endpoint returns a stream of events.
57 *
58 * @default 30000
59 */
60 sseMaxRetryDelay?: number
61 /**
62 * Optional sleep function for retry backoff.
63 *
64 * Defaults to using `setTimeout`.
65 */
66 sseSleepFn?: (ms: number) => Promise<void>
67 url: string
68 }
69
70export interface StreamEvent<TData = unknown> {
71 data: TData
72 event?: string
73 id?: string
74 retry?: number
75}
76
77export type ServerSentEventsResult<
78 TData = unknown,
79 TReturn = void,
80 TNext = unknown,
81> = {
82 stream: AsyncGenerator<
83 TData extends Record<string, unknown> ? TData[keyof TData] : TData,
84 TReturn,
85 TNext
86 >
87}
88
89export function createSseClient<TData = unknown>({
90 onRequest,
91 onSseError,
92 onSseEvent,
93 responseTransformer,
94 responseValidator,
95 sseDefaultRetryDelay,
96 sseMaxRetryAttempts,
97 sseMaxRetryDelay,
98 sseSleepFn,
99 url,
100 ...options
101}: ServerSentEventsOptions): ServerSentEventsResult<TData> {
102 let lastEventId: string | undefined
103
104 const sleep =
105 sseSleepFn ??
106 ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
107
108 const createStream = async function* () {
109 let retryDelay: number = sseDefaultRetryDelay ?? 3000
110 let attempt = 0
111 const signal = options.signal ?? new AbortController().signal
112
113 while (true) {
114 if (signal.aborted) break
115
116 attempt++
117
118 const headers =
119 options.headers instanceof Headers
120 ? options.headers
121 : new Headers(options.headers as Record<string, string> | undefined)
122
123 if (lastEventId !== undefined) {
124 headers.set('Last-Event-ID', lastEventId)
125 }
126
127 try {
128 const requestInit: RequestInit = {
129 redirect: 'follow',
130 ...options,
131 body: options.serializedBody,
132 headers,
133 signal,
134 }
135 let request = new Request(url, requestInit)
136 if (onRequest) {
137 request = await onRequest(url, requestInit)
138 }
139 // fetch must be assigned here, otherwise it would throw the error:
140 // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
141 const _fetch = options.fetch ?? globalThis.fetch
142 const response = await _fetch(request)
143
144 if (!response.ok)
145 throw new Error(
146 `SSE failed: ${response.status} ${response.statusText}`,
147 )
148
149 if (!response.body) throw new Error('No body in SSE response')
150
151 const reader = response.body
152 .pipeThrough(new TextDecoderStream())
153 .getReader()
154
155 let buffer = ''
156
157 const abortHandler = () => {
158 try {
159 reader.cancel()
160 } catch {
161 // noop
162 }
163 }
164
165 signal.addEventListener('abort', abortHandler)
166
167 try {
168 while (true) {
169 const { done, value } = await reader.read()
170 if (done) break
171 buffer += value
172 buffer = buffer.replace(/\r\n?/g, '\n') // normalize line endings
173
174 const chunks = buffer.split('\n\n')
175 buffer = chunks.pop() ?? ''
176
177 for (const chunk of chunks) {
178 const lines = chunk.split('\n')
179 const dataLines: Array<string> = []
180 let eventName: string | undefined
181
182 for (const line of lines) {
183 if (line.startsWith('data:')) {
184 dataLines.push(line.replace(/^data:\s*/, ''))
185 } else if (line.startsWith('event:')) {
186 eventName = line.replace(/^event:\s*/, '')
187 } else if (line.startsWith('id:')) {
188 lastEventId = line.replace(/^id:\s*/, '')
189 } else if (line.startsWith('retry:')) {
190 const parsed = Number.parseInt(
191 line.replace(/^retry:\s*/, ''),
192 10,
193 )
194 if (!Number.isNaN(parsed)) {
195 retryDelay = parsed
196 }
197 }
198 }
199
200 let data: unknown
201 let parsedJson = false
202
203 if (dataLines.length) {
204 const rawData = dataLines.join('\n')
205 try {
206 data = JSON.parse(rawData)
207 parsedJson = true
208 } catch {
209 data = rawData
210 }
211 }
212
213 if (parsedJson) {
214 if (responseValidator) {
215 await responseValidator(data)
216 }
217
218 if (responseTransformer) {
219 data = await responseTransformer(data)
220 }
221 }
222
223 onSseEvent?.({
224 data,
225 event: eventName,
226 id: lastEventId,
227 retry: retryDelay,
228 })
229
230 if (dataLines.length) {
231 yield data as any
232 }
233 }
234 }
235 } finally {
236 signal.removeEventListener('abort', abortHandler)
237 reader.releaseLock()
238 }
239
240 break // exit loop on normal completion
241 } catch (error) {
242 // connection failed or aborted; retry after delay
243 onSseError?.(error)
244
245 if (
246 sseMaxRetryAttempts !== undefined &&
247 attempt >= sseMaxRetryAttempts
248 ) {
249 break // stop after firing error
250 }
251
252 // exponential backoff: double retry each attempt, cap at 30s
253 const backoff = Math.min(
254 retryDelay * 2 ** (attempt - 1),
255 sseMaxRetryDelay ?? 30000,
256 )
257 await sleep(backoff)
258 }
259 }
260 }
261
262 const stream = createStream()
263
264 return { stream }
265}