2023-08-23 17:08:21 +00:00
|
|
|
import { init } from "https://esm.sh/v131/node_events.js";
|
2023-05-23 18:53:53 +00:00
|
|
|
import type {
|
|
|
|
ProxyFetchRequest,
|
|
|
|
ProxyFetchResponse,
|
|
|
|
} from "../../common/proxy_fetch.ts";
|
2023-08-23 17:08:21 +00:00
|
|
|
import {
|
|
|
|
base64Decode,
|
|
|
|
base64Encode,
|
|
|
|
} from "../../plugos/asset_bundle/base64.ts";
|
2023-01-08 11:24:12 +00:00
|
|
|
|
2023-08-23 17:08:21 +00:00
|
|
|
export async function sandboxFetch(
|
|
|
|
reqInfo: RequestInfo,
|
2023-05-23 18:53:53 +00:00
|
|
|
options?: ProxyFetchRequest,
|
|
|
|
): Promise<ProxyFetchResponse> {
|
2023-08-23 17:08:21 +00:00
|
|
|
if (typeof reqInfo !== "string") {
|
|
|
|
// Request as first argument, let's deconstruct it
|
|
|
|
// console.log("fetch", reqInfo);
|
|
|
|
options = {
|
|
|
|
method: reqInfo.method,
|
|
|
|
headers: Object.fromEntries(reqInfo.headers.entries()),
|
|
|
|
base64Body: reqInfo.body
|
|
|
|
? base64Encode(
|
|
|
|
new Uint8Array(await (new Response(reqInfo.body)).arrayBuffer()),
|
|
|
|
)
|
|
|
|
: undefined,
|
|
|
|
};
|
|
|
|
reqInfo = reqInfo.url;
|
|
|
|
}
|
2023-01-08 11:24:12 +00:00
|
|
|
// @ts-ignore: monkey patching fetch
|
2023-08-23 17:08:21 +00:00
|
|
|
return syscall("sandboxFetch.fetch", reqInfo, options);
|
2023-01-08 11:24:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function monkeyPatchFetch() {
|
2023-07-02 09:25:32 +00:00
|
|
|
// @ts-ignore: monkey patching fetch
|
|
|
|
globalThis.nativeFetch = globalThis.fetch;
|
2023-01-08 11:24:12 +00:00
|
|
|
// @ts-ignore: monkey patching fetch
|
|
|
|
globalThis.fetch = async function (
|
2023-08-23 17:08:21 +00:00
|
|
|
reqInfo: RequestInfo,
|
2023-01-08 11:24:12 +00:00
|
|
|
init?: RequestInit,
|
|
|
|
): Promise<Response> {
|
|
|
|
const r = await sandboxFetch(
|
2023-08-23 17:08:21 +00:00
|
|
|
reqInfo,
|
2023-01-08 11:24:12 +00:00
|
|
|
init && {
|
|
|
|
method: init.method,
|
|
|
|
headers: init.headers as Record<string, string>,
|
2023-08-23 17:08:21 +00:00
|
|
|
base64Body: init.body
|
|
|
|
? base64Encode(
|
|
|
|
new Uint8Array(await (new Response(init.body)).arrayBuffer()),
|
|
|
|
)
|
|
|
|
: undefined,
|
2023-01-08 11:24:12 +00:00
|
|
|
},
|
|
|
|
);
|
2023-01-08 21:38:54 +00:00
|
|
|
return new Response(r.base64Body ? base64Decode(r.base64Body) : null, {
|
2023-01-08 11:24:12 +00:00
|
|
|
status: r.status,
|
|
|
|
headers: r.headers,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|