1 import type { ReadableStreamDefaultReadResult } from 'web-streams-polyfill';
2 import { ReadableStream, TransformStream } from 'web-streams-polyfill';
4 export const untilStreamEnd = async <T>(stream: ReadableStream<T>, action?: (data: T) => Promise<void>) => {
5 const reader = stream.getReader();
7 const processResponse = async (result: ReadableStreamDefaultReadResult<T>): Promise<any> => {
12 await action?.(result.value);
14 return processResponse(await reader.read());
17 return processResponse(await reader.read());
20 export const streamToBuffer = async (stream: ReadableStream<Uint8Array>) => {
21 const chunks: Uint8Array[] = [];
22 await untilStreamEnd(stream, async (chunk) => {
28 export const bufferToStream = (buffer: Uint8Array[]): ReadableStream<Uint8Array> => {
29 return new ReadableStream({
31 buffer.forEach((chunk) => controller.enqueue(chunk));
37 export class ObserverStream extends TransformStream<Uint8Array, Uint8Array> {
38 constructor(fn?: (chunk: Uint8Array) => void) {
40 transform(chunk, controller) {
42 controller.enqueue(chunk);