Skip to content
Myr

stream.ts

This file

Path

src/helper/streaming/stream.ts

45 lines · 1.4 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–45why, one step back
1import type { Context } from '../../context'
2import { StreamingApi } from '../../utils/stream'3import { isOldBunVersion } from './utils'45const contextStash: WeakMap<ReadableStream, Context> = new WeakMap<ReadableStream, Context>()67export const stream = (8 c: Context,9 cb: (stream: StreamingApi) => Promise<void>,10 onError?: (e: Error, stream: StreamingApi) => Promise<void>11): Response => {12 const { readable, writable } = new TransformStream()13 const stream = new StreamingApi(writable, readable)1415 // Until Bun v1.1.27, Bun didn't call cancel() on the ReadableStream for Response objects from Bun.serve()16 if (isOldBunVersion()) {17 c.req.raw.signal.addEventListener('abort', () => {18 if (!stream.closed) {19 stream.abort()20 }21 })22 }2324 // in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming25 contextStash.set(stream.responseReadable, c)26 ;(async () => {27 try {28 await cb(stream)29 } catch (e) {30 if (e === undefined) {31 // If reading is canceled without a reason value (e.g. by StreamingApi)32 // then the .pipeTo() promise will reject with undefined.33 // In this case, do nothing because the stream is already closed.34 } else if (e instanceof Error && onError) {35 await onError(e, stream)36 } else {37 console.error(e)38 }39 } finally {40 stream.close()41 }42 })()4344 return c.newResponse(stream.responseReadable)45}