* Creates a stream of AsyncIterator from a Server-Sent Events (SSE) response. * * @template Item - The type of items in the stream. * @param {Response} response - The SSE response object. * @param {AbortController} controller - The abort controller used to cancel the ongoing request. * @re
(response: Response, controller: AbortController)
| 26 | * @throws {Error} - If the stream has already been consumed. |
| 27 | */ |
| 28 | static fromSSEResponse<Item>(response: Response, controller: AbortController) { |
| 29 | let consumed = false; |
| 30 | |
| 31 | async function* iterator(): AsyncIterator<Item, any, undefined> { |
| 32 | if (consumed) { |
| 33 | throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); |
| 34 | } |
| 35 | consumed = true; |
| 36 | let done = false; |
| 37 | try { |
| 38 | for await (const sse of _iterSSEMessages(response, controller)) { |
| 39 | if (done) continue; |
| 40 | |
| 41 | if (sse.data.startsWith('[DONE]')) { |
| 42 | done = true; |
| 43 | continue; |
| 44 | } |
| 45 | |
| 46 | if (sse.event === null) { |
| 47 | let data; |
| 48 | |
| 49 | try { |
| 50 | data = JSON.parse(sse.data); |
| 51 | } catch (e) { |
| 52 | console.error(`Could not parse message into JSON:`, sse.data); |
| 53 | console.error(`From chunk:`, sse.raw); |
| 54 | throw e; |
| 55 | } |
| 56 | |
| 57 | if (data && data.error) { |
| 58 | throw new Error(data.error); |
| 59 | } |
| 60 | |
| 61 | yield data; |
| 62 | } else { |
| 63 | let data; |
| 64 | try { |
| 65 | data = JSON.parse(sse.data); |
| 66 | } catch (e) { |
| 67 | console.error(`Could not parse message into JSON:`, sse.data); |
| 68 | console.error(`From chunk:`, sse.raw); |
| 69 | throw e; |
| 70 | } |
| 71 | // TODO: Is this where the error should be thrown? |
| 72 | if (sse.event == 'error') { |
| 73 | throw new Error(data.message); |
| 74 | } |
| 75 | yield {event: sse.event, data: data} as any; |
| 76 | } |
| 77 | } |
| 78 | done = true; |
| 79 | } catch (e) { |
| 80 | // If the user calls `stream.controller.abort()`, we should exit without throwing. |
| 81 | if (e instanceof Error && e.name === 'AbortError') return; |
| 82 | throw e; |
| 83 | } finally { |
| 84 | // If the user `break`s, abort the ongoing request. |
| 85 | if (!done) controller.abort(); |
no outgoing calls
no test coverage detected