Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

response-stream.ts

42 lines1.4 KB

1export type MissingResponseStreamFeature =
2 | 'TextDecoder'
3 | 'Response.body'
4 | 'Response.body.getReader'
5​
6export class UnsupportedResponseStreamError extends Error {
7 readonly missingFeature: MissingResponseStreamFeature
8​
9 constructor(missingFeature: MissingResponseStreamFeature) {
10 super(createUnsupportedResponseStreamMessage(missingFeature))
11 this.name = 'UnsupportedResponseStreamError'
12 this.missingFeature = missingFeature
13 }
15​
16function createUnsupportedResponseStreamMessage(
17 missingFeature: MissingResponseStreamFeature,
18): string {
19 return `Streaming fetch responses are not supported in this runtime because ${missingFeature} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`
21​
22export function getResponseStreamReader(
23 response: Response,
24): ReadableStreamDefaultReader<Uint8Array> {
25 if (!response.body) {
26 throw new UnsupportedResponseStreamError('Response.body')
27 }
28​
29 if (typeof response.body.getReader !== 'function') {
30 throw new UnsupportedResponseStreamError('Response.body.getReader')
31 }
32​
33 return response.body.getReader()
35​
36export function createResponseStreamTextDecoder(): TextDecoder {
37 if (typeof globalThis.TextDecoder !== 'function') {
38 throw new UnsupportedResponseStreamError('TextDecoder')
39 }
40​
41 return new globalThis.TextDecoder()