Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

readBoundedDocument.ts

26 lines843 Bytes

1export async function readBoundedDocument(
2 src: string,
3 signal: AbortSignal,
4 limit: number,
5 cache: RequestCache = "default",
6) {
7 const response = await fetch(src, { signal, cache });
8 if (!response.ok || Number(response.headers.get("content-length")) > limit)
9 throw new Error("This file is unavailable or too large to preview.");
10 const reader = response.body?.getReader();
11 if (!reader) throw new Error("This file is unavailable.");
12 const chunks: Uint8Array<ArrayBuffer>[] = [];
13 let size = 0;
14 try {
15 while (true) {
16 const { done, value } = await reader.read();
17 if (done) break;
18 size += value.length;
19 if (size > limit) throw new Error("This file is too large to preview.");
20 chunks.push(value);
21 }
22 } finally {
23 await reader.cancel();
24 }
25 return new Blob(chunks).arrayBuffer();