diff --git a/src/client/shared/worker.ts b/src/client/shared/worker.ts index 0920a2f..a5c58b9 100644 --- a/src/client/shared/worker.ts +++ b/src/client/shared/worker.ts @@ -6,7 +6,18 @@ export default function (client: ScramjetClient, self: typeof globalThis) { construct({ args }) { if (args[0] instanceof URL) args[0] = args[0].href; if (args[0].startsWith("blob:") || args[0].startsWith("data:")) { - // TODO + if (args[0].startsWith("blob:")) { + args[0] = + "data:application/javascript;base64," + btoa(syncfetch(args[0])); + } + + args[0] = "/scramjet/worker?data=" + args[0]; + if (args[1] && args[1].type === "module") { + args[0] += "&type=module"; + } + + args[0] += "&origin=" + encodeURIComponent(client.url.origin); + return; } @@ -18,3 +29,11 @@ export default function (client: ScramjetClient, self: typeof globalThis) { }, }); } + +function syncfetch(url: string) { + const xhr = new XMLHttpRequest(); + xhr.open("GET", url, false); + xhr.send(); + + return xhr.responseText; +} diff --git a/src/worker/fetch.ts b/src/worker/fetch.ts index 90a7f6e..842bc5e 100644 --- a/src/worker/fetch.ts +++ b/src/worker/fetch.ts @@ -13,6 +13,28 @@ export async function swfetch( this: ScramjetServiceWorker, { request }: FetchEvent ) { + if (new URL(request.url).pathname.startsWith("/scramjet/worker")) { + const dataurl = new URL(request.url).searchParams.get("data"); + const res = await fetch(dataurl); + const ab = await res.arrayBuffer(); + + const ismodule = new URL(request.url).searchParams.get("type") === "module"; + + const origin = new URL( + decodeURIComponent(new URL(request.url).searchParams.get("origin")) + ); + + if (ismodule) origin.searchParams.set("type", "module"); + + const rewritten = rewriteWorkers(ab, new URL(origin)); + + return new Response(rewritten, { + headers: { + "Content-Type": "application/javascript", + }, + }); + } + const urlParam = new URLSearchParams(new URL(request.url).search); if (urlParam.has("url")) {