2023-04-12 14:08:55 +00:00
|
|
|
/** Set the receiver function for a worker */
|
2023-04-19 23:14:30 +00:00
|
|
|
export function workerExport(handlers: Record<string, (...data: any) => Promise<any>>): void {
|
2023-04-12 14:08:55 +00:00
|
|
|
/** Promise API for web worker */
|
2023-04-19 02:19:05 +00:00
|
|
|
self.onmessage = async ({
|
|
|
|
data,
|
|
|
|
}: {
|
|
|
|
data: {
|
|
|
|
id: number;
|
|
|
|
name: string;
|
|
|
|
args: any[];
|
|
|
|
};
|
|
|
|
}) => {
|
2023-04-12 14:08:55 +00:00
|
|
|
try {
|
|
|
|
const handler = handlers[data.name];
|
|
|
|
if (!handler) throw new Error(`No handler for type ${data.name}`);
|
|
|
|
const res = await handler.apply(self, data.args);
|
|
|
|
self.postMessage({
|
|
|
|
id: data.id,
|
|
|
|
resolve: res,
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
self.postMessage({
|
|
|
|
id: data.id,
|
|
|
|
reject: e.message,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get the CALL function for a worker. Call this only once. */
|
|
|
|
export function workerImporter(worker: Worker) {
|
2023-04-19 02:19:05 +00:00
|
|
|
const promises = new Map<number, { resolve: any; reject: any }>();
|
|
|
|
|
2023-04-12 14:08:55 +00:00
|
|
|
worker.onmessage = ({ data }: { data: any }) => {
|
|
|
|
const { id, resolve, reject } = data;
|
2023-04-19 02:19:05 +00:00
|
|
|
if (resolve) promises.get(id)?.resolve(resolve);
|
|
|
|
if (reject) promises.get(id)?.reject(reject);
|
|
|
|
promises.delete(id);
|
2023-04-12 14:08:55 +00:00
|
|
|
};
|
2023-04-19 02:19:05 +00:00
|
|
|
|
|
|
|
type PromiseFun = (...args: any) => Promise<any>;
|
|
|
|
return function importer<F extends PromiseFun>(name: string) {
|
|
|
|
return async function fun(...args: Parameters<F>) {
|
|
|
|
return await new Promise<ReturnType<Awaited<F>>>((resolve, reject) => {
|
2023-04-12 14:08:55 +00:00
|
|
|
const id = Math.random();
|
2023-04-19 02:19:05 +00:00
|
|
|
promises.set(id, { resolve, reject });
|
2023-04-12 14:08:55 +00:00
|
|
|
worker.postMessage({ id, name, args });
|
|
|
|
});
|
2023-04-19 02:19:05 +00:00
|
|
|
};
|
2023-04-12 14:08:55 +00:00
|
|
|
};
|
|
|
|
}
|