(line: string)
| 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]")) { |
no test coverage detected