|
1 | | -import type { LogOutputChannel } from "vscode"; |
| 1 | +import { Writable } from "node:stream"; |
2 | 2 |
|
3 | | -import type { Callback } from "./emitter.ts"; |
4 | | -import { createEmitter } from "./emitter.ts"; |
5 | | - |
6 | | -interface JsonlStream { |
7 | | - write(data: Buffer): void; |
8 | | - on(callback: Callback<unknown>): void; |
9 | | -} |
10 | | - |
11 | | -function safeJsonParse(text: string): unknown { |
| 3 | +/** |
| 4 | + * Safely parses a JSON string, returning null if parsing fails. |
| 5 | + * @param str - The JSON string to parse. |
| 6 | + * @returns The parsed object or null if invalid. |
| 7 | + */ |
| 8 | +export function safeJsonParse(str: string): unknown { |
12 | 9 | try { |
13 | | - return JSON.parse(text); |
| 10 | + return JSON.parse(str); |
14 | 11 | } catch { |
15 | 12 | return undefined; |
16 | 13 | } |
17 | 14 | } |
18 | 15 |
|
19 | | -export const createJsonlStream = (outputChannel: LogOutputChannel): JsonlStream => { |
20 | | - const emitter = createEmitter(outputChannel) |
21 | | - let buffer = ""; |
22 | | - return { |
23 | | - write(data) { |
24 | | - buffer += data.toString(); |
| 16 | +/** |
| 17 | + * Writable stream that buffers data until a newline, |
| 18 | + * parses each line as JSON, and emits the parsed object. |
| 19 | + */ |
| 20 | +export class JsonlStream extends Writable { |
| 21 | + constructor() { |
| 22 | + let buffer = ""; |
| 23 | + super({ |
| 24 | + write: (chunk, _encoding, callback) => { |
| 25 | + buffer += String(chunk); |
25 | 26 |
|
26 | | - // Process all complete lines |
27 | 27 | let newlineIndex = buffer.indexOf("\n"); |
28 | 28 | while (newlineIndex !== -1) { |
29 | 29 | const line = buffer.substring(0, newlineIndex).trim(); |
30 | 30 | buffer = buffer.substring(newlineIndex + 1); |
31 | 31 |
|
32 | 32 | const json = safeJsonParse(line); |
33 | | - if (json) { |
34 | | - void emitter.emit(json) |
35 | | - } |
| 33 | + if (json !== null) { |
| 34 | + this.emit("json", json); |
| 35 | + } |
36 | 36 |
|
37 | 37 | newlineIndex = buffer.indexOf("\n"); |
38 | 38 | } |
39 | | - }, |
40 | | - on(callback) { |
41 | | - emitter.on(callback) |
42 | | - }, |
43 | | - } |
44 | | -}; |
| 39 | + |
| 40 | + callback(); |
| 41 | + }, |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Registers a listener for parsed JSON objects. |
| 47 | + * @param listener - Function called with each parsed object. |
| 48 | + */ |
| 49 | + onJson(callback: (json: unknown) => void) { |
| 50 | + this.on("json", callback); |
| 51 | + } |
| 52 | +} |
0 commit comments