| 1 | export async function* toAsyncIterable( |
| 2 | nodeReadable: NodeJS.ReadableStream, |
| 3 | ): AsyncGenerator<Uint8Array> { |
| 4 | for await (const chunk of nodeReadable) { |
| 5 | // @ts-ignore |
| 6 | yield chunk as Uint8Array; |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | export async function* streamResponse( |
| 11 | response: Response, |
| 12 | ): AsyncGenerator<string> { |
| 13 | if (response.status === 499) { |
| 14 | return; // In case of client-side cancellation, just return |
| 15 | } |
| 16 | |
| 17 | if (response.status !== 200) { |
| 18 | throw new Error(await response.text()); |
| 19 | } |
| 20 | |
| 21 | if (!response.body) { |
| 22 | throw new Error("No response body returned."); |
| 23 | } |
| 24 | |
| 25 | // Get the major version of Node.js |
| 26 | const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); |
| 27 | let chunks = 0; |
| 28 | |
| 29 | try { |
| 30 | if (nodeMajorVersion >= 20) { |
| 31 | // Use the new API for Node 20 and above |
| 32 | const stream = (ReadableStream as any).from(response.body); |
| 33 | for await (const chunk of stream.pipeThrough( |
| 34 | new TextDecoderStream("utf-8"), |
| 35 | )) { |
| 36 | yield chunk; |
| 37 | chunks++; |
| 38 | } |
| 39 | } else { |
| 40 | // Fallback for Node versions below 20 |
| 41 | // Streaming with this method doesn't work as version 20+ does |
| 42 | const decoder = new TextDecoder("utf-8"); |
| 43 | const nodeStream = response.body as unknown as NodeJS.ReadableStream; |
| 44 | for await (const chunk of toAsyncIterable(nodeStream)) { |
| 45 | yield decoder.decode(chunk, { stream: true }); |
| 46 | chunks++; |
| 47 | } |
| 48 | } |
| 49 | } catch (e) { |
| 50 | if (e instanceof Error) { |
| 51 | if (e.name.startsWith("AbortError")) { |
| 52 | return; // In case of client-side cancellation, just return |
| 53 | } |
| 54 | if (e.message.toLowerCase().includes("premature close")) { |
| 55 | // Premature close can happen for various reasons, including: |
| 56 | // - Malformed chunks of data received from the server |
| 57 | // - The server closed the connection before sending the complete response |
| 58 | // - Long delays from the server during streaming |
| 59 | // - 'Keep alive' header being used in combination with an http agent and a set, low number of maxSockets |
| 60 | if (chunks === 0) { |
| 61 | throw new Error( |
| 62 | "Stream was closed before any data was received. Try again. (Premature Close)", |
| 63 | ); |
| 64 | } else { |
| 65 | throw new Error( |
| 66 | "The response was cancelled mid-stream. Try again. (Premature Close).", |
| 67 | ); |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | throw e; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // Export for testing purposes |
| 76 | export function parseDataLine(line: string): any { |
| 77 | const json = line.startsWith("data: ") |
| 78 | ? line.slice("data: ".length) |
| 79 | : line.slice("data:".length); |
| 80 | |
| 81 | try { |
| 82 | const data = JSON.parse(json); |
| 83 | if (data.error) { |
| 84 | if ( |
| 85 | data.error && |
| 86 | typeof data.error === "object" && |
| 87 | "message" in data.error |
| 88 | ) { |
| 89 | console.error("Error in streamed response:", data.error); |
| 90 | throw new Error(`Error streaming response: ${data.error.message}`); |
| 91 | } |
| 92 | throw new Error( |
| 93 | `Error streaming response: ${JSON.stringify(data.error)}`, |
| 94 | ); |
| 95 | } |
| 96 | |
| 97 | return data; |
| 98 | } catch (e) { |
| 99 | // If the error was thrown by our error check, rethrow it |
| 100 | if ( |
| 101 | e instanceof Error && |
| 102 | e.message.startsWith("Error streaming response:") |
| 103 | ) { |
| 104 | throw e; |
| 105 | } |
| 106 | // Otherwise it's a JSON parsing error |
| 107 | throw new Error(`Malformed JSON sent from server: ${json}`); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | function parseSseLine(line: string): { done: boolean; data: any } { |
| 112 | if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { |
| 113 | return { done: true, data: undefined }; |
| 114 | } |
| 115 | if (line.startsWith("data:")) { |
| 116 | return { done: false, data: parseDataLine(line) }; |
| 117 | } |
| 118 | if (line.startsWith(": ping")) { |
| 119 | return { done: true, data: undefined }; |
| 120 | } |
| 121 | return { done: false, data: undefined }; |
| 122 | } |
| 123 | |
| 124 | export async function* streamSse(response: Response): AsyncGenerator<any> { |
| 125 | let buffer = ""; |
| 126 | for await (const value of streamResponse(response)) { |
| 127 | buffer += value; |
| 128 | |
| 129 | let position: number; |
| 130 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 131 | const line = buffer.slice(0, position); |
| 132 | buffer = buffer.slice(position + 1); |
| 133 | |
| 134 | const { done, data } = parseSseLine(line); |
| 135 | if (done) { |
| 136 | break; |
| 137 | } |
| 138 | if (data) { |
| 139 | yield data; |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | if (buffer.length > 0) { |
| 145 | const { done, data } = parseSseLine(buffer); |
| 146 | if (!done && data) { |
| 147 | yield data; |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | export async function* streamJSON(response: Response): AsyncGenerator<any> { |
| 153 | let buffer = ""; |
| 154 | for await (const value of streamResponse(response)) { |
| 155 | buffer += value; |
| 156 | |
| 157 | let position; |
| 158 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 159 | const line = buffer.slice(0, position); |
| 160 | try { |
| 161 | const data = JSON.parse(line); |
| 162 | yield data; |
| 163 | } catch (e) { |
| 164 | throw new Error(`Malformed JSON sent from server: ${line}`); |
| 165 | } |
| 166 | buffer = buffer.slice(position + 1); |
| 167 | } |
| 168 | } |
| 169 | } |