1
import type { Readable } from "node:stream";2
import { StringDecoder } from "node:string_decoder";4
/**5
* Serialize a single strict JSONL record.6
*7
* Framing is LF-only. Payload strings may contain other Unicode separators such as8
* U+2028 and U+2029. Clients must split records on `\n` only.9
*/10
export function serializeJsonLine(value: unknown): string {11
return `${JSON.stringify(value)}\n`;12
}14
/**15
* Attach an LF-only JSONL reader to a stream.16
*17
* This intentionally does not use Node readline. Readline splits on additional18
* Unicode separators that are valid inside JSON strings and therefore does not19
* implement strict JSONL framing.20
*/21
export function attachJsonlLineReader(stream: Readable, onLine: (line: string) => void): () => void {22
const decoder = new StringDecoder("utf8");23
let buffer = "";25
const emitLine = (line: string) => {26
onLine(line.endsWith("\r") ? line.slice(0, -1) : line);27
};29
const onData = (chunk: string | Buffer) => {30
buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);32
while (true) {33
const newlineIndex = buffer.indexOf("\n");34
if (newlineIndex === -1) {35
return;36
}38
emitLine(buffer.slice(0, newlineIndex));39
buffer = buffer.slice(newlineIndex + 1);40
}41
};43
const onEnd = () => {44
buffer += decoder.end();45
if (buffer.length > 0) {46
emitLine(buffer);47
buffer = "";48
}49
};51
stream.on("data", onData);52
stream.on("end", onEnd);54
return () => {55
stream.off("data", onData);56
stream.off("end", onEnd);57
};58
}