()
| 47 | * Installing twice is a no-op. Call before any stream-json output is emitted. |
| 48 | */ |
| 49 | export function installStreamJsonStdoutGuard(): void { |
| 50 | if (installed) { |
| 51 | return |
| 52 | } |
| 53 | installed = true |
| 54 | |
| 55 | originalWrite = process.stdout.write.bind( |
| 56 | process.stdout, |
| 57 | ) as typeof process.stdout.write |
| 58 | |
| 59 | process.stdout.write = function ( |
| 60 | chunk: string | Uint8Array, |
| 61 | encodingOrCb?: BufferEncoding | ((err?: Error) => void), |
| 62 | cb?: (err?: Error) => void, |
| 63 | ): boolean { |
| 64 | const text = |
| 65 | typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8') |
| 66 | |
| 67 | buffer += text |
| 68 | let newlineIdx: number |
| 69 | let wrote = true |
| 70 | while ((newlineIdx = buffer.indexOf('\n')) !== -1) { |
| 71 | const line = buffer.slice(0, newlineIdx) |
| 72 | buffer = buffer.slice(newlineIdx + 1) |
| 73 | if (isJsonLine(line)) { |
| 74 | wrote = originalWrite!(line + '\n') |
| 75 | } else { |
| 76 | process.stderr.write(`${STDOUT_GUARD_MARKER} ${line}\n`) |
| 77 | logForDebugging( |
| 78 | `streamJsonStdoutGuard diverted non-JSON stdout line: ${line.slice(0, 200)}`, |
| 79 | ) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // Fire the callback once buffering is done. We report success even when |
| 84 | // a line was diverted — the caller's intent (emit text) was honored, |
| 85 | // just on a different fd. |
| 86 | const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb |
| 87 | if (callback) { |
| 88 | queueMicrotask(() => callback()) |
| 89 | } |
| 90 | return wrote |
| 91 | } as typeof process.stdout.write |
| 92 | |
| 93 | registerCleanup(async () => { |
| 94 | // Flush any partial line left in the buffer at shutdown. If it's a JSON |
| 95 | // fragment it won't parse — divert it rather than drop it silently. |
| 96 | if (buffer.length > 0) { |
| 97 | if (originalWrite && isJsonLine(buffer)) { |
| 98 | originalWrite(buffer + '\n') |
| 99 | } else { |
| 100 | process.stderr.write(`${STDOUT_GUARD_MARKER} ${buffer}\n`) |
| 101 | } |
| 102 | buffer = '' |
| 103 | } |
| 104 | if (originalWrite) { |
| 105 | process.stdout.write = originalWrite |
| 106 | originalWrite = null |
no test coverage detected