-
Notifications
You must be signed in to change notification settings - Fork 4
/
worker-no-support.js
94 lines (74 loc) · 2 KB
/
worker-no-support.js
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
import {
forwardEvents,
createWorkerClass,
findWorkerId
} from './shared-utils.js';
import {
addPropertyListener,
setupWorkerScope,
generateId,
parseWorkerArgs
} from './worker-utils.js';
import { terminate, createWorker, CONNECT, ERROR } from './messages.js';
const workers = {};
const commands = {
[CONNECT]({ id, port }) {
forwardEvents(port, workers[id]._port);
},
[ERROR]({ id, event }) {
workers[id]._port.dispatchEvent(Object.assign(new Event('error'), event));
}
};
function setupScope({ postMessage, addEventListener, close }) {
const port = setupWorkerScope({ postMessage });
// Add self to list of workers
workers[0] = { _port: port };
// Listen for messages from parent
addEventListener('message', ({ data }) => {
commands[data.type](data);
});
Object.assign(self, {
close() {
// Terminate subworkers
Object.keys(workers).forEach(id => postMessage(...terminate({ id })));
// Tell window to forget about self
postMessage(...terminate({ id: 0 }));
// Close self
close();
}
});
}
function setupWorker({ postMessage }) {
const BaseClass = createWorkerClass(class {
constructor(port, ...args) {
const parsedArgs = parseWorkerArgs(...args);
const id = generateId();
workers[id] = this;
postMessage(...createWorker({ id, port, args: parsedArgs }));
}
terminate() {
const id = findWorkerId(workers, this);
workers[id] = undefined;
postMessage(...terminate({ id }));
}
set onerror(value) {
this._port.onerror = value;
}
get onerror() {
return this._port.onerror;
}
});
// `addPropertyListener` needs to run after `this._port` has been set,
// hence the aditional class.
self.Worker = class Worker extends BaseClass {
constructor(...args) {
super(...args);
// Add `onerror` property listener
addPropertyListener(this._port, 'error');
}
};
}
export default () => {
setupWorker(self);
setupScope(self);
};