-
Notifications
You must be signed in to change notification settings - Fork 8
/
extapi.js
85 lines (69 loc) · 2.34 KB
/
extapi.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
(function() {
var messageQueue = {};
var readyCallbacks = [];
var commandCallbacks = {};
self.attoX = {
onReady: function(callback) {
readyCallbacks.push(callback);
}
};
function _call(command, ...args) {
return new Promise(function(resolve, reject) {
var id = Math.random();
self.postMessage({
type: "call",
id,
command,
args: args.map(function(arg) {
try {
return JSON.parse(JSON.stringify(arg));
} catch (e) {
return undefined;
}
})
});
var interval = setInterval(function() {
if (messageQueue[id]?.type == "reply") {
(messageQueue[id].status == "reject" ? reject : resolve)(messageQueue[id].data);
delete messageQueue[id];
clearInterval(interval);
}
});
});
}
function onReady(callback) {
callback();
}
function registerCommand(command, callback) {
commandCallbacks[command] = callback;
self.postMessage({
type: "registerCommand",
command
});
}
self.addEventListener("message", function(event) {
if (event.data.type == "commandExecution") {
(commandCallbacks[event.data.command](...event.data.args) || Promise.resolve()).then(function() {
_call("_finishExecution", null);
}).catch(function(error) {
_call("_finishExecution", error);
});
}
if (event.data.type == "reply") {
messageQueue[event.data.id] = event.data;
}
});
return _call("_getApiCommandList").then(function(commandList) {
var commands = {};
commandList.forEach(function(command) {
commands[command] = function() {
return _call(command, ...arguments);
};
});
return Promise.resolve({attoX: {_call, onReady, registerCommand, ...commands}, readyCallbacks});
});
})().then(function({attoX, readyCallbacks}) {
self.attoX = Object.freeze(attoX);
readyCallbacks.forEach((callback) => callback());
})
// Start of extension code