/
_messaging.js
96 lines (78 loc) · 2.2 KB
/
_messaging.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
95
96
export function createMessageHandler(_sendMessage) {
const listeners = new Map();
const interceptors = new Map();
const waiting = new Map();
let transaction = 0;
function addListener(type, callback) {
if (listeners.has(type)) {
throw new Error(`Listener for "${type}" already exists.`);
}
listeners.set(type, callback);
}
function addInterceptor(type, callback) {
if (interceptors.has(type)) {
throw new Error(`Interceptor for "${type}" already exists.`);
}
interceptors.set(type, callback);
}
function sendMessage(type, data, context) {
if (interceptors.has(type)) {
return (async () => {
try {
return await interceptors.get(type)(data, context);
} catch (e) {
throw new Error(`Error in "${type}" interceptor: ${e.message || e}`);
}
})();
}
++transaction;
_sendMessage(type, { data, transaction }, context);
return new Promise((resolve, reject) => waiting.set(transaction, { resolve, reject }));
}
function _handleMessage(type, { data, transaction, error, isResponse }, context) {
if (isResponse) {
if (!waiting.has(transaction)) {
throw new Error(`No "${type}" response handler (transaction ${transaction}) - this should never happen.`);
}
const handler = waiting.get(transaction);
waiting.delete(transaction);
if (error) {
handler.reject(new Error(`Error in target's "${type}" handler: ${error}`));
} else {
handler.resolve(data);
}
return false;
}
if (!listeners.has(type)) {
throw new Error(`Unrecognised message type: ${type}`);
}
function sendResponse({ data, error }) {
_sendMessage(type, { data, transaction, error, isResponse: true }, context);
}
let response;
try {
response = listeners.get(type)(data, context);
} catch (e) {
sendResponse({ error: e.message || e });
throw e;
}
if (response instanceof Promise) {
response
.then(data => sendResponse({ data }))
.catch(e => {
sendResponse({ error: e.message || e });
throw e;
});
// true = response will be handled asynchronously (needed for Chrome)
return true;
}
sendResponse({ data: response });
return false;
}
return {
_handleMessage,
sendMessage,
addListener,
addInterceptor,
};
}