From adf42f0483956335493b765da05787d1f237bb52 Mon Sep 17 00:00:00 2001 From: Stu Kabakoff Date: Tue, 22 Dec 2020 16:27:03 -0500 Subject: [PATCH 1/4] fix cursor error in Safari --- dist/es/broadcast-channel.js | 39 ++++++++---- dist/es/browserify.index.js | 8 ++- dist/es/index.es5.js | 13 ++-- dist/es/index.js | 35 ++++++++++- dist/es/leader-election.js | 25 +++++--- dist/es/method-chooser.js | 38 ++++++++---- dist/es/methods/cookies.js | 3 +- dist/es/methods/indexed-db.js | 102 ++++++++++++++++++++++---------- dist/es/methods/localstorage.js | 82 ++++++++++++++++++------- dist/es/methods/native.js | 48 +++++++++++---- dist/es/methods/node.js | 81 +++++++++++++------------ dist/es/methods/simulate.js | 46 ++++++++++---- dist/es/oblivious-set.js | 10 +++- dist/es/options.js | 9 ++- dist/es/util.js | 30 ++++++++-- dist/lib/browser.js | 9 ++- dist/lib/browser.min.js | 2 +- dist/lib/methods/indexed-db.js | 9 ++- docs/e2e.js | 13 ++-- docs/iframe.js | 13 ++-- docs/index.js | 13 ++-- docs/leader-iframe.js | 13 ++-- docs/worker.js | 13 ++-- src/methods/indexed-db.js | 7 +-- 24 files changed, 448 insertions(+), 213 deletions(-) diff --git a/dist/es/broadcast-channel.js b/dist/es/broadcast-channel.js index eae03f2f..2d34e047 100644 --- a/dist/es/broadcast-channel.js +++ b/dist/es/broadcast-channel.js @@ -1,15 +1,27 @@ -import { isPromise } from './util.js'; -import { chooseMethod } from './method-chooser.js'; -import { fillOptionsWithDefaults } from './options.js'; -export var BroadcastChannel = function BroadcastChannel(name, options) { +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.clearNodeFolder = clearNodeFolder; +exports.enforceOptions = enforceOptions; +exports.BroadcastChannel = void 0; + +var _util = require("./util.js"); + +var _methodChooser = require("./method-chooser.js"); + +var _options = require("./options.js"); + +var BroadcastChannel = function BroadcastChannel(name, options) { this.name = name; if (ENFORCED_OPTIONS) { options = ENFORCED_OPTIONS; } - this.options = fillOptionsWithDefaults(options); - this.method = chooseMethod(this.options); // isListening + this.options = (0, _options.fillOptionsWithDefaults)(options); + this.method = (0, _methodChooser.chooseMethod)(this.options); // isListening this._iL = false; /** @@ -49,15 +61,17 @@ export var BroadcastChannel = function BroadcastChannel(name, options) { * See methods/native.js */ + +exports.BroadcastChannel = BroadcastChannel; BroadcastChannel._pubkey = true; /** * clears the tmp-folder if is node * @return {Promise} true if has run, false if not node */ -export function clearNodeFolder(options) { - options = fillOptionsWithDefaults(options); - var method = chooseMethod(options); +function clearNodeFolder(options) { + options = (0, _options.fillOptionsWithDefaults)(options); + var method = (0, _methodChooser.chooseMethod)(options); if (method.type === 'node') { return method.clearNodeFolder().then(function () { @@ -72,11 +86,14 @@ export function clearNodeFolder(options) { * no mather what the options are */ + var ENFORCED_OPTIONS; -export function enforceOptions(options) { + +function enforceOptions(options) { ENFORCED_OPTIONS = options; } // PROTOTYPE + BroadcastChannel.prototype = { postMessage: function postMessage(msg) { if (this.closed) { @@ -162,7 +179,7 @@ function _post(broadcastChannel, type, msg) { function _prepareChannel(channel) { var maybePromise = channel.method.create(channel.name, channel.options); - if (isPromise(maybePromise)) { + if ((0, _util.isPromise)(maybePromise)) { channel._prepP = maybePromise; maybePromise.then(function (s) { // used in tests to simulate slow runtime diff --git a/dist/es/browserify.index.js b/dist/es/browserify.index.js index e500d3df..a30fe523 100644 --- a/dist/es/browserify.index.js +++ b/dist/es/browserify.index.js @@ -1,6 +1,8 @@ -var module = require('./index.es5.js'); +"use strict"; -var BroadcastChannel = module.BroadcastChannel; -var createLeaderElection = module.createLeaderElection; +var _module = require('./index.es5.js'); + +var BroadcastChannel = _module.BroadcastChannel; +var createLeaderElection = _module.createLeaderElection; window['BroadcastChannel2'] = BroadcastChannel; window['createLeaderElection'] = createLeaderElection; \ No newline at end of file diff --git a/dist/es/index.es5.js b/dist/es/index.es5.js index 72f71a17..f61bff0b 100644 --- a/dist/es/index.es5.js +++ b/dist/es/index.es5.js @@ -1,3 +1,7 @@ +"use strict"; + +var _index = require("./index.js"); + /** * because babel can only export on default-attribute, * we use this for the non-module-build @@ -6,10 +10,9 @@ * but * var BroadcastChannel = require('broadcast-channel'); */ -import { BroadcastChannel, createLeaderElection, clearNodeFolder, enforceOptions } from './index.js'; module.exports = { - BroadcastChannel: BroadcastChannel, - createLeaderElection: createLeaderElection, - clearNodeFolder: clearNodeFolder, - enforceOptions: enforceOptions + BroadcastChannel: _index.BroadcastChannel, + createLeaderElection: _index.createLeaderElection, + clearNodeFolder: _index.clearNodeFolder, + enforceOptions: _index.enforceOptions }; \ No newline at end of file diff --git a/dist/es/index.js b/dist/es/index.js index 20d17701..a7039fba 100644 --- a/dist/es/index.js +++ b/dist/es/index.js @@ -1,2 +1,33 @@ -export { BroadcastChannel, clearNodeFolder, enforceOptions } from './broadcast-channel'; -export { createLeaderElection } from './leader-election'; \ No newline at end of file +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "BroadcastChannel", { + enumerable: true, + get: function get() { + return _broadcastChannel.BroadcastChannel; + } +}); +Object.defineProperty(exports, "clearNodeFolder", { + enumerable: true, + get: function get() { + return _broadcastChannel.clearNodeFolder; + } +}); +Object.defineProperty(exports, "enforceOptions", { + enumerable: true, + get: function get() { + return _broadcastChannel.enforceOptions; + } +}); +Object.defineProperty(exports, "createLeaderElection", { + enumerable: true, + get: function get() { + return _leaderElection.createLeaderElection; + } +}); + +var _broadcastChannel = require("./broadcast-channel"); + +var _leaderElection = require("./leader-election"); \ No newline at end of file diff --git a/dist/es/leader-election.js b/dist/es/leader-election.js index 90e63218..c34638f3 100644 --- a/dist/es/leader-election.js +++ b/dist/es/leader-election.js @@ -1,12 +1,22 @@ -import { sleep, randomToken } from './util.js'; -import unload from 'unload'; +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createLeaderElection = createLeaderElection; + +var _util = require("./util.js"); + +var _unload = _interopRequireDefault(require("unload")); var LeaderElection = function LeaderElection(channel, options) { this._channel = channel; this._options = options; this.isLeader = false; this.isDead = false; - this.token = randomToken(); + this.token = (0, _util.randomToken)(); this._isApl = false; // _isApplying this._reApply = false; // things to clean up @@ -57,12 +67,12 @@ LeaderElection.prototype = { var ret = _sendMessage(this, 'apply') // send out that this one is applying .then(function () { - return sleep(_this._options.responseTime); + return (0, _util.sleep)(_this._options.responseTime); }) // let others time to respond .then(function () { if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this, 'apply'); }).then(function () { - return sleep(_this._options.responseTime); + return (0, _util.sleep)(_this._options.responseTime); }) // let others time to respond .then(function () { if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this); @@ -176,7 +186,8 @@ function _sendMessage(leaderElector, action) { function _beLeader(leaderElector) { leaderElector.isLeader = true; - var unloadFn = unload.add(function () { + + var unloadFn = _unload["default"].add(function () { return leaderElector.die(); }); @@ -210,7 +221,7 @@ function fillOptionsWithDefaults(options, channel) { return options; } -export function createLeaderElection(channel, options) { +function createLeaderElection(channel, options) { if (channel._leaderElector) { throw new Error('BroadcastChannel already has a leader-elector'); } diff --git a/dist/es/method-chooser.js b/dist/es/method-chooser.js index 3e34b009..e2c7fe06 100644 --- a/dist/es/method-chooser.js +++ b/dist/es/method-chooser.js @@ -1,17 +1,31 @@ -import NativeMethod from './methods/native.js'; -import IndexeDbMethod from './methods/indexed-db.js'; -import LocalstorageMethod from './methods/localstorage.js'; -import SimulateMethod from './methods/simulate.js'; -import { isNode } from './util'; // order is important - -var METHODS = [NativeMethod, // fastest -IndexeDbMethod, LocalstorageMethod]; +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.chooseMethod = chooseMethod; + +var _native = _interopRequireDefault(require("./methods/native.js")); + +var _indexedDb = _interopRequireDefault(require("./methods/indexed-db.js")); + +var _localstorage = _interopRequireDefault(require("./methods/localstorage.js")); + +var _simulate = _interopRequireDefault(require("./methods/simulate.js")); + +var _util = require("./util"); + +// order is important +var METHODS = [_native["default"], // fastest +_indexedDb["default"], _localstorage["default"]]; /** * The NodeMethod is loaded lazy * so it will not get bundled in browser-builds */ -if (isNode) { +if (_util.isNode) { /** * we use the non-transpiled code for nodejs * because it runs faster @@ -31,13 +45,13 @@ if (isNode) { } } -export function chooseMethod(options) { +function chooseMethod(options) { var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen if (options.type) { if (options.type === 'simulate') { // only use simulate-method if directly chosen - return SimulateMethod; + return _simulate["default"]; } var ret = chooseMethods.find(function (m) { @@ -51,7 +65,7 @@ export function chooseMethod(options) { */ - if (!options.webWorkerSupport && !isNode) { + if (!options.webWorkerSupport && !_util.isNode) { chooseMethods = chooseMethods.filter(function (m) { return m.type !== 'idb'; }); diff --git a/dist/es/methods/cookies.js b/dist/es/methods/cookies.js index f0cf25c8..0011f3e2 100644 --- a/dist/es/methods/cookies.js +++ b/dist/es/methods/cookies.js @@ -1,4 +1,5 @@ /** * if you really need this method, * implement it - */ \ No newline at end of file + */ +"use strict"; \ No newline at end of file diff --git a/dist/es/methods/indexed-db.js b/dist/es/methods/indexed-db.js index eedc7019..aa9e4727 100644 --- a/dist/es/methods/indexed-db.js +++ b/dist/es/methods/indexed-db.js @@ -1,16 +1,45 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getIdb = getIdb; +exports.createDatabase = createDatabase; +exports.writeMessage = writeMessage; +exports.getAllMessages = getAllMessages; +exports.getMessagesHigherThan = getMessagesHigherThan; +exports.removeMessageById = removeMessageById; +exports.getOldMessages = getOldMessages; +exports.cleanOldMessages = cleanOldMessages; +exports.create = create; +exports.close = close; +exports.postMessage = postMessage; +exports.onMessage = onMessage; +exports.canBeUsed = canBeUsed; +exports.averageResponseTime = averageResponseTime; +exports["default"] = exports.type = exports.microSeconds = void 0; + +var _util = require("../util.js"); + +var _obliviousSet = _interopRequireDefault(require("../oblivious-set")); + +var _options = require("../options"); + /** * this method uses indexeddb to store the messages * There is currently no observerAPI for idb * @link https://github.com/w3c/IndexedDB/issues/51 */ -import { sleep, randomInt, randomToken, microSeconds as micro, isNode } from '../util.js'; -export var microSeconds = micro; -import ObliviousSet from '../oblivious-set'; -import { fillOptionsWithDefaults } from '../options'; +var microSeconds = _util.microSeconds; +exports.microSeconds = microSeconds; var DB_PREFIX = 'pubkey.broadcast-channel-0-'; var OBJECT_STORE_ID = 'messages'; -export var type = 'idb'; -export function getIdb() { +var type = 'idb'; +exports.type = type; + +function getIdb() { if (typeof indexedDB !== 'undefined') return indexedDB; if (typeof window !== 'undefined') { @@ -21,7 +50,8 @@ export function getIdb() { return false; } -export function createDatabase(channelName) { + +function createDatabase(channelName) { var IndexedDB = getIdb(); // create table var dbName = DB_PREFIX + channelName; @@ -51,7 +81,8 @@ export function createDatabase(channelName) { * so other readers can find it */ -export function writeMessage(db, readerUuid, messageJson) { + +function writeMessage(db, readerUuid, messageJson) { var time = new Date().getTime(); var writeObject = { uuid: readerUuid, @@ -72,7 +103,8 @@ export function writeMessage(db, readerUuid, messageJson) { objectStore.add(writeObject); }); } -export function getAllMessages(db) { + +function getAllMessages(db) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; return new Promise(function (res) { @@ -89,12 +121,12 @@ export function getAllMessages(db) { }; }); } -export function getMessagesHigherThen(db, lastCursorId) { + +function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; - var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); return new Promise(function (res) { - objectStore.openCursor(keyRangeValue).onsuccess = function (ev) { + objectStore.openCursor(lastCursorId + 1).onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { @@ -106,7 +138,8 @@ export function getMessagesHigherThen(db, lastCursorId) { }; }); } -export function removeMessageById(db, id) { + +function removeMessageById(db, id) { var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)["delete"](id); return new Promise(function (res) { request.onsuccess = function () { @@ -114,7 +147,8 @@ export function removeMessageById(db, id) { }; }); } -export function getOldMessages(db, ttl) { + +function getOldMessages(db, ttl) { var olderThen = new Date().getTime() - ttl; var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; @@ -140,29 +174,31 @@ export function getOldMessages(db, ttl) { }; }); } -export function cleanOldMessages(db, ttl) { + +function cleanOldMessages(db, ttl) { return getOldMessages(db, ttl).then(function (tooOld) { return Promise.all(tooOld.map(function (msgObj) { return removeMessageById(db, msgObj.id); })); }); } -export function create(channelName, options) { - options = fillOptionsWithDefaults(options); + +function create(channelName, options) { + options = (0, _options.fillOptionsWithDefaults)(options); return createDatabase(channelName).then(function (db) { var state = { closed: false, lastCursorId: 0, channelName: channelName, options: options, - uuid: randomToken(), + uuid: (0, _util.randomToken)(), /** * emittedMessagesIds * contains all messages that have been emitted before * @type {ObliviousSet} */ - eMIs: new ObliviousSet(options.idb.ttl * 2), + eMIs: new _obliviousSet["default"](options.idb.ttl * 2), // ensures we do not read messages in parrallel writeBlockPromise: Promise.resolve(), messagesCallback: null, @@ -196,7 +232,7 @@ export function create(channelName, options) { function _readLoop(state) { if (state.closed) return; readNewMessages(state).then(function () { - return sleep(state.options.idb.fallbackInterval); + return (0, _util.sleep)(state.options.idb.fallbackInterval); }).then(function () { return _readLoop(state); }); @@ -221,7 +257,7 @@ function readNewMessages(state) { if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages if (!state.messagesCallback) return Promise.resolve(); - return getMessagesHigherThen(state.db, state.lastCursorId).then(function (newerMessages) { + return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) { var useMessages = newerMessages /** * there is a bug in iOS where the msgObj can be undefined some times @@ -252,36 +288,41 @@ function readNewMessages(state) { }); } -export function close(channelState) { +function close(channelState) { channelState.closed = true; channelState.db.close(); } -export function postMessage(channelState, messageJson) { + +function postMessage(channelState, messageJson) { channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () { return writeMessage(channelState.db, channelState.uuid, messageJson); }).then(function () { - if (randomInt(0, 10) === 0) { + if ((0, _util.randomInt)(0, 10) === 0) { /* await (do not await) */ cleanOldMessages(channelState.db, channelState.options.idb.ttl); } }); return channelState.writeBlockPromise; } -export function onMessage(channelState, fn, time) { + +function onMessage(channelState, fn, time) { channelState.messagesCallbackTime = time; channelState.messagesCallback = fn; readNewMessages(channelState); } -export function canBeUsed() { - if (isNode) return false; + +function canBeUsed() { + if (_util.isNode) return false; var idb = getIdb(); if (!idb) return false; return true; } -export function averageResponseTime(options) { + +function averageResponseTime(options) { return options.idb.fallbackInterval * 2; } -export default { + +var _default = { create: create, close: close, onMessage: onMessage, @@ -290,4 +331,5 @@ export default { type: type, averageResponseTime: averageResponseTime, microSeconds: microSeconds -}; \ No newline at end of file +}; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/es/methods/localstorage.js b/dist/es/methods/localstorage.js index da9a304f..b5d0dca1 100644 --- a/dist/es/methods/localstorage.js +++ b/dist/es/methods/localstorage.js @@ -1,3 +1,28 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLocalStorage = getLocalStorage; +exports.storageKey = storageKey; +exports.postMessage = postMessage; +exports.addStorageEventListener = addStorageEventListener; +exports.removeStorageEventListener = removeStorageEventListener; +exports.create = create; +exports.close = close; +exports.onMessage = onMessage; +exports.canBeUsed = canBeUsed; +exports.averageResponseTime = averageResponseTime; +exports["default"] = exports.type = exports.microSeconds = void 0; + +var _obliviousSet = _interopRequireDefault(require("../oblivious-set")); + +var _options = require("../options"); + +var _util = require("../util"); + /** * A localStorage-only method which uses localstorage and its 'storage'-event * This does not work inside of webworkers because they have no access to locastorage @@ -5,18 +30,18 @@ * @link https://caniuse.com/#feat=namevalue-storage * @link https://caniuse.com/#feat=indexeddb */ -import ObliviousSet from '../oblivious-set'; -import { fillOptionsWithDefaults } from '../options'; -import { sleep, randomToken, microSeconds as micro, isNode } from '../util'; -export var microSeconds = micro; +var microSeconds = _util.microSeconds; +exports.microSeconds = microSeconds; var KEY_PREFIX = 'pubkey.broadcastChannel-'; -export var type = 'localstorage'; +var type = 'localstorage'; /** * copied from crosstab * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32 */ -export function getLocalStorage() { +exports.type = type; + +function getLocalStorage() { var localStorage; if (typeof window === 'undefined') return null; @@ -30,7 +55,8 @@ export function getLocalStorage() { return localStorage; } -export function storageKey(channelName) { + +function storageKey(channelName) { return KEY_PREFIX + channelName; } /** @@ -38,12 +64,13 @@ export function storageKey(channelName) { * and fires the storage-event so other readers can find it */ -export function postMessage(channelState, messageJson) { + +function postMessage(channelState, messageJson) { return new Promise(function (res) { - sleep().then(function () { + (0, _util.sleep)().then(function () { var key = storageKey(channelState.channelName); var writeObj = { - token: randomToken(), + token: (0, _util.randomToken)(), time: new Date().getTime(), data: messageJson, uuid: channelState.uuid @@ -65,7 +92,8 @@ export function postMessage(channelState, messageJson) { }); }); } -export function addStorageEventListener(channelName, fn) { + +function addStorageEventListener(channelName, fn) { var key = storageKey(channelName); var listener = function listener(ev) { @@ -77,24 +105,26 @@ export function addStorageEventListener(channelName, fn) { window.addEventListener('storage', listener); return listener; } -export function removeStorageEventListener(listener) { + +function removeStorageEventListener(listener) { window.removeEventListener('storage', listener); } -export function create(channelName, options) { - options = fillOptionsWithDefaults(options); + +function create(channelName, options) { + options = (0, _options.fillOptionsWithDefaults)(options); if (!canBeUsed()) { throw new Error('BroadcastChannel: localstorage cannot be used'); } - var uuid = randomToken(); + var uuid = (0, _util.randomToken)(); /** * eMIs * contains all messages that have been emitted before * @type {ObliviousSet} */ - var eMIs = new ObliviousSet(options.localstorage.removeTimeout); + var eMIs = new _obliviousSet["default"](options.localstorage.removeTimeout); var state = { channelName: channelName, uuid: uuid, @@ -115,15 +145,18 @@ export function create(channelName, options) { }); return state; } -export function close(channelState) { + +function close(channelState) { removeStorageEventListener(channelState.listener); } -export function onMessage(channelState, fn, time) { + +function onMessage(channelState, fn, time) { channelState.messagesCallbackTime = time; channelState.messagesCallback = fn; } -export function canBeUsed() { - if (isNode) return false; + +function canBeUsed() { + if (_util.isNode) return false; var ls = getLocalStorage(); if (!ls) return false; @@ -140,7 +173,8 @@ export function canBeUsed() { return true; } -export function averageResponseTime() { + +function averageResponseTime() { var defaultTime = 120; var userAgent = navigator.userAgent.toLowerCase(); @@ -151,7 +185,8 @@ export function averageResponseTime() { return defaultTime; } -export default { + +var _default = { create: create, close: close, onMessage: onMessage, @@ -160,4 +195,5 @@ export default { type: type, averageResponseTime: averageResponseTime, microSeconds: microSeconds -}; \ No newline at end of file +}; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/es/methods/native.js b/dist/es/methods/native.js index fb67fa3b..91a4e66e 100644 --- a/dist/es/methods/native.js +++ b/dist/es/methods/native.js @@ -1,7 +1,24 @@ -import { microSeconds as micro, isNode } from '../util'; -export var microSeconds = micro; -export var type = 'native'; -export function create(channelName) { +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = create; +exports.close = close; +exports.postMessage = postMessage; +exports.onMessage = onMessage; +exports.canBeUsed = canBeUsed; +exports.averageResponseTime = averageResponseTime; +exports["default"] = exports.type = exports.microSeconds = void 0; + +var _util = require("../util"); + +var microSeconds = _util.microSeconds; +exports.microSeconds = microSeconds; +var type = 'native'; +exports.type = type; + +function create(channelName) { var state = { messagesCallback: null, bc: new BroadcastChannel(channelName), @@ -17,22 +34,26 @@ export function create(channelName) { return state; } -export function close(channelState) { + +function close(channelState) { channelState.bc.close(); channelState.subFns = []; } -export function postMessage(channelState, messageJson) { + +function postMessage(channelState, messageJson) { channelState.bc.postMessage(messageJson, false); } -export function onMessage(channelState, fn) { + +function onMessage(channelState, fn) { channelState.messagesCallback = fn; } -export function canBeUsed() { + +function canBeUsed() { /** * in the electron-renderer, isNode will be true even if we are in browser-context * so we also check if window is undefined */ - if (isNode && typeof window === 'undefined') return false; + if (_util.isNode && typeof window === 'undefined') return false; if (typeof BroadcastChannel === 'function') { if (BroadcastChannel._pubkey) { @@ -42,10 +63,12 @@ export function canBeUsed() { return true; } else return false; } -export function averageResponseTime() { + +function averageResponseTime() { return 150; } -export default { + +var _default = { create: create, close: close, onMessage: onMessage, @@ -54,4 +77,5 @@ export default { type: type, averageResponseTime: averageResponseTime, microSeconds: microSeconds -}; \ No newline at end of file +}; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/es/methods/node.js b/dist/es/methods/node.js index d74f78ae..db11c1a5 100644 --- a/dist/es/methods/node.js +++ b/dist/es/methods/node.js @@ -1,5 +1,10 @@ -import _regeneratorRuntime from "@babel/runtime/regenerator"; -import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); /** * this method is used in nodejs-environments. @@ -96,8 +101,8 @@ function ensureBaseFolderExists() { } function _ensureBaseFolderExists() { - _ensureBaseFolderExists = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { - return _regeneratorRuntime.wrap(function _callee4$(_context4) { + _ensureBaseFolderExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: @@ -129,9 +134,9 @@ function ensureFoldersExist(_x, _x2) { function _ensureFoldersExist() { - _ensureFoldersExist = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(channelName, paths) { + _ensureFoldersExist = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(channelName, paths) { var chmodValue; - return _regeneratorRuntime.wrap(function _callee5$(_context5) { + return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: @@ -176,8 +181,8 @@ function clearNodeFolder() { } function _clearNodeFolder() { - _clearNodeFolder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { - return _regeneratorRuntime.wrap(function _callee6$(_context6) { + _clearNodeFolder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { + return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: @@ -244,9 +249,9 @@ function countChannelFolders() { } function _countChannelFolders() { - _countChannelFolders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { + _countChannelFolders = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { var folders; - return _regeneratorRuntime.wrap(function _callee7$(_context7) { + return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: @@ -281,9 +286,9 @@ function connectionError(_x3) { function _connectionError() { - _connectionError = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(originalError) { + _connectionError = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(originalError) { var count, addObj, text, newError; - return _regeneratorRuntime.wrap(function _callee8$(_context8) { + return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: @@ -326,9 +331,9 @@ function createSocketEventEmitter(_x4, _x5, _x6) { } function _createSocketEventEmitter() { - _createSocketEventEmitter = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(channelName, readerUuid, paths) { + _createSocketEventEmitter = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(channelName, readerUuid, paths) { var pathToSocket, emitter, server; - return _regeneratorRuntime.wrap(function _callee11$(_context11) { + return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: @@ -343,9 +348,9 @@ function _createSocketEventEmitter() { _context11.next = 5; return new Promise(function (resolve, reject) { server.on('error', /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(err) { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(err) { var useErr; - return _regeneratorRuntime.wrap(function _callee9$(_context9) { + return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: @@ -369,9 +374,9 @@ function _createSocketEventEmitter() { }; }()); server.listen(pathToSocket, /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(err, res) { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(err, res) { var useErr; - return _regeneratorRuntime.wrap(function _callee10$(_context10) { + return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: @@ -434,9 +439,9 @@ function openClientConnection(_x7, _x8) { function _openClientConnection() { - _openClientConnection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(channelName, readerUuid) { + _openClientConnection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(channelName, readerUuid) { var pathToSocket, client; - return _regeneratorRuntime.wrap(function _callee12$(_context12) { + return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: @@ -492,9 +497,9 @@ function getReadersUuids(_x9, _x10) { } function _getReadersUuids() { - _getReadersUuids = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(channelName, paths) { + _getReadersUuids = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(channelName, paths) { var readersPath, files; - return _regeneratorRuntime.wrap(function _callee13$(_context13) { + return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: @@ -529,9 +534,9 @@ function messagePath(_x11, _x12, _x13, _x14) { } function _messagePath() { - _messagePath = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(channelName, time, token, writerUuid) { + _messagePath = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(channelName, time, token, writerUuid) { var fileName, msgPath; - return _regeneratorRuntime.wrap(function _callee14$(_context14) { + return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: @@ -554,9 +559,9 @@ function getAllMessages(_x15, _x16) { } function _getAllMessages() { - _getAllMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(channelName, paths) { + _getAllMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(channelName, paths) { var messagesPath, files; - return _regeneratorRuntime.wrap(function _callee15$(_context15) { + return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: @@ -609,9 +614,9 @@ function cleanOldMessages(_x17, _x18) { } function _cleanOldMessages() { - _cleanOldMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(messageObjects, ttl) { + _cleanOldMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(messageObjects, ttl) { var olderThen; - return _regeneratorRuntime.wrap(function _callee16$(_context16) { + return _regenerator["default"].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: @@ -646,7 +651,7 @@ function create(_x19) { } function _create() { - _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(channelName) { + _create = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(channelName) { var options, time, paths, @@ -658,7 +663,7 @@ function _create() { infoFilePath, _args17 = arguments; - return _regeneratorRuntime.wrap(function _callee17$(_context17) { + return _regenerator["default"].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: @@ -760,9 +765,9 @@ function handleMessagePing(_x20, _x21) { function _handleMessagePing() { - _handleMessagePing = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(state, msgObj) { + _handleMessagePing = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(state, msgObj) { var messages, useMessages; - return _regeneratorRuntime.wrap(function _callee18$(_context18) { + return _regenerator["default"].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: @@ -840,8 +845,8 @@ function refreshReaderClients(channelState) { Object.keys(channelState.otherReaderClients).filter(function (readerUuid) { return !otherReaders.includes(readerUuid); }).forEach( /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(readerUuid) { - return _regeneratorRuntime.wrap(function _callee$(_context) { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(readerUuid) { + return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: @@ -880,9 +885,9 @@ function refreshReaderClients(channelState) { return !channelState.otherReaderClients[readerUuid]; }) // not already has client .map( /*#__PURE__*/function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(readerUuid) { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(readerUuid) { var client; - return _regeneratorRuntime.wrap(function _callee2$(_context2) { + return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: @@ -940,10 +945,10 @@ function refreshReaderClients(channelState) { function postMessage(channelState, messageJson) { var writePromise = writeMessage(channelState.channelName, channelState.uuid, messageJson, channelState.paths); - channelState.writeBlockPromise = channelState.writeBlockPromise.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + channelState.writeBlockPromise = channelState.writeBlockPromise.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var _yield$Promise$all, msgObj, pingStr, writeToReadersPromise; - return _regeneratorRuntime.wrap(function _callee3$(_context3) { + return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: diff --git a/dist/es/methods/simulate.js b/dist/es/methods/simulate.js index 135256bc..09b12b89 100644 --- a/dist/es/methods/simulate.js +++ b/dist/es/methods/simulate.js @@ -1,8 +1,25 @@ -import { microSeconds as micro } from '../util'; -export var microSeconds = micro; -export var type = 'simulate'; +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = create; +exports.close = close; +exports.postMessage = postMessage; +exports.onMessage = onMessage; +exports.canBeUsed = canBeUsed; +exports.averageResponseTime = averageResponseTime; +exports["default"] = exports.type = exports.microSeconds = void 0; + +var _util = require("../util"); + +var microSeconds = _util.microSeconds; +exports.microSeconds = microSeconds; +var type = 'simulate'; +exports.type = type; var SIMULATE_CHANNELS = new Set(); -export function create(channelName) { + +function create(channelName) { var state = { name: channelName, messagesCallback: null @@ -10,10 +27,12 @@ export function create(channelName) { SIMULATE_CHANNELS.add(state); return state; } -export function close(channelState) { + +function close(channelState) { SIMULATE_CHANNELS["delete"](channelState); } -export function postMessage(channelState, messageJson) { + +function postMessage(channelState, messageJson) { return new Promise(function (res) { return setTimeout(function () { var channelArray = Array.from(SIMULATE_CHANNELS); @@ -30,16 +49,20 @@ export function postMessage(channelState, messageJson) { }, 5); }); } -export function onMessage(channelState, fn) { + +function onMessage(channelState, fn) { channelState.messagesCallback = fn; } -export function canBeUsed() { + +function canBeUsed() { return true; } -export function averageResponseTime() { + +function averageResponseTime() { return 5; } -export default { + +var _default = { create: create, close: close, onMessage: onMessage, @@ -48,4 +71,5 @@ export default { type: type, averageResponseTime: averageResponseTime, microSeconds: microSeconds -}; \ No newline at end of file +}; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/es/oblivious-set.js b/dist/es/oblivious-set.js index 840865c5..875cc485 100644 --- a/dist/es/oblivious-set.js +++ b/dist/es/oblivious-set.js @@ -1,3 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + /** * this is a set which automatically forgets * a given entry when a new entry is set and the ttl @@ -46,4 +53,5 @@ function now() { return new Date().getTime(); } -export default ObliviousSet; \ No newline at end of file +var _default = ObliviousSet; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/es/options.js b/dist/es/options.js index d5354bee..18d4d8a5 100644 --- a/dist/es/options.js +++ b/dist/es/options.js @@ -1,4 +1,11 @@ -export function fillOptionsWithDefaults() { +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fillOptionsWithDefaults = fillOptionsWithDefaults; + +function fillOptionsWithDefaults() { var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var options = JSON.parse(JSON.stringify(originalOptions)); // main diff --git a/dist/es/util.js b/dist/es/util.js index f8fc8363..8fba57af 100644 --- a/dist/es/util.js +++ b/dist/es/util.js @@ -1,29 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isPromise = isPromise; +exports.sleep = sleep; +exports.randomInt = randomInt; +exports.randomToken = randomToken; +exports.microSeconds = microSeconds; +exports.isNode = void 0; + /** * returns true if the given object is a promise */ -export function isPromise(obj) { +function isPromise(obj) { if (obj && typeof obj.then === 'function') { return true; } else { return false; } } -export function sleep(time) { + +function sleep(time) { if (!time) time = 0; return new Promise(function (res) { return setTimeout(res, time); }); } -export function randomInt(min, max) { + +function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } /** * https://stackoverflow.com/a/8084248 */ -export function randomToken() { + +function randomToken() { return Math.random().toString(36).substring(2); } + var lastMs = 0; var additional = 0; /** @@ -34,7 +50,7 @@ var additional = 0; * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests. */ -export function microSeconds() { +function microSeconds() { var ms = new Date().getTime(); if (ms === lastMs) { @@ -52,4 +68,6 @@ export function microSeconds() { * @link https://github.com/iliakan/detect-node/blob/master/index.js */ -export var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; \ No newline at end of file + +var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +exports.isNode = isNode; \ No newline at end of file diff --git a/dist/lib/browser.js b/dist/lib/browser.js index a18fd0d7..7d647ab0 100644 --- a/dist/lib/browser.js +++ b/dist/lib/browser.js @@ -642,7 +642,7 @@ exports.getIdb = getIdb; exports.createDatabase = createDatabase; exports.writeMessage = writeMessage; exports.getAllMessages = getAllMessages; -exports.getMessagesHigherThen = getMessagesHigherThen; +exports.getMessagesHigherThan = getMessagesHigherThan; exports.removeMessageById = removeMessageById; exports.getOldMessages = getOldMessages; exports.cleanOldMessages = cleanOldMessages; @@ -755,12 +755,11 @@ function getAllMessages(db) { }); } -function getMessagesHigherThen(db, lastCursorId) { +function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; - var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); return new Promise(function (res) { - objectStore.openCursor(keyRangeValue).onsuccess = function (ev) { + objectStore.openCursor(lastCursorId + 1).onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { @@ -891,7 +890,7 @@ function readNewMessages(state) { if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages if (!state.messagesCallback) return Promise.resolve(); - return getMessagesHigherThen(state.db, state.lastCursorId).then(function (newerMessages) { + return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) { var useMessages = newerMessages /** * there is a bug in iOS where the msgObj can be undefined some times diff --git a/dist/lib/browser.min.js b/dist/lib/browser.min.js index 2c3fddc9..4b050eef 100644 --- a/dist/lib/browser.min.js +++ b/dist/lib/browser.min.js @@ -1 +1 @@ -!function r(o,i,s){function a(t,e){if(!i[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=i[t]={exports:{}},o[t][0].call(n.exports,function(e){return a(o[t][1][e]||e)},n,n.exports,r,o,i,s)}return i[t].exports}for(var u="function"==typeof require&&require,e=0;e=e.time&&e.fn(t.data)})},n=e.method.microSeconds(),e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,n)}):(e._iL=!0,e.method.onMessage(e._state,t,n)))}}(e)}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),function(e){{var t;e._iL&&!u(e)&&(e._iL=!1,t=e.method.microSeconds(),e.method.onMessage(e._state,null,t))}}(e)}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThen=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,t){var n=e.transaction(u).objectStore(u),r=[],o=IDBKeyRange.bound(t+1,1/0);return new Promise(function(t){n.openCursor(o).onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})}function h(e,t){var n=e.transaction([u],"readwrite").objectStore(u).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function p(e,t){var r=(new Date).getTime()-t,o=e.transaction(u).objectStore(u),i=[];return new Promise(function(n){o.openCursor().onsuccess=function(e){var t,e=e.target.result;e&&(t=e.value).timen.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time=e.time&&e.fn(t.data)})},i=r.method.microSeconds(),r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,o,i)}):(r._iL=!0,r.method.onMessage(r._state,o,i)))}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),(t=e)._iL&&!u(t)&&(t._iL=!1,e=t.method.microSeconds(),t.method.onMessage(t._state,null,e))}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThan=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,n){var r=e.transaction(u).objectStore(u),o=[];return new Promise(function(t){r.openCursor(n+1).onsuccess=function(e){e=e.target.result;e?(o.push(e.value),e.continue()):t(o)}})}function h(e,t){var n=e.transaction([u],"readwrite").objectStore(u).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function p(e,t){var r=(new Date).getTime()-t,o=e.transaction(u).objectStore(u),i=[];return new Promise(function(n){o.openCursor().onsuccess=function(e){var t,e=e.target.result;e&&(t=e.value).timen.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time { - objectStore.openCursor(keyRangeValue).onsuccess = ev => { + objectStore.openCursor(lastCursorId + 1).onsuccess = ev => { const cursor = ev.target.result; if (cursor) { ret.push(cursor.value); @@ -232,7 +231,7 @@ function readNewMessages(state) { // if no one is listening, we do not need to scan for new messages if (!state.messagesCallback) return Promise.resolve(); - return getMessagesHigherThen(state.db, state.lastCursorId) + return getMessagesHigherThan(state.db, state.lastCursorId) .then(newerMessages => { const useMessages = newerMessages /** From c331810b2d4a1a77206756c829d017359a3e055d Mon Sep 17 00:00:00 2001 From: Stu Kabakoff Date: Tue, 5 Jan 2021 10:57:52 -0500 Subject: [PATCH 2/4] fix spelling in test --- test/unit/indexed-db.method.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit/indexed-db.method.test.js b/test/unit/indexed-db.method.test.js index 4d4a880c..5700ec5f 100644 --- a/test/unit/indexed-db.method.test.js +++ b/test/unit/indexed-db.method.test.js @@ -112,7 +112,7 @@ describe('unit/indexed-db.method.test.js', () => { assert.equal(messagesAfter.length, 0); }); }); - describe('.getMessagesHigherThen()', () => { + describe('.getMessagesHigherThan()', () => { it('should only get messages with higher id', async () => { const channelName = AsyncTestUtil.randomString(10); const readerUuid = AsyncTestUtil.randomString(10); @@ -128,7 +128,7 @@ describe('unit/indexed-db.method.test.js', () => { ); // get last 5 messages - const lastFive = await IndexedDbMethod.getMessagesHigherThen(db, 5); + const lastFive = await IndexedDbMethod.getMessagesHigherThan(db, 5); assert.equal(lastFive.length, 5); assert.equal(lastFive[0].id, 6); assert.equal(lastFive[4].id, 10); From 811a1bed7a293c082d880bb6ad4e775976b684f2 Mon Sep 17 00:00:00 2001 From: Stu Kabakoff Date: Tue, 5 Jan 2021 11:18:48 -0500 Subject: [PATCH 3/4] create cursor for everything, then advance it. --- dist/es/methods/indexed-db.js | 10 +++++++--- dist/lib/browser.js | 10 +++++++--- dist/lib/browser.min.js | 2 +- dist/lib/methods/indexed-db.js | 10 +++++++--- docs/e2e.js | 10 +++++++--- docs/iframe.js | 10 +++++++--- docs/index.js | 10 +++++++--- docs/leader-iframe.js | 10 +++++++--- docs/worker.js | 10 +++++++--- src/methods/indexed-db.js | 10 +++++++--- 10 files changed, 64 insertions(+), 28 deletions(-) diff --git a/dist/es/methods/indexed-db.js b/dist/es/methods/indexed-db.js index aa9e4727..c0240424 100644 --- a/dist/es/methods/indexed-db.js +++ b/dist/es/methods/indexed-db.js @@ -126,12 +126,16 @@ function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; return new Promise(function (res) { - objectStore.openCursor(lastCursorId + 1).onsuccess = function (ev) { + objectStore.openCursor().onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { - ret.push(cursor.value); - cursor["continue"](); + if (cursor.value.id < lastCursorId + 1) { + cursor["continue"](lastCursorId + 1); + } else { + ret.push(cursor.value); + cursor["continue"](); + } } else { res(ret); } diff --git a/dist/lib/browser.js b/dist/lib/browser.js index 7d647ab0..c0722c61 100644 --- a/dist/lib/browser.js +++ b/dist/lib/browser.js @@ -759,12 +759,16 @@ function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; return new Promise(function (res) { - objectStore.openCursor(lastCursorId + 1).onsuccess = function (ev) { + objectStore.openCursor().onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { - ret.push(cursor.value); - cursor["continue"](); + if (cursor.value.id < lastCursorId + 1) { + cursor["continue"](lastCursorId + 1); + } else { + ret.push(cursor.value); + cursor["continue"](); + } } else { res(ret); } diff --git a/dist/lib/browser.min.js b/dist/lib/browser.min.js index 4b050eef..fb8aa62b 100644 --- a/dist/lib/browser.min.js +++ b/dist/lib/browser.min.js @@ -1 +1 @@ -!function r(o,i,s){function a(t,e){if(!i[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=i[t]={exports:{}},o[t][0].call(n.exports,function(e){return a(o[t][1][e]||e)},n,n.exports,r,o,i,s)}return i[t].exports}for(var u="function"==typeof require&&require,e=0;e=e.time&&e.fn(t.data)})},i=r.method.microSeconds(),r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,o,i)}):(r._iL=!0,r.method.onMessage(r._state,o,i)))}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),(t=e)._iL&&!u(t)&&(t._iL=!1,e=t.method.microSeconds(),t.method.onMessage(t._state,null,e))}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThan=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,n){var r=e.transaction(u).objectStore(u),o=[];return new Promise(function(t){r.openCursor(n+1).onsuccess=function(e){e=e.target.result;e?(o.push(e.value),e.continue()):t(o)}})}function h(e,t){var n=e.transaction([u],"readwrite").objectStore(u).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function p(e,t){var r=(new Date).getTime()-t,o=e.transaction(u).objectStore(u),i=[];return new Promise(function(n){o.openCursor().onsuccess=function(e){var t,e=e.target.result;e&&(t=e.value).timen.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time=e.time&&e.fn(t.data)})},i=r.method.microSeconds(),r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,o,i)}):(r._iL=!0,r.method.onMessage(r._state,o,i)))}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),(t=e)._iL&&!u(t)&&(t._iL=!1,e=t.method.microSeconds(),t.method.onMessage(t._state,null,e))}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThan=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,n){var r=e.transaction(u).objectStore(u),o=[];return new Promise(function(t){r.openCursor().onsuccess=function(e){e=e.target.result;e?e.value.idn.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time { - objectStore.openCursor(lastCursorId + 1).onsuccess = ev => { + objectStore.openCursor().onsuccess = ev => { const cursor = ev.target.result; if (cursor) { - ret.push(cursor.value); - cursor.continue(); + if (cursor.value.id < lastCursorId + 1) { + cursor.continue(lastCursorId + 1); + } else { + ret.push(cursor.value); + cursor.continue(); + } } else { res(ret); } From 2c1b1952e311859ac69f0e7a7cea3db168ba3f0e Mon Sep 17 00:00:00 2001 From: Stu Kabakoff Date: Tue, 19 Jan 2021 16:41:03 -0500 Subject: [PATCH 4/4] start IDB cursor at beginning only when creating the key range errors. --- dist/es/methods/indexed-db.js | 15 ++++++++++++++- dist/lib/browser.js | 15 ++++++++++++++- dist/lib/browser.min.js | 2 +- dist/lib/methods/indexed-db.js | 15 ++++++++++++++- docs/e2e.js | 15 ++++++++++++++- docs/iframe.js | 15 ++++++++++++++- docs/index.js | 15 ++++++++++++++- docs/leader-iframe.js | 15 ++++++++++++++- docs/worker.js | 15 ++++++++++++++- src/methods/indexed-db.js | 15 ++++++++++++++- 10 files changed, 127 insertions(+), 10 deletions(-) diff --git a/dist/es/methods/indexed-db.js b/dist/es/methods/indexed-db.js index c0240424..c47df15e 100644 --- a/dist/es/methods/indexed-db.js +++ b/dist/es/methods/indexed-db.js @@ -125,8 +125,21 @@ function getAllMessages(db) { function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; + + function openCursor() { + // Occasionally Safari will fail on IDBKeyRange.bound, this + // catches that error, having it open the cursor to the first + // item. When it gets data it will advance to the desired key. + try { + var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); + return objectStore.openCursor(keyRangeValue); + } catch (e) { + return objectStore.openCursor(); + } + } + return new Promise(function (res) { - objectStore.openCursor().onsuccess = function (ev) { + openCursor().onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { diff --git a/dist/lib/browser.js b/dist/lib/browser.js index c0722c61..fadef72e 100644 --- a/dist/lib/browser.js +++ b/dist/lib/browser.js @@ -758,8 +758,21 @@ function getAllMessages(db) { function getMessagesHigherThan(db, lastCursorId) { var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); var ret = []; + + function openCursor() { + // Occasionally Safari will fail on IDBKeyRange.bound, this + // catches that error, having it open the cursor to the first + // item. When it gets data it will advance to the desired key. + try { + var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); + return objectStore.openCursor(keyRangeValue); + } catch (e) { + return objectStore.openCursor(); + } + } + return new Promise(function (res) { - objectStore.openCursor().onsuccess = function (ev) { + openCursor().onsuccess = function (ev) { var cursor = ev.target.result; if (cursor) { diff --git a/dist/lib/browser.min.js b/dist/lib/browser.min.js index fb8aa62b..0ffd16d9 100644 --- a/dist/lib/browser.min.js +++ b/dist/lib/browser.min.js @@ -1 +1 @@ -!function r(o,i,s){function a(t,e){if(!i[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=i[t]={exports:{}},o[t][0].call(n.exports,function(e){return a(o[t][1][e]||e)},n,n.exports,r,o,i,s)}return i[t].exports}for(var u="function"==typeof require&&require,e=0;e=e.time&&e.fn(t.data)})},i=r.method.microSeconds(),r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,o,i)}):(r._iL=!0,r.method.onMessage(r._state,o,i)))}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),(t=e)._iL&&!u(t)&&(t._iL=!1,e=t.method.microSeconds(),t.method.onMessage(t._state,null,e))}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThan=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,n){var r=e.transaction(u).objectStore(u),o=[];return new Promise(function(t){r.openCursor().onsuccess=function(e){e=e.target.result;e?e.value.idn.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time=e.time&&e.fn(t.data)})},i=r.method.microSeconds(),r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,o,i)}):(r._iL=!0,r.method.onMessage(r._state,o,i)))}function l(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),(t=e)._iL&&!u(t)&&(t._iL=!1,e=t.method.microSeconds(),t.method.onMessage(t._state,null,e))}(n.BroadcastChannel=e)._pubkey=!0,e.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return a(this,"message",e)},postInternal:function(e){return a(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,c(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();c(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});l(this,e,n)},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP||Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),e=r.BroadcastChannel,r=r.createLeaderElection;window.BroadcastChannel2=e,window.createLeaderElection=r},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";e=e("./index.js");t.exports={BroadcastChannel:e.BroadcastChannel,createLeaderElection:e.createLeaderElection,clearNodeFolder:e.clearNodeFolder,enforceOptions:e.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}o.prototype={applyOnce:function(){var t=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){var i;return this._aLP||(this._aLP=(i=this).isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,u).filter(Boolean);if(t.type){if("simulate"===t.type)return s.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||a.isNode||(e=e.filter(function(e){return"idb"!==e.type}));e=e.find(function(e){return e.canBeUsed()});{if(e)return e;throw new Error("No useable methode found:"+JSON.stringify(u.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),n=r(e("./methods/localstorage.js")),s=r(e("./methods/simulate.js")),a=e("./util"),u=[o.default,i.default,n.default];!a.isNode||"function"==typeof(e=e("../../src/methods/node.js")).canBeUsed&&u.push(e)},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=c,n.createDatabase=l,n.writeMessage=d,n.getAllMessages=function(e){var n=e.transaction(u).objectStore(u),r=[];return new Promise(function(t){n.openCursor().onsuccess=function(e){e=e.target.result;e?(r.push(e.value),e.continue()):t(r)}})},n.getMessagesHigherThan=f,n.removeMessageById=h,n.getOldMessages=p,n.cleanOldMessages=m,n.create=v,n.close=g,n.postMessage=w,n.onMessage=_,n.canBeUsed=y,n.averageResponseTime=k,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var a="pubkey.broadcast-channel-0-",u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e){var t=c(),e=a+e,n=t.open(e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function d(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([u],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(r)})}function f(e,n){var r=e.transaction(u).objectStore(u),o=[];return new Promise(function(t){(function(){try{var e=IDBKeyRange.bound(n+1,1/0);return r.openCursor(e)}catch(e){return r.openCursor()}})().onsuccess=function(e){e=e.target.result;e?e.value.idn.lastCursorId&&(n.lastCursorId=e.id),e}).filter(function(e){return t=n,(e=e).uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time { - objectStore.openCursor().onsuccess = ev => { + openCursor().onsuccess = ev => { const cursor = ev.target.result; if (cursor) { if (cursor.value.id < lastCursorId + 1) {