2018-10-04 17:03:40 +00:00
|
|
|
/* global promisify */
|
2018-10-04 04:46:19 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const API = (() => {
|
2018-10-05 10:47:52 +00:00
|
|
|
const preparing = chrome.runtime.getBackgroundPage ?
|
|
|
|
promisify(chrome.runtime.getBackgroundPage.bind(chrome.runtime))()
|
|
|
|
.catch(() => null) :
|
|
|
|
Promise.resolve(null);
|
2018-10-04 04:46:19 +00:00
|
|
|
const runtimeSendMessage = promisify(chrome.runtime.sendMessage.bind(chrome.runtime));
|
|
|
|
return new Proxy(() => {}, {
|
|
|
|
get: (target, name) =>
|
|
|
|
(...args) => invokeBG(name, args),
|
|
|
|
});
|
|
|
|
|
|
|
|
function sendMessage(msg) {
|
|
|
|
return runtimeSendMessage(msg)
|
|
|
|
.then(result => {
|
2018-10-04 17:03:40 +00:00
|
|
|
if (result && result.__ERROR__) {
|
2018-10-04 04:46:19 +00:00
|
|
|
throw new Error(result.__ERROR__);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function invokeBG(name, args) {
|
|
|
|
return preparing.then(BG => {
|
|
|
|
if (!BG) {
|
|
|
|
return sendMessage({
|
|
|
|
method: 'invokeAPI',
|
|
|
|
name,
|
|
|
|
args
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// FIXME: why deep-copying input/output?
|
|
|
|
if (BG !== window) {
|
|
|
|
args = BG.deepCopy(args);
|
|
|
|
}
|
2018-10-04 17:03:40 +00:00
|
|
|
const fn = BG.API_METHODS[name];
|
|
|
|
if (!fn) {
|
|
|
|
throw new Error(`unknown API method: ${name}`);
|
|
|
|
}
|
|
|
|
return Promise.resolve(fn(...args))
|
2018-10-04 04:46:19 +00:00
|
|
|
.then(BG.deepCopy);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
})();
|