-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathworker.ts
More file actions
172 lines (142 loc) · 3.92 KB
/
worker.ts
File metadata and controls
172 lines (142 loc) · 3.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// deno-lint-ignore-file no-explicit-any
import { deferred, type Deferred } from "../compat/runtime/async.ts";
import { inspect } from "../compat/runtime/inspect.ts";
/**
* Deco labs: 🐁🐁🐁
*
* This module is heavily inspired by Google's comlink:
* https://github.com/GoogleChromeLabs/comlink
*
* This script exposes any other file via web worker with an enjoyable
* functions/promises interface. No more nasty postMessages!
*/
// @ts-expect-error https://stackoverflow.com/questions/7931182/reliably-detect-if-the-script-is-executing-in-a-web-worker
const IS_WORKER = typeof WorkerGlobalScope !== "undefined" &&
// @ts-expect-error https://stackoverflow.com/questions/7931182/reliably-detect-if-the-script-is-executing-in-a-web-worker
self instanceof WorkerGlobalScope;
type WorkerEvent = {
type: "setup";
payload: string;
} | {
type: "invoke";
payload: {
fn: string;
args: any[];
id: string;
};
};
type MasterEvent = {
type: "setup:fulfill";
payload: string[];
} | {
type: "setup:reject";
payload: string;
} | {
type: "invoke:fulfill";
payload: {
id: string;
return: unknown;
};
} | {
type: "invoke:reject";
payload: {
id: string;
reason: string;
};
};
export const createWorker = (
url: URL,
options?: WorkerOptions | undefined,
): Promise<any> => {
const setup = deferred();
const worker = new Worker(new URL(import.meta.url), options);
const invokes = new Map<string, Deferred<unknown>>([]);
worker.postMessage({ type: "setup", payload: url.href });
worker.addEventListener("message", (event: MessageEvent<MasterEvent>) => {
const { type, payload } = event.data;
switch (type) {
case "setup:fulfill": {
const mod = payload.reduce((acc, curr) => {
acc[curr] = (...args: any[]) => {
const run = deferred<void>();
const id = crypto.randomUUID();
invokes.set(id, run);
worker.postMessage({
type: "invoke",
payload: {
fn: curr,
args,
id,
},
});
return run;
};
return acc;
}, {} as Record<string, any>);
// Use using/Symbol.dispose once Deno accepts TypeScript 5.2
mod.dispose = () => worker.terminate();
setup.resolve(mod);
return;
}
case "setup:reject": {
setup.reject(payload);
return;
}
case "invoke:fulfill": {
const { id, return: response } = payload;
invokes.get(id)?.resolve(response);
invokes.delete(id);
return;
}
case "invoke:reject": {
const { id, reason } = payload;
invokes.get(id)?.reject(reason);
invokes.delete(id);
return;
}
}
});
return setup;
};
if (IS_WORKER) {
let mod: Record<string, any> = {};
addEventListener("message", async (event: MessageEvent<WorkerEvent>) => {
const { type, payload } = event.data;
switch (type) {
case "invoke": {
const { fn, args, id } = payload;
if (typeof mod[fn] !== "function") {
throw new Error(`function ${fn} not exported by worker`);
}
try {
const response = await mod[fn](...args);
self.postMessage({
type: "invoke:fulfill",
payload: { id, return: response },
});
} catch (error) {
self.postMessage({
type: "invoke:reject",
payload: { id, reason: inspect(error) },
});
}
return;
}
case "setup": {
try {
mod = await import(payload);
self.postMessage({
type: "setup:fulfill",
payload: Object.keys(mod),
});
} catch (error) {
self.postMessage({
type: "setup:reject",
payload: inspect(error),
});
}
return;
}
}
});
}