import { Transform, Writable, type TransformCallback, type WritableOptions } from "stream"; import { StringDecoder } from "string_decoder"; export type TailHandler = (line: string) => void; export class HandlerWriter extends Writable { private handler: any; private decoder: StringDecoder; private data: string; constructor(handler: TailHandler, options?: WritableOptions) { if (!options) options = {}; options.objectMode = true; super(options); this.handler = handler; this.decoder = new StringDecoder(options?.defaultEncoding); this.data = ""; } _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void { chunk = this.decoder.write(chunk); for (const line of chunk.split("\n")) { if (line.length) { this.handler(line); } } this.data += chunk; callback(); } _final(callback: (error?: Error | null) => void): void { this.data += this.decoder.end(); callback(); } } export class TailTransform extends Transform { constructor(private handler: TailHandler) { super({ objectMode: true }); } _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void { if (chunk.contents && chunk.contents.pipe) { chunk.contents.pipe(new HandlerWriter(this.handler)); } this.push(chunk); callback(); } } export const tail = (handler: TailHandler) => new TailTransform(handler);