brf/server/lib/split.ts
2025-11-23 21:44:01 +01:00

37 lines
713 B
TypeScript

const defaultMatcher = /\r?\n/
export type Decoder = {
decode: (chunk?: ArrayBufferView) => void
}
interface Options {
decoder?: Decoder
}
export default function split(matcher: RegExp, { decoder }: Options = {}) {
matcher ??= defaultMatcher
let rest: string | null = 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()
}
},
})
}