Fix OpenScript.fetch JSON IPC serialization for text and binary

This commit is contained in:
2026-09-13 14:03:29 -07:00
parent da135d506a
commit a0f8160302
7 changed files with 102 additions and 13 deletions
+17 -1
View File
@@ -1,9 +1,25 @@
const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
const toBase64 = buffer => {
const bytes = new Uint8Array(buffer);
let bin = '';
for (let i = 0; i < bytes.byteLength; i += 8192) {
bin += String.fromCharCode(...bytes.subarray(i, Math.min(i + 8192, bytes.byteLength)));
}
return btoa(bin);
};
export const runScriptFetch = async (url, options = {}) => {
const res = await fetch(url, options);
const { status, statusText } = res;
const headers = [...res.headers.entries()];
const body = NULL_BODY_STATUSES.has(status) ? null : await res.arrayBuffer();
if (NULL_BODY_STATUSES.has(status)) {
return { status, statusText, headers, url: res.url, body: null };
}
if (['arraybuffer', 'blob'].includes(options?.responseType)) {
const buffer = await res.arrayBuffer();
return { status, statusText, headers, url: res.url, base64: toBase64(buffer) };
}
const body = await res.text();
return { status, statusText, headers, url: res.url, body };
};
+11 -1
View File
@@ -42,7 +42,17 @@ ${code}
type: '${FETCH_MESSAGE}', url: url.toString(), options: { ...rest, headers, body },
});
if (!response?.ok) throw new TypeError(response?.error || 'OpenScript fetch failed');
const resBody = [101, 204, 205, 304].includes(response.status) ? null : response.body;
let resBody = null;
if (![101, 204, 205, 304].includes(response.status)) {
if (response.base64 !== undefined) {
const bin = atob(response.base64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
resBody = bytes.buffer;
} else {
resBody = response.body ?? null;
}
}
const res = new Response(resBody, {
status: response.status, statusText: response.statusText, headers: response.headers,
});
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '1.0.4';
export const VERSION = '1.0.5';