diff --git a/plugins.md b/plugins.md index 83bb3965..2034382d 100644 --- a/plugins.md +++ b/plugins.md @@ -67,6 +67,7 @@ Fetches a URL with the native API, which doesn't have CORS restrictions. this AP - `status: number` - The response status. - `json: () => Promise` - A function that returns a promise that resolves to the JSON representation of the response body. - `text: () => Promise` - A function that returns a promise that resolves to the text representation of the response body. + - `arrayBuffer: () => Promise` - A function that returns a promise that resolves to the ArrayBuffer representation of the response body. ### `getArg(name: string): string|number` diff --git a/src/ts/globalApi.svelte.ts b/src/ts/globalApi.svelte.ts index 6c7dbe45..225db6c9 100644 --- a/src/ts/globalApi.svelte.ts +++ b/src/ts/globalApi.svelte.ts @@ -1821,6 +1821,7 @@ export async function fetchNative(url:string, arg:{ status: number; json: () => Promise; text: () => Promise; + arrayBuffer: () => Promise; }> { const jsonizer = (body:ReadableStream) => { @@ -1835,6 +1836,27 @@ export async function fetchNative(url:string, arg:{ return text } } + const arrayBufferizer = (body:ReadableStream) => { + return async () => { + const chunks:Uint8Array[] = [] + const reader = body.getReader() + while(true){ + const {done, value} = await reader.read() + if(done){ + break + } + chunks.push(value) + } + const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0) + const arrayBuffer = new Uint8Array(totalLength) + let offset = 0 + for(const chunk of chunks){ + arrayBuffer.set(chunk, offset) + offset += chunk.length + } + return arrayBuffer.buffer + } + } arg.method = arg.method ?? 'POST' @@ -1961,7 +1983,8 @@ export async function fetchNative(url:string, arg:{ headers: new Headers(resHeaders), status: status, json: jsonizer(readableStream), - text: textizer(readableStream) + text: textizer(readableStream), + arrayBuffer: arrayBufferizer(readableStream) } @@ -1988,7 +2011,8 @@ export async function fetchNative(url:string, arg:{ headers: r.headers, status: r.status, json: jsonizer(r.body), - text: textizer(r.body) + text: textizer(r.body), + arrayBuffer: arrayBufferizer(r.body) } } else{