import { TransformStream } from 'stream/web' const defaultMatcher = /\r?\n/ export type Decoder = { decode: (chunk: Uint8Array) => string } interface Options { decoder?: Decoder } export default function split(matcher?: RegExp | null, { decoder }: Options = {}) { matcher ??= defaultMatcher let rest: string | null | undefined = null return new TransformStream({ start() {}, transform(chunk, controller) { if (chunk) { if (decoder) { chunk = decoder.decode(chunk) } const lines = ((rest == null ? '' : rest) + chunk).split(matcher) rest = lines.pop() for (const line of lines) { controller.enqueue(line) } } else { controller.terminate() } }, }) }