stylus/js/msg.js

330 lines
8.4 KiB
JavaScript
Raw Normal View History

2018-10-05 19:19:51 +00:00
/* global promisify deepCopy */
2018-10-10 16:54:38 +00:00
/* exported msg API */
2018-10-05 20:39:48 +00:00
// deepCopy is only used if the script is executed in extension pages.
2018-10-05 19:10:04 +00:00
'use strict';
const msg = (() => {
let isBg = false;
if (chrome.extension.getBackgroundPage && chrome.extension.getBackgroundPage() === window) {
isBg = true;
window._msg = {
id: 1,
2018-10-06 07:11:01 +00:00
storage: new Map(),
2018-10-12 08:39:47 +00:00
handler: null,
clone: deepCopy
2018-10-05 19:10:04 +00:00
};
}
const runtimeSend = promisify(chrome.runtime.sendMessage.bind(chrome.runtime));
const tabSend = chrome.tabs && promisify(chrome.tabs.sendMessage.bind(chrome.tabs));
const tabQuery = chrome.tabs && promisify(chrome.tabs.query.bind(chrome.tabs));
let bg;
const preparing = !isBg && chrome.runtime.getBackgroundPage &&
promisify(chrome.runtime.getBackgroundPage.bind(chrome.runtime))()
.catch(() => null)
.then(_bg => {
bg = _bg;
});
bg = isBg ? window : !preparing ? null : undefined;
const EXTENSION_URL = chrome.runtime.getURL('');
let handler;
const from_ = location.href.startsWith(EXTENSION_URL) ? 'extension' : 'content';
const RX_NO_RECEIVER = /Receiving end does not exist/;
const RX_PORT_CLOSED = /The message port closed before a response was received/;
2018-10-05 19:10:04 +00:00
return {
send,
sendTab,
2018-10-06 03:43:42 +00:00
sendBg,
2018-10-05 19:10:04 +00:00
broadcast,
broadcastTab,
2018-10-06 10:10:47 +00:00
broadcastExtension,
2018-10-13 15:57:45 +00:00
ignoreError,
2018-10-06 03:43:42 +00:00
on,
onTab,
2018-10-06 05:02:45 +00:00
onExtension,
off,
RX_NO_RECEIVER,
RX_PORT_CLOSED
2018-10-05 19:10:04 +00:00
};
function send(data, target = 'extension') {
if (bg === undefined) {
return preparing.then(() => send(data, target));
}
const message = {type: 'direct', data, target, from: from_};
if (bg) {
exchangeSet(message);
}
const request = runtimeSend(message).then(unwrapData);
if (message.id) {
return withCleanup(request, () => bg._msg.storage.delete(message.id));
}
return request;
}
function sendTab(tabId, data, options, target = 'tab') {
return tabSend(tabId, {type: 'direct', data, target, from: from_}, options)
.then(unwrapData);
}
2018-10-06 03:43:42 +00:00
function sendBg(data) {
2018-10-06 07:11:01 +00:00
if (bg === undefined) {
return preparing.then(doSend);
}
return withPromiseError(doSend);
2018-10-06 03:43:42 +00:00
function doSend() {
if (bg) {
if (!bg._msg.handler) {
throw new Error('there is no bg handler');
}
const handlers = bg._msg.handler.extension.concat(bg._msg.handler.both);
2018-10-12 08:39:47 +00:00
// in FF, the object would become a dead object when the window
// is closed, so we have to clone the object into background.
return Promise.resolve(executeCallbacks(handlers, bg._msg.clone(data), {url: location.href}))
2018-10-06 03:43:42 +00:00
.then(deepCopy);
}
return send(data);
}
}
2018-10-13 15:57:45 +00:00
function ignoreError(err) {
2018-10-10 15:05:20 +00:00
if (err.message && (
RX_NO_RECEIVER.test(err.message) ||
RX_PORT_CLOSED.test(err.message)
2018-10-10 15:05:20 +00:00
)) {
return;
}
console.warn(err);
}
2018-10-05 19:10:04 +00:00
function broadcast(data, filter) {
return Promise.all([
2018-10-13 15:57:45 +00:00
send(data, 'both').catch(ignoreError),
2018-10-05 19:10:04 +00:00
broadcastTab(data, filter, null, true, 'both')
]);
}
function broadcastTab(data, filter, options, ignoreExtension = false, target = 'tab') {
return tabQuery({})
2018-10-06 05:27:58 +00:00
// TODO: send to activated tabs first?
2018-10-05 19:10:04 +00:00
.then(tabs => {
const requests = [];
for (const tab of tabs) {
const isExtension = tab.url.startsWith(EXTENSION_URL);
if (
2018-10-06 05:02:45 +00:00
tab.discarded ||
2018-10-06 05:27:58 +00:00
// FIXME: use `URLS.supported`?
2018-10-05 19:10:04 +00:00
!/^(http|ftp|file)/.test(tab.url) &&
!tab.url.startsWith('chrome://newtab/') &&
!isExtension ||
isExtension && ignoreExtension ||
2018-10-10 08:14:51 +00:00
filter && !filter(tab)
2018-10-05 19:10:04 +00:00
) {
continue;
}
const dataObj = typeof data === 'function' ? data(tab) : data;
if (!dataObj) {
continue;
}
const message = {type: 'direct', data: dataObj, target, from: from_};
if (isExtension) {
exchangeSet(message);
}
2018-10-11 17:11:17 +00:00
let request = tabSend(tab.id, message, options).then(unwrapData);
2018-10-05 19:10:04 +00:00
if (message.id) {
request = withCleanup(request, () => bg._msg.storage.delete(message.id));
}
2018-10-13 15:57:45 +00:00
requests.push(request.catch(ignoreError));
2018-10-05 19:10:04 +00:00
}
return Promise.all(requests);
});
}
2018-10-06 10:10:47 +00:00
function broadcastExtension(...args) {
2018-10-13 15:57:45 +00:00
return send(...args).catch(ignoreError);
2018-10-06 10:10:47 +00:00
}
2018-10-06 03:43:42 +00:00
function on(fn) {
2018-10-05 19:10:04 +00:00
initHandler();
handler.both.push(fn);
}
2018-10-06 03:43:42 +00:00
function onTab(fn) {
2018-10-05 19:10:04 +00:00
initHandler();
handler.tab.push(fn);
}
2018-10-06 03:43:42 +00:00
function onExtension(fn) {
2018-10-05 19:10:04 +00:00
initHandler();
handler.extension.push(fn);
}
2018-10-06 05:02:45 +00:00
function off(fn) {
for (const type of ['both', 'tab', 'extension']) {
const index = handler[type].indexOf(fn);
if (index >= 0) {
handler[type].splice(index, 1);
}
}
}
2018-10-05 19:10:04 +00:00
function initHandler() {
if (handler) {
return;
}
2018-10-06 07:11:01 +00:00
handler = {
2018-10-05 19:10:04 +00:00
both: [],
tab: [],
extension: []
};
2018-10-06 07:11:01 +00:00
if (isBg) {
bg._msg.handler = handler;
}
2018-10-05 20:39:48 +00:00
chrome.runtime.onMessage.addListener(handleMessage);
}
2018-10-06 03:43:42 +00:00
function executeCallbacks(callbacks, ...args) {
let result;
for (const fn of callbacks) {
const data = withPromiseError(fn, ...args);
if (data !== undefined && result === undefined) {
result = data;
}
}
return result;
}
2018-10-05 20:39:48 +00:00
function handleMessage(message, sender, sendResponse) {
const handlers = message.target === 'tab' ?
handler.tab.concat(handler.both) : message.target === 'extension' ?
handler.extension.concat(handler.both) :
handler.both.concat(handler.extension, handler.tab);
if (!handlers.length) {
return;
}
if (message.type === 'exchange') {
const pending = exchangeGet(message, true);
if (pending) {
pending.then(response);
return true;
2018-10-05 19:10:04 +00:00
}
2018-10-05 20:39:48 +00:00
}
return response();
function response() {
2018-10-06 03:43:42 +00:00
const result = executeCallbacks(handlers, message.data, sender);
2018-10-05 20:39:48 +00:00
if (result === undefined) {
return;
2018-10-05 19:10:04 +00:00
}
2018-10-05 20:39:48 +00:00
Promise.resolve(result)
.then(
2018-10-10 19:21:38 +00:00
data => ({
error: false,
data
}),
err => ({
error: true,
data: Object.assign({
message: err.message || String(err),
// FIXME: do we want to pass the entire stack?
stack: err.stack
}, err) // this allows us to pass custom properties e.g. `err.index`
})
2018-10-05 20:39:48 +00:00
)
.then(function doResponse(responseMessage) {
if (message.from === 'extension' && bg === undefined) {
return preparing.then(() => doResponse(responseMessage));
}
if (message.from === 'extension' && bg) {
exchangeSet(responseMessage);
} else {
responseMessage.type = 'direct';
}
return responseMessage;
})
.then(sendResponse);
return true;
}
2018-10-05 19:10:04 +00:00
}
function exchangeGet(message, keepStorage = false) {
if (bg === undefined) {
return preparing.then(() => exchangeGet(message, keepStorage));
}
message.data = bg._msg.storage.get(message.id);
2018-10-05 19:19:51 +00:00
if (keepStorage) {
2018-10-05 20:39:48 +00:00
message.data = deepCopy(message.data);
2018-10-05 19:19:51 +00:00
} else {
2018-10-05 19:10:04 +00:00
bg._msg.storage.delete(message.id);
}
}
function exchangeSet(message) {
const id = bg._msg.id;
bg._msg.storage.set(id, message.data);
bg._msg.id++;
message.type = 'exchange';
message.id = id;
delete message.data;
}
2018-10-05 20:39:48 +00:00
function withPromiseError(fn, ...args) {
try {
return fn(...args);
} catch (err) {
return Promise.reject(err);
}
}
2018-10-05 19:10:04 +00:00
function withCleanup(p, fn) {
return p.then(
result => {
cleanup();
return result;
},
err => {
cleanup();
throw err;
}
);
function cleanup() {
try {
fn();
} catch (err) {
// pass
}
}
}
// {type, error, data, id}
function unwrapData(result) {
if (result === undefined) {
throw new Error('Receiving end does not exist');
}
2018-10-05 19:10:04 +00:00
if (result.type === 'exchange') {
const pending = exchangeGet(result);
if (pending) {
return pending.then(unwrap);
}
}
return unwrap();
function unwrap() {
if (result.error) {
2018-10-10 19:21:38 +00:00
throw Object.assign(new Error(result.data.message), result.data);
2018-10-05 19:10:04 +00:00
}
return result.data;
}
}
})();
2018-10-05 20:39:48 +00:00
const API = new Proxy({}, {
get: (target, name) =>
2018-10-06 07:14:05 +00:00
(...args) => Promise.resolve(msg.sendBg({
2018-10-05 20:39:48 +00:00
method: 'invokeAPI',
name,
args
2018-10-06 07:14:05 +00:00
}))
2018-10-05 20:39:48 +00:00
});