const DEFAULT_FLUSH_DELAY_MS = 5;
export class TerminalOutputCoalescer {
    constructor(options) {
        this.chunks = [];
        this.bytes = 0;
        this.chars = 0;
        this.flushTimer = null;
        this.timers = options.timers;
        this.flushDelayMs = options.flushDelayMs ?? DEFAULT_FLUSH_DELAY_MS;
        this.onFlush = options.onFlush;
    }
    handle(data) {
        if (data.length === 0) {
            return;
        }
        const chunk = Buffer.from(data, "utf8");
        this.chunks.push(chunk);
        this.bytes += chunk.byteLength;
        this.chars += data.length;
        if (!this.flushTimer) {
            this.flushTimer = this.timers.setTimeout(() => {
                this.flushTimer = null;
                this.flush();
            }, this.flushDelayMs);
        }
    }
    flush() {
        this.clearTimer();
        if (this.chunks.length === 0) {
            return;
        }
        const payload = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks, this.bytes);
        const bytes = this.bytes;
        const chars = this.chars;
        this.clearPending();
        this.onFlush({ payload, bytes, chars });
    }
    dispose() {
        this.clearTimer();
        this.clearPending();
    }
    clearTimer() {
        if (!this.flushTimer) {
            return;
        }
        this.timers.clearTimeout(this.flushTimer);
        this.flushTimer = null;
    }
    clearPending() {
        this.chunks = [];
        this.bytes = 0;
        this.chars = 0;
    }
}
//# sourceMappingURL=terminal-output-coalescer.js.map