MCPcopy
hub / github.com/codeaashu/claude-code / createBufferedWriter

Function createBufferedWriter

src/utils/bufferedWriter.ts:9–100  ·  view source on GitHub ↗
({
  writeFn,
  flushIntervalMs = 1000,
  maxBufferSize = 100,
  maxBufferBytes = Infinity,
  immediateMode = false,
}: {
  writeFn: WriteFn
  flushIntervalMs?: number
  maxBufferSize?: number
  maxBufferBytes?: number
  immediateMode?: boolean
})

Source from the content-addressed store, hash-verified

7}
8
9export function createBufferedWriter({
10 writeFn,
11 flushIntervalMs = 1000,
12 maxBufferSize = 100,
13 maxBufferBytes = Infinity,
14 immediateMode = false,
15}: {
16 writeFn: WriteFn
17 flushIntervalMs?: number
18 maxBufferSize?: number
19 maxBufferBytes?: number
20 immediateMode?: boolean
21}): BufferedWriter {
22 let buffer: string[] = []
23 let bufferBytes = 0
24 let flushTimer: NodeJS.Timeout | null = null
25 // Batch detached by overflow that hasn't been written yet. Tracked so
26 // flush()/dispose() can drain it synchronously if the process exits
27 // before the setImmediate fires.
28 let pendingOverflow: string[] | null = null
29
30 function clearTimer(): void {
31 if (flushTimer) {
32 clearTimeout(flushTimer)
33 flushTimer = null
34 }
35 }
36
37 function flush(): void {
38 if (pendingOverflow) {
39 writeFn(pendingOverflow.join(''))
40 pendingOverflow = null
41 }
42 if (buffer.length === 0) return
43 writeFn(buffer.join(''))
44 buffer = []
45 bufferBytes = 0
46 clearTimer()
47 }
48
49 function scheduleFlush(): void {
50 if (!flushTimer) {
51 flushTimer = setTimeout(flush, flushIntervalMs)
52 }
53 }
54
55 // Detach the buffer synchronously so the caller never waits on writeFn.
56 // writeFn may block (e.g. errorLogSink.ts appendFileSync) — if overflow fires
57 // mid-render or mid-keystroke, deferring the write keeps the current tick
58 // short. Timer-based flushes already run outside user code paths so they
59 // stay synchronous.
60 function flushDeferred(): void {
61 if (pendingOverflow) {
62 // A previous overflow write is still queued. Coalesce into it to
63 // preserve ordering — writes land in a single setImmediate-ordered batch.
64 pendingOverflow.push(...buffer)
65 buffer = []
66 bufferBytes = 0

Callers 3

createJsonlWriterFunction · 0.85
installAsciicastRecorderFunction · 0.85
getDebugWriterFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected