37 lines
713 B
TypeScript
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()
|
|
}
|
|
},
|
|
})
|
|
}
|