Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing worker as blob #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 65 additions & 6 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { dirname, join } from "https://deno.land/[email protected]/path/mod.ts";

type AsyncFunction<S extends unknown[], T> = (...params: S) => Promise<T>;
type MaybeAsyncFunction<S extends unknown[], T> = (
...params: S
Expand Down Expand Up @@ -85,10 +83,7 @@ export const parry: Parry = <S extends unknown[], T extends unknown>(
];
} = {};

const worker = new Worker(
join(dirname(import.meta.url), "worker.js"), // Allows the Worker to be run both locally and imported from an URL
{ type: "module", deno },
);
const worker = new Worker(URL.createObjectURL(new Blob([`(${expose.toString()})()`])), { type: "module" });

worker.onmessage = (event) => {
const { type, id, data } = event.data; // All parry Worker messages use this object structure
Expand Down Expand Up @@ -227,4 +222,68 @@ parry.close = (): void => {
}
};

function expose() {
let __func = () => {};
self.onmessage = (event) => {
const { type, id, data } = event.data;
switch (type) {
case "set":
__func = new Function(`return ${data};`)();
break;
case "call": {
Promise.resolve(data)
.then((v) => __func.apply(null, v))
.then(
(resolved) =>
self.postMessage({
type: "resolve",
id,
data: resolved,
}),
(rejected) =>
self.postMessage({
type: "reject",
id,
data: rejected,
}),
);
break;
}
case "run": {
const r = new Function(`return ${data.func};`)();
Promise.resolve(data.params)
.then((v) => r.apply(null, v))
.then(
(resolved) => {
self.postMessage({
type: "resolve",
id,
data: resolved,
});
},
(rejected) =>
self.postMessage({
type: "reject",
id,
data: rejected,
}),
);
break;
}
case "declare":
self[data.ident] = data.value;
break;
case "define":
self[data.ident] = new Function(`return ${data.func};`)();
break;
default:
self.postMessage({
type: "error",
data: "Unknown message type",
});
break;
}
};
}

export default parry;
61 changes: 0 additions & 61 deletions worker.js

This file was deleted.