|
2 | 2 |
|
3 | 3 | import { BODY_TYPES } from "./consts.ts"; |
4 | 4 |
|
5 | | -interface Reader { |
6 | | - read(p: Uint8Array): Promise<number | null>; |
7 | | -} |
8 | | - |
9 | | -interface Closer { |
10 | | - close(): void; |
11 | | -} |
12 | | - |
13 | | -interface ReadableStreamFromReaderOptions { |
14 | | - /** If the `reader` is also a `Closer`, automatically close the `reader` |
15 | | - * when `EOF` is encountered, or a read error occurs. |
16 | | - * |
17 | | - * Defaults to `true`. */ |
18 | | - autoClose?: boolean; |
19 | | - |
20 | | - /** The size of chunks to allocate to read, the default is ~16KiB, which is |
21 | | - * the maximum size that Deno operations can currently support. */ |
22 | | - chunkSize?: number; |
23 | | - |
24 | | - /** The queuing strategy to create the `ReadableStream` with. */ |
25 | | - strategy?: { highWaterMark?: number | undefined; size?: undefined }; |
26 | | -} |
27 | | - |
28 | | -function isCloser(value: unknown): value is Deno.Closer { |
29 | | - return typeof value === "object" && value != null && "close" in value && |
30 | | - // deno-lint-ignore no-explicit-any |
31 | | - typeof (value as Record<string, any>)["close"] === "function"; |
32 | | -} |
33 | | - |
34 | | -const DEFAULT_CHUNK_SIZE = 16_640; // 17 Kib |
35 | | - |
36 | 5 | const encoder = new TextEncoder(); |
37 | 6 |
|
38 | | -/** |
39 | | - * Create a `ReadableStream<Uint8Array>` from a `Reader`. |
40 | | - * |
41 | | - * When the pull algorithm is called on the stream, a chunk from the reader |
42 | | - * will be read. When `null` is returned from the reader, the stream will be |
43 | | - * closed along with the reader (if it is also a `Closer`). |
44 | | - */ |
45 | | -export function readableStreamFromReader( |
46 | | - reader: Reader | (Reader & Closer), |
47 | | - options: ReadableStreamFromReaderOptions = {}, |
48 | | -): ReadableStream<Uint8Array> { |
49 | | - const { |
50 | | - autoClose = true, |
51 | | - chunkSize = DEFAULT_CHUNK_SIZE, |
52 | | - strategy, |
53 | | - } = options; |
54 | | - |
55 | | - return new ReadableStream({ |
56 | | - async pull(controller) { |
57 | | - const chunk = new Uint8Array(chunkSize); |
58 | | - try { |
59 | | - const read = await reader.read(chunk); |
60 | | - if (read === null) { |
61 | | - if (isCloser(reader) && autoClose) { |
62 | | - reader.close(); |
63 | | - } |
64 | | - controller.close(); |
65 | | - return; |
66 | | - } |
67 | | - controller.enqueue(chunk.subarray(0, read)); |
68 | | - } catch (e) { |
69 | | - controller.error(e); |
70 | | - if (isCloser(reader)) { |
71 | | - reader.close(); |
72 | | - } |
73 | | - } |
74 | | - }, |
75 | | - cancel() { |
76 | | - if (isCloser(reader) && autoClose) { |
77 | | - reader.close(); |
78 | | - } |
79 | | - }, |
80 | | - }, strategy); |
81 | | -} |
82 | | - |
83 | 7 | /** |
84 | 8 | * Create a `ReadableStream<Uint8Array>` from an `AsyncIterable`. |
85 | 9 | */ |
|
0 commit comments