* Asynchronously converts a stream of chunks into lines. * @param {AsyncIterable } chunksAsync - Stream of chunks to convert into lines. * @returns {AsyncIterable } - An asynchronous iterable that yields lines from the input chunks.
(chunksAsync: any)
| 4 | * @returns {AsyncIterable<string>} - An asynchronous iterable that yields lines from the input chunks. |
| 5 | */ |
| 6 | async function* chunksToLines(chunksAsync: any) { |
| 7 | let previous = ""; |
| 8 | for await (const chunk of chunksAsync) { |
| 9 | const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 10 | previous += bufferChunk; |
| 11 | let eolIndex; |
| 12 | while ((eolIndex = previous.indexOf("\n")) >= 0) { |
| 13 | // line includes the EOL |
| 14 | const line = previous.slice(0, eolIndex + 1).trimEnd(); |
| 15 | if (line === "data: [DONE]") break; |
| 16 | if (line.startsWith("data: ")) yield line; |
| 17 | previous = previous.slice(eolIndex + 1); |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Asynchronously converts a stream of lines into messages. |