|
| 1 | +{{>partial_header}} |
| 2 | + |
| 3 | +import type { Readable } from "node:stream"; |
| 4 | + |
| 5 | +// Helper: create async iterable from classic EventEmitter-style Readable streams |
| 6 | +const createAsyncIterableFromReadable = (readable: any): AsyncIterable<any> => { |
| 7 | + return { |
| 8 | + [Symbol.asyncIterator](): AsyncIterator<any> { |
| 9 | + const chunkQueue: any[] = []; |
| 10 | + const pendingResolvers: Array<(value: IteratorResult<any>) => void> = []; |
| 11 | + let ended = false; |
| 12 | + let error: any = null; |
| 13 | +
|
| 14 | + const onData = (chunk: any) => { |
| 15 | + if (pendingResolvers.length > 0) { |
| 16 | + const resolve = pendingResolvers.shift()!; |
| 17 | + resolve({ value: chunk, done: false }); |
| 18 | + } else { |
| 19 | + chunkQueue.push(chunk); |
| 20 | + } |
| 21 | + }; |
| 22 | + |
| 23 | + const onEnd = () => { |
| 24 | + ended = true; |
| 25 | + while (pendingResolvers.length > 0) { |
| 26 | + const resolve = pendingResolvers.shift()!; |
| 27 | + resolve({ value: undefined, done: true }); |
| 28 | + } |
| 29 | + }; |
| 30 | + |
| 31 | + const onError = (err: any) => { |
| 32 | + error = err; |
| 33 | + while (pendingResolvers.length > 0) { |
| 34 | + const resolve = pendingResolvers.shift()!; |
| 35 | + // Rejecting inside async iterator isn't straightforward; surface as end and throw later |
| 36 | + resolve({ value: undefined, done: true }); |
| 37 | + } |
| 38 | + }; |
| 39 | +
|
| 40 | + readable.on("data", onData); |
| 41 | + readable.once("end", onEnd); |
| 42 | + readable.once("error", onError); |
| 43 | +
|
| 44 | + const cleanup = () => { |
| 45 | + readable.off("data", onData); |
| 46 | + readable.off("end", onEnd); |
| 47 | + readable.off("error", onError); |
| 48 | + }; |
| 49 | +
|
| 50 | + return { |
| 51 | + next(): Promise<IteratorResult<any>> { |
| 52 | + if (error) { |
| 53 | + cleanup(); |
| 54 | + return Promise.reject(error); |
| 55 | + } |
| 56 | + if (chunkQueue.length > 0) { |
| 57 | + const value = chunkQueue.shift(); |
| 58 | + return Promise.resolve({ value, done: false }); |
| 59 | + } |
| 60 | + if (ended) { |
| 61 | + cleanup(); |
| 62 | + return Promise.resolve({ value: undefined, done: true }); |
| 63 | + } |
| 64 | + return new Promise<IteratorResult<any>>((resolve) => { |
| 65 | + pendingResolvers.push(resolve); |
| 66 | + }); |
| 67 | + }, |
| 68 | + return(): Promise<IteratorResult<any>> { |
| 69 | + cleanup(); |
| 70 | + return Promise.resolve({ value: undefined, done: true }); |
| 71 | + }, |
| 72 | + throw(e?: any): Promise<IteratorResult<any>> { |
| 73 | + cleanup(); |
| 74 | + return Promise.reject(e); |
| 75 | + } |
| 76 | + }; |
| 77 | + } |
| 78 | + }; |
| 79 | +}; |
| 80 | +
|
| 81 | +/** |
| 82 | + * Parse newline-delimited JSON (NDJSON) from a Node.js readable stream |
| 83 | + * @param stream - Node.js readable stream |
| 84 | + * @returns AsyncGenerator that yields parsed JSON objects |
| 85 | + */ |
| 86 | +export async function* parseNDJSONStream(stream: Readable): AsyncGenerator<any> { |
| 87 | + const decoder = new TextDecoder("utf-8"); |
| 88 | + let buffer = ""; |
| 89 | +
|
| 90 | + // If stream is actually a string or Buffer-like, handle as whole payload |
| 91 | + const isString = typeof stream === "string"; |
| 92 | + const isBuffer = typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(stream); |
| 93 | +
|
| 94 | + if (isString || isBuffer) { |
| 95 | + const text = isString ? stream : new TextDecoder("utf-8").decode(new Uint8Array(stream)); |
| 96 | + const lines = text.split("\n"); |
| 97 | +
|
| 98 | + for (const line of lines) { |
| 99 | + const trimmed = line.trim(); |
| 100 | + if (!trimmed) { |
| 101 | + continue; |
| 102 | + } |
| 103 | +
|
| 104 | + try { |
| 105 | + yield JSON.parse(trimmed); |
| 106 | + } catch (err) { |
| 107 | + console.warn("Failed to parse JSON line:", err); |
| 108 | + } |
| 109 | + } |
| 110 | + return; |
| 111 | + } |
| 112 | +
|
| 113 | + const isAsyncIterable = stream && typeof stream[Symbol.asyncIterator] === "function"; |
| 114 | + const source: AsyncIterable<any> = isAsyncIterable ? stream : createAsyncIterableFromReadable(stream); |
| 115 | +
|
| 116 | + for await (const chunk of source) { |
| 117 | + // Node.js streams can return Buffer or string chunks |
| 118 | + // Convert to Uint8Array if needed for TextDecoder |
| 119 | + const uint8Chunk = typeof chunk === "string" |
| 120 | + ? new TextEncoder().encode(chunk) |
| 121 | + : chunk instanceof Buffer |
| 122 | + ? new Uint8Array(chunk) |
| 123 | + : chunk; |
| 124 | +
|
| 125 | + // Append decoded chunk to buffer |
| 126 | + buffer += decoder.decode(uint8Chunk, { stream: true }); |
| 127 | +
|
| 128 | + // Split on newlines |
| 129 | + const lines = buffer.split("\n"); |
| 130 | +
|
| 131 | + // Keep the last (potentially incomplete) line in the buffer |
| 132 | + buffer = lines.pop() || ""; |
| 133 | +
|
| 134 | + // Parse and yield complete lines |
| 135 | + for (const line of lines) { |
| 136 | + const trimmed = line.trim(); |
| 137 | + if (trimmed) { |
| 138 | + try { |
| 139 | + yield JSON.parse(trimmed); |
| 140 | + } catch (err) { |
| 141 | + console.warn("Failed to parse JSON line:", err); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | +
|
| 147 | + // Flush any remaining decoder state |
| 148 | + buffer += decoder.decode(); |
| 149 | +
|
| 150 | + // Handle any remaining data in buffer |
| 151 | + if (buffer.trim()) { |
| 152 | + try { |
| 153 | + yield JSON.parse(buffer); |
| 154 | + } catch (err) { |
| 155 | + console.warn("Failed to parse final JSON buffer:", err); |
| 156 | + } |
| 157 | + } |
| 158 | +} |
| 159 | +
|
0 commit comments