From dc94e9368a0751bf3d1aacbdaf3eeb9011ce45e7 Mon Sep 17 00:00:00 2001 From: Travis Fischer Date: Wed, 7 Dec 2022 14:44:30 -0600 Subject: [PATCH] fix: add support for polyfilled node-fetch on Vercel --- src/fetch-sse.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/fetch-sse.ts b/src/fetch-sse.ts index 705480cb..3dc4352a 100644 --- a/src/fetch-sse.ts +++ b/src/fetch-sse.ts @@ -19,8 +19,25 @@ export async function fetchSSE( } }) - for await (const chunk of streamAsyncIterable(res.body)) { - const str = new TextDecoder().decode(chunk) - parser.feed(str) + if (!res.body.getReader) { + // Vercel polyfills `fetch` with `node-fetch`, which doesn't conform to + // web standards, so this is a workaround... + const body: NodeJS.ReadableStream = res.body as any + + if (body.on || !body.read) { + throw new Error('unsupported "fetch" implementation') + } + + body.on('readable', () => { + let chunk: string | Buffer + while (null !== (chunk = body.read())) { + parser.feed(chunk.toString()) + } + }) + } else { + for await (const chunk of streamAsyncIterable(res.body)) { + const str = new TextDecoder().decode(chunk) + parser.feed(str) + } } }