This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathworker.js
66 lines (56 loc) · 2.52 KB
/
worker.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
import EventEmitter from "./events.js";
import HookEvent from "./hook.js";
class Workers extends EventEmitter {
constructor(ctx) {
super();
this.ctx = ctx;
this.window = ctx.window;
this.Worker = this.window.Worker || {};
this.Worklet = this.window.Worklet || {};
this.workletProto = this.Worklet.prototype || {};
this.workerProto = this.Worker.prototype || {};
this.postMessage = this.workerProto.postMessage;
this.terminate = this.workerProto.terminate;
this.addModule = this.workletProto.addModule;
};
overrideWorker() {
this.ctx.override(this.window, 'Worker', (target, that, args) => {
if (!args.length) return new target(...args);
let [ url, options = {} ] = args;
const event = new HookEvent({ url, options }, target, that);
this.emit('worker', event);
if (event.intercepted) return event.returnValue;
return new event.target(...[ event.data.url, event.data.options ]);
}, true);
};
overrideAddModule() {
this.ctx.override(this.workletProto, 'addModule', (target, that, args) => {
if (!args.length) return target.apply(that, args);
let [ url, options = {} ] = args;
const event = new HookEvent({ url, options }, target, that);
this.emit('addModule', event);
if (event.intercepted) return event.returnValue;
return event.target.call(event.that, event.data.url, event.data.options);
});
};
overridePostMessage() {
this.ctx.override(this.workerProto, 'postMessage', (target, that, args) => {
if (!args.length) return target.apply(that, args);
let [ message, transfer = [] ] = args;
const event = new HookEvent({ message, transfer }, target, that);
this.emit('postMessage', event);
if (event.intercepted) return event.returnValue;
return event.target.call(event.that, event.data.message, event.data.transfer);
});
};
overrideImportScripts() {
this.ctx.override(this.window, 'importScripts', (target, that, scripts) => {
if (!scripts.length) return target.apply(that, scripts);
const event = new HookEvent({ scripts }, target, that);
this.emit('importScripts', event);
if (event.intercepted) return event.returnValue;
return event.target.apply(event.that, event.data.scripts);
});
};
};
export default Workers;