broadcast-channel
Advanced tools
Comparing version 4.0.0 to 4.1.0
@@ -5,2 +5,8 @@ # CHANGELOG | ||
## 4.1.0 (2 August 2021) | ||
Bugfixes: | ||
- Fixed various problems with the module loading. Thanks [benmccann](https://github.com/benmccann) and [chbdetta](https://github.com/chbdetta) | ||
## 4.0.0 (15 July 2021) | ||
@@ -7,0 +13,0 @@ |
@@ -20,3 +20,3 @@ "use strict"; | ||
var NodeMethod = _interopRequireWildcard(require("../../src/methods/node.js")); | ||
var NodeMethod = _interopRequireWildcard(require("./methods/node.js")); | ||
@@ -30,3 +30,2 @@ var _util = require("./util"); | ||
// the line below will be removed from es5/browser builds | ||
// the non-transpiled code runs faster | ||
// order is important | ||
@@ -37,13 +36,6 @@ var METHODS = [_native["default"], // fastest | ||
function chooseMethod(options) { | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // process.browser check allows ES6 builds to be used on server or client. Bundlers like | ||
// Browserify, Webpack, etc. define process.browser and can then dead code eliminate the unused | ||
// import. However, we still use sed during build of es5/browser build to remove the import so | ||
// that it's also removed from non-minified version | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // the line below will be removed from es5/browser builds | ||
if (!process.browser) { | ||
// the line below will be removed from es5/browser builds | ||
chooseMethods.push(NodeMethod); | ||
} // directly chosen | ||
chooseMethods.push(NodeMethod); // directly chosen | ||
if (options.type) { | ||
@@ -50,0 +42,0 @@ if (options.type === 'simulate') { |
@@ -5,2 +5,35 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.cleanPipeName = cleanPipeName; | ||
exports.getPaths = getPaths; | ||
exports.ensureFoldersExist = ensureFoldersExist; | ||
exports.clearNodeFolder = clearNodeFolder; | ||
exports.socketPath = socketPath; | ||
exports.socketInfoPath = socketInfoPath; | ||
exports.createSocketInfoFile = createSocketInfoFile; | ||
exports.countChannelFolders = countChannelFolders; | ||
exports.createSocketEventEmitter = createSocketEventEmitter; | ||
exports.openClientConnection = openClientConnection; | ||
exports.writeMessage = writeMessage; | ||
exports.getReadersUuids = getReadersUuids; | ||
exports.messagePath = messagePath; | ||
exports.getAllMessages = getAllMessages; | ||
exports.getSingleMessage = getSingleMessage; | ||
exports.readMessage = readMessage; | ||
exports.cleanOldMessages = cleanOldMessages; | ||
exports.create = create; | ||
exports._filterMessage = _filterMessage; | ||
exports.handleMessagePing = handleMessagePing; | ||
exports.refreshReaderClients = refreshReaderClients; | ||
exports.postMessage = postMessage; | ||
exports.emitOverFastPath = emitOverFastPath; | ||
exports.onMessage = onMessage; | ||
exports.close = close; | ||
exports.canBeUsed = canBeUsed; | ||
exports.averageResponseTime = averageResponseTime; | ||
exports.microSeconds = microSeconds; | ||
exports.type = exports.TMP_FOLDER_BASE = void 0; | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
@@ -10,43 +43,39 @@ | ||
/** | ||
* this method is used in nodejs-environments. | ||
* The ipc is handled via sockets and file-writes to the tmp-folder | ||
*/ | ||
var util = require('util'); | ||
var _util = _interopRequireDefault(require("util")); | ||
var fs = require('fs'); | ||
var _fs = _interopRequireDefault(require("fs")); | ||
var os = require('os'); | ||
var _os = _interopRequireDefault(require("os")); | ||
var events = require('events'); | ||
var _events = _interopRequireDefault(require("events")); | ||
var net = require('net'); | ||
var _net = _interopRequireDefault(require("net")); | ||
var path = require('path'); | ||
var _path = _interopRequireDefault(require("path")); | ||
var micro = require('nano-time'); | ||
var _nanoTime = _interopRequireDefault(require("nano-time")); | ||
var rimraf = require('rimraf'); | ||
var _rimraf = _interopRequireDefault(require("rimraf")); | ||
var sha3_224 = require('js-sha3').sha3_224; | ||
var _jsSha = require("js-sha3"); | ||
var isNode = require('detect-node'); | ||
var _detectNode = _interopRequireDefault(require("detect-node")); | ||
var unload = require('unload'); | ||
var _unload = _interopRequireDefault(require("unload")); | ||
var fillOptionsWithDefaults = require('../../dist/lib/options.js').fillOptionsWithDefaults; | ||
var _options = require("../options.js"); | ||
var ownUtil = require('../../dist/lib/util.js'); | ||
var _util2 = require("../util.js"); | ||
var randomInt = ownUtil.randomInt; | ||
var randomToken = ownUtil.randomToken; | ||
var _obliviousSet = require("oblivious-set"); | ||
var _require = require('oblivious-set'), | ||
ObliviousSet = _require.ObliviousSet; | ||
/** | ||
* this method is used in nodejs-environments. | ||
* The ipc is handled via sockets and file-writes to the tmp-folder | ||
*/ | ||
/** | ||
* windows sucks, so we have handle windows-type of socket-paths | ||
* @link https://gist.github.com/domenic/2790533#gistcomment-331356 | ||
*/ | ||
function cleanPipeName(str) { | ||
@@ -62,12 +91,22 @@ if (process.platform === 'win32' && !str.startsWith('\\\\.\\pipe\\')) { | ||
var mkdir = util.promisify(fs.mkdir); | ||
var writeFile = util.promisify(fs.writeFile); | ||
var readFile = util.promisify(fs.readFile); | ||
var unlink = util.promisify(fs.unlink); | ||
var readdir = util.promisify(fs.readdir); | ||
var chmod = util.promisify(fs.chmod); | ||
var removeDir = util.promisify(rimraf); | ||
var mkdir = _util["default"].promisify(_fs["default"].mkdir); | ||
var writeFile = _util["default"].promisify(_fs["default"].writeFile); | ||
var readFile = _util["default"].promisify(_fs["default"].readFile); | ||
var unlink = _util["default"].promisify(_fs["default"].unlink); | ||
var readdir = _util["default"].promisify(_fs["default"].readdir); | ||
var chmod = _util["default"].promisify(_fs["default"].chmod); | ||
var removeDir = _util["default"].promisify(_rimraf["default"]); | ||
var OTHER_INSTANCES = {}; | ||
var TMP_FOLDER_NAME = 'pubkey.bc'; | ||
var TMP_FOLDER_BASE = path.join(os.tmpdir(), TMP_FOLDER_NAME); | ||
var TMP_FOLDER_BASE = _path["default"].join(_os["default"].tmpdir(), TMP_FOLDER_NAME); | ||
exports.TMP_FOLDER_BASE = TMP_FOLDER_BASE; | ||
var getPathsCache = new Map(); | ||
@@ -77,3 +116,3 @@ | ||
if (!getPathsCache.has(channelName)) { | ||
var channelHash = sha3_224(channelName); // use hash incase of strange characters | ||
var channelHash = (0, _jsSha.sha3_224)(channelName); // use hash incase of strange characters | ||
@@ -87,5 +126,9 @@ /** | ||
var channelFolder = 'A' + channelHash.substring(0, 20); | ||
var channelPathBase = path.join(TMP_FOLDER_BASE, channelFolder); | ||
var folderPathReaders = path.join(channelPathBase, 'rdrs'); | ||
var folderPathMessages = path.join(channelPathBase, 'messages'); | ||
var channelPathBase = _path["default"].join(TMP_FOLDER_BASE, channelFolder); | ||
var folderPathReaders = _path["default"].join(channelPathBase, 'rdrs'); | ||
var folderPathMessages = _path["default"].join(channelPathBase, 'messages'); | ||
var ret = { | ||
@@ -223,3 +266,5 @@ channelBase: channelPathBase, | ||
paths = paths || getPaths(channelName); | ||
var socketPath = path.join(paths.readers, readerUuid + '.s'); | ||
var socketPath = _path["default"].join(paths.readers, readerUuid + '.s'); | ||
return cleanPipeName(socketPath); | ||
@@ -230,3 +275,5 @@ } | ||
paths = paths || getPaths(channelName); | ||
var socketPath = path.join(paths.readers, readerUuid + '.json'); | ||
var socketPath = _path["default"].join(paths.readers, readerUuid + '.json'); | ||
return socketPath; | ||
@@ -349,4 +396,4 @@ } | ||
pathToSocket = socketPath(channelName, readerUuid, paths); | ||
emitter = new events.EventEmitter(); | ||
server = net.createServer(function (stream) { | ||
emitter = new _events["default"].EventEmitter(); | ||
server = _net["default"].createServer(function (stream) { | ||
stream.on('end', function () {}); | ||
@@ -458,3 +505,3 @@ stream.on('data', function (msg) { | ||
pathToSocket = socketPath(channelName, readerUuid); | ||
client = new net.Socket(); | ||
client = new _net["default"].Socket(); | ||
return _context12.abrupt("return", new Promise(function (res, rej) { | ||
@@ -487,5 +534,7 @@ client.connect(pathToSocket, function () { | ||
}; | ||
var token = randomToken(); | ||
var token = (0, _util2.randomToken)(); | ||
var fileName = time + '_' + readerUuid + '_' + token + '.json'; | ||
var msgPath = path.join(paths.messages, fileName); | ||
var msgPath = _path["default"].join(paths.messages, fileName); | ||
return writeFile(msgPath, JSON.stringify(writeObject)).then(function () { | ||
@@ -555,3 +604,3 @@ return { | ||
fileName = time + '_' + writerUuid + '_' + token + '.json'; | ||
msgPath = path.join(getPaths(channelName).messages, fileName); | ||
msgPath = _path["default"].join(getPaths(channelName).messages, fileName); | ||
return _context14.abrupt("return", msgPath); | ||
@@ -591,3 +640,3 @@ | ||
return { | ||
path: path.join(messagesPath, file), | ||
path: _path["default"].join(messagesPath, file), | ||
time: parseInt(split[0]), | ||
@@ -612,3 +661,3 @@ senderUuid: split[1], | ||
return { | ||
path: path.join(paths.messages, msgObj.t + '_' + msgObj.u + '_' + msgObj.to + '.json'), | ||
path: _path["default"].join(paths.messages, msgObj.t + '_' + msgObj.u + '_' + msgObj.to + '.json'), | ||
time: msgObj.t, | ||
@@ -663,2 +712,4 @@ senderUuid: msgObj.u, | ||
exports.type = type; | ||
function create(_x19) { | ||
@@ -686,7 +737,7 @@ return _create.apply(this, arguments); | ||
options = _args17.length > 1 && _args17[1] !== undefined ? _args17[1] : {}; | ||
options = fillOptionsWithDefaults(options); | ||
options = (0, _options.fillOptionsWithDefaults)(options); | ||
time = microSeconds(); | ||
paths = getPaths(channelName); | ||
ensureFolderExistsPromise = ensureFoldersExist(channelName, paths); | ||
uuid = randomToken(); | ||
uuid = (0, _util2.randomToken)(); | ||
state = { | ||
@@ -699,3 +750,3 @@ time: time, | ||
// contains all messages that have been emitted before | ||
emittedMessagesIds: new ObliviousSet(options.node.ttl * 2), | ||
emittedMessagesIds: new _obliviousSet.ObliviousSet(options.node.ttl * 2), | ||
messagesCallbackTime: null, | ||
@@ -707,3 +758,3 @@ messagesCallback: null, | ||
// ensure if process crashes, everything is cleaned up | ||
removeUnload: unload.add(function () { | ||
removeUnload: _unload["default"].add(function () { | ||
return close(state); | ||
@@ -1001,3 +1052,3 @@ }), | ||
if (randomInt(0, 20) === 0) { | ||
if ((0, _util2.randomInt)(0, 20) === 0) { | ||
/* await */ | ||
@@ -1078,3 +1129,3 @@ getAllMessages(channelState.channelName, channelState.paths).then(function (allMessages) { | ||
try { | ||
fs.unlinkSync(channelState.infoFilePath); | ||
_fs["default"].unlinkSync(channelState.infoFilePath); | ||
} catch (err) {} | ||
@@ -1096,3 +1147,3 @@ } | ||
function canBeUsed() { | ||
return isNode; | ||
return _detectNode["default"]; | ||
} | ||
@@ -1112,36 +1163,3 @@ /** | ||
function microSeconds() { | ||
return parseInt(micro.microseconds()); | ||
} | ||
module.exports = { | ||
TMP_FOLDER_BASE: TMP_FOLDER_BASE, | ||
cleanPipeName: cleanPipeName, | ||
getPaths: getPaths, | ||
ensureFoldersExist: ensureFoldersExist, | ||
clearNodeFolder: clearNodeFolder, | ||
socketPath: socketPath, | ||
socketInfoPath: socketInfoPath, | ||
createSocketInfoFile: createSocketInfoFile, | ||
countChannelFolders: countChannelFolders, | ||
createSocketEventEmitter: createSocketEventEmitter, | ||
openClientConnection: openClientConnection, | ||
writeMessage: writeMessage, | ||
getReadersUuids: getReadersUuids, | ||
messagePath: messagePath, | ||
getAllMessages: getAllMessages, | ||
getSingleMessage: getSingleMessage, | ||
readMessage: readMessage, | ||
cleanOldMessages: cleanOldMessages, | ||
type: type, | ||
create: create, | ||
_filterMessage: _filterMessage, | ||
handleMessagePing: handleMessagePing, | ||
refreshReaderClients: refreshReaderClients, | ||
postMessage: postMessage, | ||
emitOverFastPath: emitOverFastPath, | ||
onMessage: onMessage, | ||
close: close, | ||
canBeUsed: canBeUsed, | ||
averageResponseTime: averageResponseTime, | ||
microSeconds: microSeconds | ||
}; | ||
return parseInt(_nanoTime["default"].microseconds()); | ||
} |
@@ -626,3 +626,2 @@ (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ | ||
},{"./util.js":12,"@babel/runtime/helpers/interopRequireDefault":13,"unload":20}],6:[function(require,module,exports){ | ||
(function (process){(function (){ | ||
"use strict"; | ||
@@ -656,3 +655,2 @@ | ||
// the line below will be removed from es5/browser builds | ||
// the non-transpiled code runs faster | ||
// order is important | ||
@@ -663,13 +661,6 @@ var METHODS = [_native["default"], // fastest | ||
function chooseMethod(options) { | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // process.browser check allows ES6 builds to be used on server or client. Bundlers like | ||
// Browserify, Webpack, etc. define process.browser and can then dead code eliminate the unused | ||
// import. However, we still use sed during build of es5/browser build to remove the import so | ||
// that it's also removed from non-minified version | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // the line below will be removed from es5/browser builds | ||
if (!process.browser) { | ||
// the line below will be removed from es5/browser builds | ||
} // directly chosen | ||
if (options.type) { | ||
@@ -705,4 +696,3 @@ if (options.type === 'simulate') { | ||
} | ||
}).call(this)}).call(this,require('_process')) | ||
},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":14,"_process":18}],7:[function(require,module,exports){ | ||
},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":14}],7:[function(require,module,exports){ | ||
"use strict"; | ||
@@ -709,0 +699,0 @@ |
@@ -1,1 +0,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<s.length;e++)a(s[e]);return a}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.clearNodeFolder=function(e){e=(0,s.fillOptionsWithDefaults)(e);e=(0,i.chooseMethod)(e);return"node"===e.type?e.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},n.enforceOptions=function(e){r=e},n.BroadcastChannel=void 0;var r,o=e("./util.js"),i=e("./method-chooser.js"),s=e("./options.js"),e=function(e,t){var n;this.name=e,r&&(t=r),this.options=(0,s.fillOptionsWithDefaults)(t),this.method=(0,i.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,t=(n=this).method.create(n.name,n.options),(0,o.isPromise)(t)?(n._prepP=t).then(function(e){n._state=e}):n._state=t};function a(t,e,n){var r={time:t.method.microSeconds(),type:e,data:n};return(t._prepP||Promise.resolve()).then(function(){var e=t.method.postMessage(t._state,r);return t._uMP.add(e),e.catch().then(function(){return t._uMP.delete(e)}),e})}function u(e){return 0<e._addEL.message.length||0<e._addEL.internal.length}function c(e,t,n){e._addEL[t].push(n),function(e){{var t,n;!e._iL&&u(e)&&(t=function(t){e._addEL[t.type].forEach(function(e){t.time>=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(Array.from(e._uMP))}).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},get isClosed(){return this.closed}}},{"./method-chooser.js":6,"./options.js":11,"./util.js":12}],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,beLeader:e.beLeader}},{"./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}}),Object.defineProperty(n,"beLeader",{enumerable:!0,get:function(){return o.beLeader}});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.beLeader=u,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 s(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),o=r(e("unload")),s=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=[],this._dpL=function(){},this._dpLC=!1};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}function u(t){t.isLeader=!0;var e=o.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell"),"leader"!==e.context||"tell"!==e.action||t._dpLC||(t._dpLC=!0,t._dpL(),a(t,"tell"))};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}s.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 u(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){var t=!1;function n(){t||(t=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}i.applyOnce().then(function(){i.isLeader&&n()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&n()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&n()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},set onduplicate(e){this._dpL=e},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":12,"@babel/runtime/helpers/interopRequireDefault":13,unload:20}],6:[function(u,e,c){!function(a){!function(){"use strict";var e=u("@babel/runtime/helpers/interopRequireDefault");u("@babel/runtime/helpers/typeof");Object.defineProperty(c,"__esModule",{value:!0}),c.chooseMethod=function(t){var e=[].concat(t.methods,s).filter(Boolean);a.browser;if(t.type){if("simulate"===t.type)return o.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||i.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 method found in "+JSON.stringify(s.map(function(e){return e.type})))}};var t=e(u("./methods/native.js")),n=e(u("./methods/indexed-db.js")),r=e(u("./methods/localstorage.js")),o=e(u("./methods/simulate.js")),i=u("./util");var s=[t.default,n.default,r.default]}.call(this)}.call(this,u("_process"))},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":14,_process:18}],7:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=u,n.createDatabase=c,n.writeMessage=l,n.getAllMessages=function(e){var n=e.transaction(a).objectStore(a),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=d,n.removeMessageById=f,n.getOldMessages=p,n.cleanOldMessages=h,n.create=m,n.close=b,n.postMessage=g,n.onMessage=y,n.canBeUsed=_,n.averageResponseTime=w,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=e("oblivious-set"),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var r="pubkey.broadcast-channel-0-",a="messages";function u(){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 c(e){var n=u().open(r+e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(a,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function l(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([a],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(a).add(r)})}function d(e,n){var r=e.transaction(a).objectStore(a),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.id<n+1?e.continue(n+1):(o.push(e.value),e.continue()):t(o)}})}function f(e,t){var n=e.transaction([a],"readwrite").objectStore(a).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(a).objectStore(a),i=[];return new Promise(function(n){o.openCursor().onsuccess=function(e){var t,e=e.target.result;e&&(t=e.value).time<r?(i.push(t),e.continue()):n(i)}})}function h(t,e){return p(t,e).then(function(e){return Promise.all(e.map(function(e){return f(t,e.id)}))})}function m(n,r){return r=(0,s.fillOptionsWithDefaults)(r),c(n).then(function(e){var t={closed:!1,lastCursorId:0,channelName:n,options:r,uuid:(0,o.randomToken)(),eMIs:new i.ObliviousSet(2*r.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:e};return e.onclose=function(){t.closed=!0,r.idb.onclose&&r.idb.onclose()},function e(t){if(t.closed)return;v(t).then(function(){return(0,o.sleep)(t.options.idb.fallbackInterval)}).then(function(){return e(t)})}(t),t})}function v(n){return!n.closed&&n.messagesCallback?d(n.db,n.lastCursorId).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return e.id>n.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<t.messagesCallbackTime));var t}).sort(function(e,t){return e.time-t.time}).forEach(function(e){n.messagesCallback&&(n.eMIs.add(e.id),n.messagesCallback(e.data))}),Promise.resolve()}):Promise.resolve()}function b(e){e.closed=!0,e.db.close()}function g(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return l(e.db,e.uuid,t)}).then(function(){0===(0,o.randomInt)(0,10)&&h(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function y(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,v(e)}function _(){return!o.isNode&&!!u()}function w(e){return 2*e.idb.fallbackInterval}n.type="idb",n.default={create:m,close:b,onMessage:y,postMessage:g,canBeUsed:_,type:"idb",averageResponseTime:w,microSeconds:e}},{"../options":11,"../util.js":12,"oblivious-set":17}],8:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getLocalStorage=u,n.storageKey=c,n.postMessage=l,n.addStorageEventListener=d,n.removeStorageEventListener=f,n.create=p,n.close=h,n.onMessage=m,n.canBeUsed=v,n.averageResponseTime=b,n.default=n.type=n.microSeconds=void 0;var i=e("oblivious-set"),s=e("../options"),a=e("../util"),r=a.microSeconds;n.microSeconds=r;var o="pubkey.broadcastChannel-",e="localstorage";function u(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function c(e){return o+e}function l(o,i){return new Promise(function(r){(0,a.sleep)().then(function(){var e=c(o.channelName),t={token:(0,a.randomToken)(),time:(new Date).getTime(),data:i,uuid:o.uuid},n=JSON.stringify(t);u().setItem(e,n);t=document.createEvent("Event");t.initEvent("storage",!0,!0),t.key=e,t.newValue=n,window.dispatchEvent(t),r()})})}function d(e,t){var n=o+e,e=function(e){e.key===n&&t(JSON.parse(e.newValue))};return window.addEventListener("storage",e),e}function f(e){window.removeEventListener("storage",e)}function p(e,t){if(t=(0,s.fillOptionsWithDefaults)(t),!v())throw new Error("BroadcastChannel: localstorage cannot be used");var n=(0,a.randomToken)(),r=new i.ObliviousSet(t.localstorage.removeTimeout),o={channelName:e,uuid:n,eMIs:r};return o.listener=d(e,function(e){o.messagesCallback&&e.uuid!==n&&e.token&&!r.has(e.token)&&(e.data.time&&e.data.time<o.messagesCallbackTime||(r.add(e.token),o.messagesCallback(e.data)))}),o}function h(e){f(e.listener)}function m(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function v(){if(a.isNode)return!1;var e=u();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch(e){return!1}return!0}function b(){var e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")?240:120}n.type=e,n.default={create:p,close:h,onMessage:m,postMessage:l,canBeUsed:v,type:e,averageResponseTime:b,microSeconds:r}},{"../options":11,"../util":12,"oblivious-set":17}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=o,n.close=i,n.postMessage=s,n.onMessage=a,n.canBeUsed=u,n.averageResponseTime=c,n.default=n.type=n.microSeconds=void 0;var r=e("../util"),e=r.microSeconds;n.microSeconds=e;function o(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function i(e){e.bc.close(),e.subFns=[]}function s(e,t){try{return e.bc.postMessage(t,!1),Promise.resolve()}catch(e){return Promise.reject(e)}}function a(e,t){e.messagesCallback=t}function u(){if(r.isNode&&"undefined"==typeof window)return!1;if("function"!=typeof BroadcastChannel)return!1;if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}function c(){return 150}n.type="native",n.default={create:o,close:i,onMessage:a,postMessage:s,canBeUsed:u,type:"native",averageResponseTime:c,microSeconds:e}},{"../util":12}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=i,n.close=s,n.postMessage=a,n.onMessage=u,n.canBeUsed=c,n.averageResponseTime=l,n.default=n.type=n.microSeconds=void 0;var r=e("../util").microSeconds;n.microSeconds=r;e="simulate";n.type=e;var o=new Set;function i(e){e={name:e,messagesCallback:null};return o.add(e),e}function s(e){o.delete(e)}function a(t,n){return new Promise(function(e){return setTimeout(function(){Array.from(o).filter(function(e){return e.name===t.name}).filter(function(e){return e!==t}).filter(function(e){return!!e.messagesCallback}).forEach(function(e){return e.messagesCallback(n)}),e()},5)})}function u(e,t){e.messagesCallback=t}function c(){return!0}function l(){return 5}n.default={create:i,close:s,onMessage:u,postMessage:a,canBeUsed:c,type:e,averageResponseTime:l,microSeconds:r}},{"../util":12}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.fillOptionsWithDefaults=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],12:[function(e,t,o){!function(r){!function(){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.isPromise=function(e){return!(!e||"function"!=typeof e.then)},o.sleep=function(t){t=t||0;return new Promise(function(e){return setTimeout(e,t)})},o.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},o.randomToken=function(){return Math.random().toString(36).substring(2)},o.microSeconds=function(){var e=(new Date).getTime();return e===t?1e3*e+ ++n:(n=0,1e3*(t=e))},o.isNode=void 0;var t=0,n=0;var e="[object process]"===Object.prototype.toString.call(void 0!==r?r:0);o.isNode=e}.call(this)}.call(this,e("_process"))},{_process:18}],13:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.default=t.exports,t.exports.__esModule=!0},{}],14:[function(e,t,n){function r(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?t.exports=r=function(e){return typeof e}:t.exports=r=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.default=t.exports,t.exports.__esModule=!0,r(e)}t.exports=r,t.exports.default=t.exports,t.exports.__esModule=!0},{}],15:[function(e,t,n){},{}],16:[function(e,t,n){t.exports=!1},{}],17:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.now=n.removeTooOldValues=n.ObliviousSet=void 0;var r=(o.prototype.has=function(e){return this.set.has(e)},o.prototype.add=function(e){var t=this;this.timeMap.set(e,s()),this.set.add(e),setTimeout(function(){i(t)},0)},o.prototype.clear=function(){this.set.clear(),this.timeMap.clear()},o);function o(e){this.ttl=e,this.set=new Set,this.timeMap=new Map}function i(e){for(var t=s()-e.ttl,n=e.set[Symbol.iterator]();;){var r=n.next().value;if(!r)return;if(!(e.timeMap.get(r)<t))return;e.timeMap.delete(r),e.set.delete(r)}}function s(){return(new Date).getTime()}n.ObliviousSet=r,n.removeTooOldValues=i,n.now=s},{}],18:[function(e,t,n){var r,o,t=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(r===setTimeout)return setTimeout(t,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{o="function"==typeof clearTimeout?clearTimeout:s}catch(e){o=s}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&p())}function p(){if(!l){var e=a(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d<t;)u&&u[d].run();d=-1,t=c.length}u=null,l=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===s||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(e){try{return o.call(null,t)}catch(e){return o.call(this,t)}}}(e)}}function h(e,t){this.fun=e,this.array=t}function m(){}t.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];c.push(new h(e,t)),1!==c.length||l||a(p)},h.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=m,t.addListener=m,t.once=m,t.off=m,t.removeListener=m,t.removeAllListeners=m,t.emit=m,t.prependListener=m,t.prependOnceListener=m,t.listeners=function(e){return[]},t.binding=function(e){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(e){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}},{}],19:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0,n.default={add:function(e){"function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope||"function"==typeof window.addEventListener&&(window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0))}}},{}],20:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.add=c,n.runAll=l,n.removeAll=d,n.getSize=f,n.default=void 0;var o=r(e("detect-node")),i=r(e("./browser.js")),e=r(e("./node.js")),s=(o.default?e:i).default,a=new Set,u=!1;function c(e){if(u||(u=!0,s.add(l)),"function"!=typeof e)throw new Error("Listener is no function");return a.add(e),{remove:function(){return a.delete(e)},run:function(){return a.delete(e),e()}}}function l(){var t=[];return a.forEach(function(e){t.push(e()),a.delete(e)}),Promise.all(t)}function d(){a.clear()}function f(){return a.size}n.default={add:c,runAll:l,removeAll:d,getSize:f}},{"./browser.js":19,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":13,"detect-node":16}]},{},[2]); | ||
!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<s.length;e++)a(s[e]);return a}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.clearNodeFolder=function(e){e=(0,s.fillOptionsWithDefaults)(e);e=(0,i.chooseMethod)(e);return"node"===e.type?e.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},n.enforceOptions=function(e){r=e},n.BroadcastChannel=void 0;var r,o=e("./util.js"),i=e("./method-chooser.js"),s=e("./options.js"),e=function(e,t){var n;this.name=e,r&&(t=r),this.options=(0,s.fillOptionsWithDefaults)(t),this.method=(0,i.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,t=(n=this).method.create(n.name,n.options),(0,o.isPromise)(t)?(n._prepP=t).then(function(e){n._state=e}):n._state=t};function a(t,e,n){var r={time:t.method.microSeconds(),type:e,data:n};return(t._prepP||Promise.resolve()).then(function(){var e=t.method.postMessage(t._state,r);return t._uMP.add(e),e.catch().then(function(){return t._uMP.delete(e)}),e})}function u(e){return 0<e._addEL.message.length||0<e._addEL.internal.length}function c(e,t,n){e._addEL[t].push(n),function(e){{var t,n;!e._iL&&u(e)&&(t=function(t){e._addEL[t.type].forEach(function(e){t.time>=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(Array.from(e._uMP))}).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},get isClosed(){return this.closed}}},{"./method-chooser.js":6,"./options.js":11,"./util.js":12}],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,beLeader:e.beLeader}},{"./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}}),Object.defineProperty(n,"beLeader",{enumerable:!0,get:function(){return o.beLeader}});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.beLeader=u,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 s(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),o=r(e("unload")),s=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=[],this._dpL=function(){},this._dpLC=!1};function a(e,t){t={context:"leader",action:t,token:e.token};return e._channel.postInternal(t)}function u(t){t.isLeader=!0;var e=o.default.add(function(){return t.die()});t._unl.push(e);e=function(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell"),"leader"!==e.context||"tell"!==e.action||t._dpLC||(t._dpLC=!0,t._dpL(),a(t,"tell"))};return t._channel.addEventListener("internal",e),t._lstns.push(e),a(t,"tell")}s.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 u(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){var t=!1;function n(){t||(t=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}i.applyOnce().then(function(){i.isLeader&&n()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&n()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&n()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})),this._aLP},set onduplicate(e){this._dpL=e},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":12,"@babel/runtime/helpers/interopRequireDefault":13,unload:20}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");e("@babel/runtime/helpers/typeof");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 method found in "+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");var u=[o.default,i.default,n.default]},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":14}],7:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=u,n.createDatabase=c,n.writeMessage=l,n.getAllMessages=function(e){var n=e.transaction(a).objectStore(a),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=d,n.removeMessageById=f,n.getOldMessages=p,n.cleanOldMessages=h,n.create=m,n.close=b,n.postMessage=g,n.onMessage=y,n.canBeUsed=_,n.averageResponseTime=w,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=e("oblivious-set"),s=e("../options"),e=o.microSeconds;n.microSeconds=e;var r="pubkey.broadcast-channel-0-",a="messages";function u(){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 c(e){var n=u().open(r+e,1);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(a,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}})}function l(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([a],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(a).add(r)})}function d(e,n){var r=e.transaction(a).objectStore(a),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.id<n+1?e.continue(n+1):(o.push(e.value),e.continue()):t(o)}})}function f(e,t){var n=e.transaction([a],"readwrite").objectStore(a).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(a).objectStore(a),i=[];return new Promise(function(n){o.openCursor().onsuccess=function(e){var t,e=e.target.result;e&&(t=e.value).time<r?(i.push(t),e.continue()):n(i)}})}function h(t,e){return p(t,e).then(function(e){return Promise.all(e.map(function(e){return f(t,e.id)}))})}function m(n,r){return r=(0,s.fillOptionsWithDefaults)(r),c(n).then(function(e){var t={closed:!1,lastCursorId:0,channelName:n,options:r,uuid:(0,o.randomToken)(),eMIs:new i.ObliviousSet(2*r.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:e};return e.onclose=function(){t.closed=!0,r.idb.onclose&&r.idb.onclose()},function e(t){if(t.closed)return;v(t).then(function(){return(0,o.sleep)(t.options.idb.fallbackInterval)}).then(function(){return e(t)})}(t),t})}function v(n){return!n.closed&&n.messagesCallback?d(n.db,n.lastCursorId).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return e.id>n.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<t.messagesCallbackTime));var t}).sort(function(e,t){return e.time-t.time}).forEach(function(e){n.messagesCallback&&(n.eMIs.add(e.id),n.messagesCallback(e.data))}),Promise.resolve()}):Promise.resolve()}function b(e){e.closed=!0,e.db.close()}function g(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return l(e.db,e.uuid,t)}).then(function(){0===(0,o.randomInt)(0,10)&&h(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function y(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,v(e)}function _(){return!o.isNode&&!!u()}function w(e){return 2*e.idb.fallbackInterval}n.type="idb",n.default={create:m,close:b,onMessage:y,postMessage:g,canBeUsed:_,type:"idb",averageResponseTime:w,microSeconds:e}},{"../options":11,"../util.js":12,"oblivious-set":17}],8:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getLocalStorage=u,n.storageKey=c,n.postMessage=l,n.addStorageEventListener=d,n.removeStorageEventListener=f,n.create=p,n.close=h,n.onMessage=m,n.canBeUsed=v,n.averageResponseTime=b,n.default=n.type=n.microSeconds=void 0;var i=e("oblivious-set"),s=e("../options"),a=e("../util"),r=a.microSeconds;n.microSeconds=r;var o="pubkey.broadcastChannel-",e="localstorage";function u(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function c(e){return o+e}function l(o,i){return new Promise(function(r){(0,a.sleep)().then(function(){var e=c(o.channelName),t={token:(0,a.randomToken)(),time:(new Date).getTime(),data:i,uuid:o.uuid},n=JSON.stringify(t);u().setItem(e,n);t=document.createEvent("Event");t.initEvent("storage",!0,!0),t.key=e,t.newValue=n,window.dispatchEvent(t),r()})})}function d(e,t){var n=o+e,e=function(e){e.key===n&&t(JSON.parse(e.newValue))};return window.addEventListener("storage",e),e}function f(e){window.removeEventListener("storage",e)}function p(e,t){if(t=(0,s.fillOptionsWithDefaults)(t),!v())throw new Error("BroadcastChannel: localstorage cannot be used");var n=(0,a.randomToken)(),r=new i.ObliviousSet(t.localstorage.removeTimeout),o={channelName:e,uuid:n,eMIs:r};return o.listener=d(e,function(e){o.messagesCallback&&e.uuid!==n&&e.token&&!r.has(e.token)&&(e.data.time&&e.data.time<o.messagesCallbackTime||(r.add(e.token),o.messagesCallback(e.data)))}),o}function h(e){f(e.listener)}function m(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function v(){if(a.isNode)return!1;var e=u();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch(e){return!1}return!0}function b(){var e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")?240:120}n.type=e,n.default={create:p,close:h,onMessage:m,postMessage:l,canBeUsed:v,type:e,averageResponseTime:b,microSeconds:r}},{"../options":11,"../util":12,"oblivious-set":17}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=o,n.close=i,n.postMessage=s,n.onMessage=a,n.canBeUsed=u,n.averageResponseTime=c,n.default=n.type=n.microSeconds=void 0;var r=e("../util"),e=r.microSeconds;n.microSeconds=e;function o(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function i(e){e.bc.close(),e.subFns=[]}function s(e,t){try{return e.bc.postMessage(t,!1),Promise.resolve()}catch(e){return Promise.reject(e)}}function a(e,t){e.messagesCallback=t}function u(){if(r.isNode&&"undefined"==typeof window)return!1;if("function"!=typeof BroadcastChannel)return!1;if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}function c(){return 150}n.type="native",n.default={create:o,close:i,onMessage:a,postMessage:s,canBeUsed:u,type:"native",averageResponseTime:c,microSeconds:e}},{"../util":12}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=i,n.close=s,n.postMessage=a,n.onMessage=u,n.canBeUsed=c,n.averageResponseTime=l,n.default=n.type=n.microSeconds=void 0;var r=e("../util").microSeconds;n.microSeconds=r;e="simulate";n.type=e;var o=new Set;function i(e){e={name:e,messagesCallback:null};return o.add(e),e}function s(e){o.delete(e)}function a(t,n){return new Promise(function(e){return setTimeout(function(){Array.from(o).filter(function(e){return e.name===t.name}).filter(function(e){return e!==t}).filter(function(e){return!!e.messagesCallback}).forEach(function(e){return e.messagesCallback(n)}),e()},5)})}function u(e,t){e.messagesCallback=t}function c(){return!0}function l(){return 5}n.default={create:i,close:s,onMessage:u,postMessage:a,canBeUsed:c,type:e,averageResponseTime:l,microSeconds:r}},{"../util":12}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.fillOptionsWithDefaults=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],12:[function(e,t,o){!function(r){!function(){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.isPromise=function(e){return!(!e||"function"!=typeof e.then)},o.sleep=function(t){t=t||0;return new Promise(function(e){return setTimeout(e,t)})},o.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},o.randomToken=function(){return Math.random().toString(36).substring(2)},o.microSeconds=function(){var e=(new Date).getTime();return e===t?1e3*e+ ++n:(n=0,1e3*(t=e))},o.isNode=void 0;var t=0,n=0;var e="[object process]"===Object.prototype.toString.call(void 0!==r?r:0);o.isNode=e}.call(this)}.call(this,e("_process"))},{_process:18}],13:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.default=t.exports,t.exports.__esModule=!0},{}],14:[function(e,t,n){function r(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?t.exports=r=function(e){return typeof e}:t.exports=r=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.default=t.exports,t.exports.__esModule=!0,r(e)}t.exports=r,t.exports.default=t.exports,t.exports.__esModule=!0},{}],15:[function(e,t,n){},{}],16:[function(e,t,n){t.exports=!1},{}],17:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.now=n.removeTooOldValues=n.ObliviousSet=void 0;var r=(o.prototype.has=function(e){return this.set.has(e)},o.prototype.add=function(e){var t=this;this.timeMap.set(e,s()),this.set.add(e),setTimeout(function(){i(t)},0)},o.prototype.clear=function(){this.set.clear(),this.timeMap.clear()},o);function o(e){this.ttl=e,this.set=new Set,this.timeMap=new Map}function i(e){for(var t=s()-e.ttl,n=e.set[Symbol.iterator]();;){var r=n.next().value;if(!r)return;if(!(e.timeMap.get(r)<t))return;e.timeMap.delete(r),e.set.delete(r)}}function s(){return(new Date).getTime()}n.ObliviousSet=r,n.removeTooOldValues=i,n.now=s},{}],18:[function(e,t,n){var r,o,t=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(r===setTimeout)return setTimeout(t,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{o="function"==typeof clearTimeout?clearTimeout:s}catch(e){o=s}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&p())}function p(){if(!l){var e=a(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d<t;)u&&u[d].run();d=-1,t=c.length}u=null,l=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===s||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(e){try{return o.call(null,t)}catch(e){return o.call(this,t)}}}(e)}}function h(e,t){this.fun=e,this.array=t}function m(){}t.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];c.push(new h(e,t)),1!==c.length||l||a(p)},h.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=m,t.addListener=m,t.once=m,t.off=m,t.removeListener=m,t.removeAllListeners=m,t.emit=m,t.prependListener=m,t.prependOnceListener=m,t.listeners=function(e){return[]},t.binding=function(e){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(e){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}},{}],19:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0,n.default={add:function(e){"function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope||"function"==typeof window.addEventListener&&(window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0))}}},{}],20:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.add=c,n.runAll=l,n.removeAll=d,n.getSize=f,n.default=void 0;var o=r(e("detect-node")),i=r(e("./browser.js")),e=r(e("./node.js")),s=(o.default?e:i).default,a=new Set,u=!1;function c(e){if(u||(u=!0,s.add(l)),"function"!=typeof e)throw new Error("Listener is no function");return a.add(e),{remove:function(){return a.delete(e)},run:function(){return a.delete(e),e()}}}function l(){var t=[];return a.forEach(function(e){t.push(e()),a.delete(e)}),Promise.all(t)}function d(){a.clear()}function f(){return a.size}n.default={add:c,runAll:l,removeAll:d,getSize:f}},{"./browser.js":19,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":13,"detect-node":16}]},{},[2]); |
@@ -29,3 +29,2 @@ "use strict"; | ||
// the line below will be removed from es5/browser builds | ||
// the non-transpiled code runs faster | ||
// order is important | ||
@@ -36,13 +35,6 @@ var METHODS = [_native["default"], // fastest | ||
function chooseMethod(options) { | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // process.browser check allows ES6 builds to be used on server or client. Bundlers like | ||
// Browserify, Webpack, etc. define process.browser and can then dead code eliminate the unused | ||
// import. However, we still use sed during build of es5/browser build to remove the import so | ||
// that it's also removed from non-minified version | ||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // the line below will be removed from es5/browser builds | ||
if (!process.browser) { | ||
// the line below will be removed from es5/browser builds | ||
} // directly chosen | ||
if (options.type) { | ||
@@ -49,0 +41,0 @@ if (options.type === 'simulate') { |
@@ -5,2 +5,35 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.cleanPipeName = cleanPipeName; | ||
exports.getPaths = getPaths; | ||
exports.ensureFoldersExist = ensureFoldersExist; | ||
exports.clearNodeFolder = clearNodeFolder; | ||
exports.socketPath = socketPath; | ||
exports.socketInfoPath = socketInfoPath; | ||
exports.createSocketInfoFile = createSocketInfoFile; | ||
exports.countChannelFolders = countChannelFolders; | ||
exports.createSocketEventEmitter = createSocketEventEmitter; | ||
exports.openClientConnection = openClientConnection; | ||
exports.writeMessage = writeMessage; | ||
exports.getReadersUuids = getReadersUuids; | ||
exports.messagePath = messagePath; | ||
exports.getAllMessages = getAllMessages; | ||
exports.getSingleMessage = getSingleMessage; | ||
exports.readMessage = readMessage; | ||
exports.cleanOldMessages = cleanOldMessages; | ||
exports.create = create; | ||
exports._filterMessage = _filterMessage; | ||
exports.handleMessagePing = handleMessagePing; | ||
exports.refreshReaderClients = refreshReaderClients; | ||
exports.postMessage = postMessage; | ||
exports.emitOverFastPath = emitOverFastPath; | ||
exports.onMessage = onMessage; | ||
exports.close = close; | ||
exports.canBeUsed = canBeUsed; | ||
exports.averageResponseTime = averageResponseTime; | ||
exports.microSeconds = microSeconds; | ||
exports.type = exports.TMP_FOLDER_BASE = void 0; | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
@@ -10,43 +43,39 @@ | ||
/** | ||
* this method is used in nodejs-environments. | ||
* The ipc is handled via sockets and file-writes to the tmp-folder | ||
*/ | ||
var util = require('util'); | ||
var _util = _interopRequireDefault(require("util")); | ||
var fs = require('fs'); | ||
var _fs = _interopRequireDefault(require("fs")); | ||
var os = require('os'); | ||
var _os = _interopRequireDefault(require("os")); | ||
var events = require('events'); | ||
var _events = _interopRequireDefault(require("events")); | ||
var net = require('net'); | ||
var _net = _interopRequireDefault(require("net")); | ||
var path = require('path'); | ||
var _path = _interopRequireDefault(require("path")); | ||
var micro = require('nano-time'); | ||
var _nanoTime = _interopRequireDefault(require("nano-time")); | ||
var rimraf = require('rimraf'); | ||
var _rimraf = _interopRequireDefault(require("rimraf")); | ||
var sha3_224 = require('js-sha3').sha3_224; | ||
var _jsSha = require("js-sha3"); | ||
var isNode = require('detect-node'); | ||
var _detectNode = _interopRequireDefault(require("detect-node")); | ||
var unload = require('unload'); | ||
var _unload = _interopRequireDefault(require("unload")); | ||
var fillOptionsWithDefaults = require('../../dist/lib/options.js').fillOptionsWithDefaults; | ||
var _options = require("../options.js"); | ||
var ownUtil = require('../../dist/lib/util.js'); | ||
var _util2 = require("../util.js"); | ||
var randomInt = ownUtil.randomInt; | ||
var randomToken = ownUtil.randomToken; | ||
var _obliviousSet = require("oblivious-set"); | ||
var _require = require('oblivious-set'), | ||
ObliviousSet = _require.ObliviousSet; | ||
/** | ||
* this method is used in nodejs-environments. | ||
* The ipc is handled via sockets and file-writes to the tmp-folder | ||
*/ | ||
/** | ||
* windows sucks, so we have handle windows-type of socket-paths | ||
* @link https://gist.github.com/domenic/2790533#gistcomment-331356 | ||
*/ | ||
function cleanPipeName(str) { | ||
@@ -62,12 +91,22 @@ if (process.platform === 'win32' && !str.startsWith('\\\\.\\pipe\\')) { | ||
var mkdir = util.promisify(fs.mkdir); | ||
var writeFile = util.promisify(fs.writeFile); | ||
var readFile = util.promisify(fs.readFile); | ||
var unlink = util.promisify(fs.unlink); | ||
var readdir = util.promisify(fs.readdir); | ||
var chmod = util.promisify(fs.chmod); | ||
var removeDir = util.promisify(rimraf); | ||
var mkdir = _util["default"].promisify(_fs["default"].mkdir); | ||
var writeFile = _util["default"].promisify(_fs["default"].writeFile); | ||
var readFile = _util["default"].promisify(_fs["default"].readFile); | ||
var unlink = _util["default"].promisify(_fs["default"].unlink); | ||
var readdir = _util["default"].promisify(_fs["default"].readdir); | ||
var chmod = _util["default"].promisify(_fs["default"].chmod); | ||
var removeDir = _util["default"].promisify(_rimraf["default"]); | ||
var OTHER_INSTANCES = {}; | ||
var TMP_FOLDER_NAME = 'pubkey.bc'; | ||
var TMP_FOLDER_BASE = path.join(os.tmpdir(), TMP_FOLDER_NAME); | ||
var TMP_FOLDER_BASE = _path["default"].join(_os["default"].tmpdir(), TMP_FOLDER_NAME); | ||
exports.TMP_FOLDER_BASE = TMP_FOLDER_BASE; | ||
var getPathsCache = new Map(); | ||
@@ -77,3 +116,3 @@ | ||
if (!getPathsCache.has(channelName)) { | ||
var channelHash = sha3_224(channelName); // use hash incase of strange characters | ||
var channelHash = (0, _jsSha.sha3_224)(channelName); // use hash incase of strange characters | ||
@@ -87,5 +126,9 @@ /** | ||
var channelFolder = 'A' + channelHash.substring(0, 20); | ||
var channelPathBase = path.join(TMP_FOLDER_BASE, channelFolder); | ||
var folderPathReaders = path.join(channelPathBase, 'rdrs'); | ||
var folderPathMessages = path.join(channelPathBase, 'messages'); | ||
var channelPathBase = _path["default"].join(TMP_FOLDER_BASE, channelFolder); | ||
var folderPathReaders = _path["default"].join(channelPathBase, 'rdrs'); | ||
var folderPathMessages = _path["default"].join(channelPathBase, 'messages'); | ||
var ret = { | ||
@@ -223,3 +266,5 @@ channelBase: channelPathBase, | ||
paths = paths || getPaths(channelName); | ||
var socketPath = path.join(paths.readers, readerUuid + '.s'); | ||
var socketPath = _path["default"].join(paths.readers, readerUuid + '.s'); | ||
return cleanPipeName(socketPath); | ||
@@ -230,3 +275,5 @@ } | ||
paths = paths || getPaths(channelName); | ||
var socketPath = path.join(paths.readers, readerUuid + '.json'); | ||
var socketPath = _path["default"].join(paths.readers, readerUuid + '.json'); | ||
return socketPath; | ||
@@ -349,4 +396,4 @@ } | ||
pathToSocket = socketPath(channelName, readerUuid, paths); | ||
emitter = new events.EventEmitter(); | ||
server = net.createServer(function (stream) { | ||
emitter = new _events["default"].EventEmitter(); | ||
server = _net["default"].createServer(function (stream) { | ||
stream.on('end', function () {}); | ||
@@ -458,3 +505,3 @@ stream.on('data', function (msg) { | ||
pathToSocket = socketPath(channelName, readerUuid); | ||
client = new net.Socket(); | ||
client = new _net["default"].Socket(); | ||
return _context12.abrupt("return", new Promise(function (res, rej) { | ||
@@ -487,5 +534,7 @@ client.connect(pathToSocket, function () { | ||
}; | ||
var token = randomToken(); | ||
var token = (0, _util2.randomToken)(); | ||
var fileName = time + '_' + readerUuid + '_' + token + '.json'; | ||
var msgPath = path.join(paths.messages, fileName); | ||
var msgPath = _path["default"].join(paths.messages, fileName); | ||
return writeFile(msgPath, JSON.stringify(writeObject)).then(function () { | ||
@@ -555,3 +604,3 @@ return { | ||
fileName = time + '_' + writerUuid + '_' + token + '.json'; | ||
msgPath = path.join(getPaths(channelName).messages, fileName); | ||
msgPath = _path["default"].join(getPaths(channelName).messages, fileName); | ||
return _context14.abrupt("return", msgPath); | ||
@@ -591,3 +640,3 @@ | ||
return { | ||
path: path.join(messagesPath, file), | ||
path: _path["default"].join(messagesPath, file), | ||
time: parseInt(split[0]), | ||
@@ -612,3 +661,3 @@ senderUuid: split[1], | ||
return { | ||
path: path.join(paths.messages, msgObj.t + '_' + msgObj.u + '_' + msgObj.to + '.json'), | ||
path: _path["default"].join(paths.messages, msgObj.t + '_' + msgObj.u + '_' + msgObj.to + '.json'), | ||
time: msgObj.t, | ||
@@ -663,2 +712,4 @@ senderUuid: msgObj.u, | ||
exports.type = type; | ||
function create(_x19) { | ||
@@ -686,7 +737,7 @@ return _create.apply(this, arguments); | ||
options = _args17.length > 1 && _args17[1] !== undefined ? _args17[1] : {}; | ||
options = fillOptionsWithDefaults(options); | ||
options = (0, _options.fillOptionsWithDefaults)(options); | ||
time = microSeconds(); | ||
paths = getPaths(channelName); | ||
ensureFolderExistsPromise = ensureFoldersExist(channelName, paths); | ||
uuid = randomToken(); | ||
uuid = (0, _util2.randomToken)(); | ||
state = { | ||
@@ -699,3 +750,3 @@ time: time, | ||
// contains all messages that have been emitted before | ||
emittedMessagesIds: new ObliviousSet(options.node.ttl * 2), | ||
emittedMessagesIds: new _obliviousSet.ObliviousSet(options.node.ttl * 2), | ||
messagesCallbackTime: null, | ||
@@ -707,3 +758,3 @@ messagesCallback: null, | ||
// ensure if process crashes, everything is cleaned up | ||
removeUnload: unload.add(function () { | ||
removeUnload: _unload["default"].add(function () { | ||
return close(state); | ||
@@ -1001,3 +1052,3 @@ }), | ||
if (randomInt(0, 20) === 0) { | ||
if ((0, _util2.randomInt)(0, 20) === 0) { | ||
/* await */ | ||
@@ -1078,3 +1129,3 @@ getAllMessages(channelState.channelName, channelState.paths).then(function (allMessages) { | ||
try { | ||
fs.unlinkSync(channelState.infoFilePath); | ||
_fs["default"].unlinkSync(channelState.infoFilePath); | ||
} catch (err) {} | ||
@@ -1096,3 +1147,3 @@ } | ||
function canBeUsed() { | ||
return isNode; | ||
return _detectNode["default"]; | ||
} | ||
@@ -1112,36 +1163,3 @@ /** | ||
function microSeconds() { | ||
return parseInt(micro.microseconds()); | ||
} | ||
module.exports = { | ||
TMP_FOLDER_BASE: TMP_FOLDER_BASE, | ||
cleanPipeName: cleanPipeName, | ||
getPaths: getPaths, | ||
ensureFoldersExist: ensureFoldersExist, | ||
clearNodeFolder: clearNodeFolder, | ||
socketPath: socketPath, | ||
socketInfoPath: socketInfoPath, | ||
createSocketInfoFile: createSocketInfoFile, | ||
countChannelFolders: countChannelFolders, | ||
createSocketEventEmitter: createSocketEventEmitter, | ||
openClientConnection: openClientConnection, | ||
writeMessage: writeMessage, | ||
getReadersUuids: getReadersUuids, | ||
messagePath: messagePath, | ||
getAllMessages: getAllMessages, | ||
getSingleMessage: getSingleMessage, | ||
readMessage: readMessage, | ||
cleanOldMessages: cleanOldMessages, | ||
type: type, | ||
create: create, | ||
_filterMessage: _filterMessage, | ||
handleMessagePing: handleMessagePing, | ||
refreshReaderClients: refreshReaderClients, | ||
postMessage: postMessage, | ||
emitOverFastPath: emitOverFastPath, | ||
onMessage: onMessage, | ||
close: close, | ||
canBeUsed: canBeUsed, | ||
averageResponseTime: averageResponseTime, | ||
microSeconds: microSeconds | ||
}; | ||
return parseInt(_nanoTime["default"].microseconds()); | ||
} |
{ | ||
"name": "broadcast-channel", | ||
"version": "4.0.0", | ||
"version": "4.1.0", | ||
"description": "A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers and NodeJs", | ||
"exports": { | ||
"node": { | ||
"import": "./dist/esnode/index.js", | ||
"default": "./dist/es5node/index.js" | ||
}, | ||
"browser": { | ||
"import": "./dist/esbrowser/index.js", | ||
"default": "./dist/lib/index.es5.js" | ||
}, | ||
"./package.json": "./package.json" | ||
}, | ||
"homepage": "https://github.com/pubkey/broadcast-channel#readme", | ||
@@ -28,3 +39,3 @@ "keywords": [ | ||
"main": "./dist/es5node/index.js", | ||
"module": "./dist/es/index.js", | ||
"module": "./dist/esnode/index.js", | ||
"browser": "./dist/lib/index.es5.js", | ||
@@ -49,3 +60,4 @@ "sideEffects": false, | ||
"clear": "rimraf -rf ./dist && rimraf -rf ./gen", | ||
"build:es6": "rimraf -rf dist/es && cross-env NODE_ENV=es6 babel src --out-dir dist/es", | ||
"build:es6node": "rimraf -rf dist/esnode && cross-env NODE_ENV=es6 babel src --out-dir dist/esnode", | ||
"build:es6browser": "rimraf -rf dist/esbrowser && cross-env NODE_ENV=es6 babel src --out-dir dist/esbrowser && grep -rl NodeMethod dist/esbrowser/ | xargs sed -i 's/.*NodeMethod.*//'", | ||
"build:es5node": "cross-env NODE_ENV=es5 babel src --out-dir dist/es5node", | ||
@@ -61,3 +73,3 @@ "build:es5browser": "cross-env NODE_ENV=es5 babel src --out-dir dist/lib && grep -rl NodeMethod dist/lib/ | xargs sed -i 's/.*NodeMethod.*//'", | ||
"build:lib-browser:min": "uglifyjs --compress --mangle --output dist/lib/browser.min.js -- dist/lib/browser.js", | ||
"build": "npm run clear && concurrently \"npm run build:es6\" \"npm run build:es5node\" \"npm run build:es5browser\" \"npm run build:test\" && concurrently \"npm run build:index\" \"npm run build:browser\" \"npm run build:worker\" \"npm run build:iframe\" \"npm run build:leader-iframe\" && npm run build:lib-browser && npm run build:lib-browser:min", | ||
"build": "npm run clear && concurrently \"npm run build:es6node\" \"npm run build:es6browser\" \"npm run build:es5node\" \"npm run build:es5browser\" \"npm run build:test\" && concurrently \"npm run build:index\" \"npm run build:browser\" \"npm run build:worker\" \"npm run build:iframe\" \"npm run build:leader-iframe\" && npm run build:lib-browser && npm run build:lib-browser:min", | ||
"build:min": "uglifyjs --compress --mangle --output dist/lib/browserify.min.js -- dist/lib/browserify.index.js", | ||
@@ -88,4 +100,4 @@ "docs:only": "http-server ./docs --silent", | ||
"@babel/polyfill": "7.12.1", | ||
"@babel/preset-env": "7.14.8", | ||
"@babel/types": "7.14.8", | ||
"@babel/preset-env": "7.14.9", | ||
"@babel/types": "7.14.9", | ||
"@rollup/plugin-node-resolve": "13.0.4", | ||
@@ -102,3 +114,3 @@ "@types/core-js": "2.5.4", | ||
"cross-env": "7.0.3", | ||
"eslint": "7.31.0", | ||
"eslint": "7.32.0", | ||
"gzip-size-cli": "5.0.0", | ||
@@ -119,16 +131,16 @@ "http-server": "0.12.3", | ||
"karma-safari-launcher": "1.0.0", | ||
"mocha": "9.0.2", | ||
"mocha": "9.0.3", | ||
"pre-commit": "1.2.2", | ||
"random-int": "3.0.0", | ||
"random-token": "0.0.8", | ||
"rollup": "2.54.0", | ||
"rollup": "2.55.1", | ||
"rollup-plugin-terser": "7.0.2", | ||
"testcafe": "1.15.0", | ||
"testcafe": "1.15.1", | ||
"ts-node": "10.1.0", | ||
"typescript": "4.3.5", | ||
"uglify-js": "3.14.0", | ||
"uglify-js": "3.14.1", | ||
"watchify": "4.0.0", | ||
"webpack": "5.46.0", | ||
"webpack": "5.47.1", | ||
"webpack-cli": "4.7.2" | ||
} | ||
} |
@@ -6,3 +6,3 @@ import NativeMethod from './methods/native.js'; | ||
// the line below will be removed from es5/browser builds | ||
import * as NodeMethod from '../../src/methods/node.js'; // the non-transpiled code runs faster | ||
import * as NodeMethod from './methods/node.js'; | ||
@@ -23,10 +23,4 @@ import { | ||
// process.browser check allows ES6 builds to be used on server or client. Bundlers like | ||
// Browserify, Webpack, etc. define process.browser and can then dead code eliminate the unused | ||
// import. However, we still use sed during build of es5/browser build to remove the import so | ||
// that it's also removed from non-minified version | ||
if (!process.browser) { | ||
// the line below will be removed from es5/browser builds | ||
chooseMethods.push(NodeMethod); | ||
} | ||
// the line below will be removed from es5/browser builds | ||
chooseMethods.push(NodeMethod); | ||
@@ -33,0 +27,0 @@ // directly chosen |
@@ -6,19 +6,17 @@ /** | ||
const util = require('util'); | ||
const fs = require('fs'); | ||
const os = require('os'); | ||
const events = require('events'); | ||
const net = require('net'); | ||
const path = require('path'); | ||
const micro = require('nano-time'); | ||
const rimraf = require('rimraf'); | ||
const sha3_224 = require('js-sha3').sha3_224; | ||
const isNode = require('detect-node'); | ||
const unload = require('unload'); | ||
import util from 'util'; | ||
import fs from 'fs'; | ||
import os from 'os'; | ||
import events from 'events'; | ||
import net from 'net'; | ||
import path from 'path'; | ||
import micro from 'nano-time'; | ||
import rimraf from 'rimraf'; | ||
import { sha3_224 } from 'js-sha3'; | ||
import isNode from 'detect-node'; | ||
import unload from 'unload'; | ||
const fillOptionsWithDefaults = require('../../dist/lib/options.js').fillOptionsWithDefaults; | ||
const ownUtil = require('../../dist/lib/util.js'); | ||
const randomInt = ownUtil.randomInt; | ||
const randomToken = ownUtil.randomToken; | ||
const { ObliviousSet } = require('oblivious-set'); | ||
import { fillOptionsWithDefaults } from '../options.js'; | ||
import { randomInt, randomToken } from '../util.js'; | ||
import { ObliviousSet } from 'oblivious-set'; | ||
@@ -29,3 +27,3 @@ /** | ||
*/ | ||
function cleanPipeName(str) { | ||
export function cleanPipeName(str) { | ||
if ( | ||
@@ -53,3 +51,3 @@ process.platform === 'win32' && | ||
const TMP_FOLDER_NAME = 'pubkey.bc'; | ||
const TMP_FOLDER_BASE = path.join( | ||
export const TMP_FOLDER_BASE = path.join( | ||
os.tmpdir(), | ||
@@ -60,3 +58,3 @@ TMP_FOLDER_NAME | ||
function getPaths(channelName) { | ||
export function getPaths(channelName) { | ||
if (!getPathsCache.has(channelName)) { | ||
@@ -103,3 +101,3 @@ const channelHash = sha3_224(channelName); // use hash incase of strange characters | ||
async function ensureFoldersExist(channelName, paths) { | ||
export async function ensureFoldersExist(channelName, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -128,3 +126,3 @@ | ||
*/ | ||
async function clearNodeFolder() { | ||
export async function clearNodeFolder() { | ||
if (!TMP_FOLDER_BASE || TMP_FOLDER_BASE === '' || TMP_FOLDER_BASE === '/') { | ||
@@ -140,3 +138,3 @@ throw new Error('BroadcastChannel.clearNodeFolder(): path is wrong'); | ||
function socketPath(channelName, readerUuid, paths) { | ||
export function socketPath(channelName, readerUuid, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -150,3 +148,3 @@ const socketPath = path.join( | ||
function socketInfoPath(channelName, readerUuid, paths) { | ||
export function socketInfoPath(channelName, readerUuid, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -166,3 +164,3 @@ const socketPath = path.join( | ||
*/ | ||
function createSocketInfoFile(channelName, readerUuid, paths) { | ||
export function createSocketInfoFile(channelName, readerUuid, paths) { | ||
const pathToFile = socketInfoPath(channelName, readerUuid, paths); | ||
@@ -181,3 +179,3 @@ return writeFile( | ||
*/ | ||
async function countChannelFolders() { | ||
export async function countChannelFolders() { | ||
await ensureBaseFolderExists(); | ||
@@ -211,3 +209,3 @@ const folders = await readdir(TMP_FOLDER_BASE); | ||
*/ | ||
async function createSocketEventEmitter(channelName, readerUuid, paths) { | ||
export async function createSocketEventEmitter(channelName, readerUuid, paths) { | ||
const pathToSocket = socketPath(channelName, readerUuid, paths); | ||
@@ -245,3 +243,3 @@ | ||
async function openClientConnection(channelName, readerUuid) { | ||
export async function openClientConnection(channelName, readerUuid) { | ||
const pathToSocket = socketPath(channelName, readerUuid); | ||
@@ -264,3 +262,3 @@ const client = new net.Socket(); | ||
*/ | ||
function writeMessage(channelName, readerUuid, messageJson, paths) { | ||
export function writeMessage(channelName, readerUuid, messageJson, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -299,3 +297,3 @@ const time = microSeconds(); | ||
*/ | ||
async function getReadersUuids(channelName, paths) { | ||
export async function getReadersUuids(channelName, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -311,3 +309,3 @@ const readersPath = paths.readers; | ||
async function messagePath(channelName, time, token, writerUuid) { | ||
export async function messagePath(channelName, time, token, writerUuid) { | ||
const fileName = time + '_' + writerUuid + '_' + token + '.json'; | ||
@@ -322,3 +320,3 @@ | ||
async function getAllMessages(channelName, paths) { | ||
export async function getAllMessages(channelName, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -343,3 +341,3 @@ const messagesPath = paths.messages; | ||
function getSingleMessage(channelName, msgObj, paths) { | ||
export function getSingleMessage(channelName, msgObj, paths) { | ||
paths = paths || getPaths(channelName); | ||
@@ -359,3 +357,3 @@ | ||
function readMessage(messageObj) { | ||
export function readMessage(messageObj) { | ||
return readFile(messageObj.path, 'utf8') | ||
@@ -365,3 +363,3 @@ .then(content => JSON.parse(content)); | ||
async function cleanOldMessages(messageObjects, ttl) { | ||
export async function cleanOldMessages(messageObjects, ttl) { | ||
const olderThen = Date.now() - ttl; | ||
@@ -377,3 +375,3 @@ await Promise.all( | ||
const type = 'node'; | ||
export const type = 'node'; | ||
@@ -384,3 +382,3 @@ /** | ||
*/ | ||
async function create(channelName, options = {}) { | ||
export async function create(channelName, options = {}) { | ||
options = fillOptionsWithDefaults(options); | ||
@@ -446,3 +444,3 @@ const time = microSeconds(); | ||
function _filterMessage(msgObj, state) { | ||
export function _filterMessage(msgObj, state) { | ||
if (msgObj.senderUuid === state.uuid) return false; // not send by own | ||
@@ -462,3 +460,3 @@ if (state.emittedMessagesIds.has(msgObj.token)) return false; // not already emitted | ||
*/ | ||
async function handleMessagePing(state, msgObj) { | ||
export async function handleMessagePing(state, msgObj) { | ||
@@ -511,3 +509,3 @@ /** | ||
*/ | ||
function refreshReaderClients(channelState) { | ||
export function refreshReaderClients(channelState) { | ||
return getReadersUuids(channelState.channelName, channelState.paths) | ||
@@ -553,3 +551,3 @@ .then(otherReaders => { | ||
*/ | ||
function postMessage(channelState, messageJson) { | ||
export function postMessage(channelState, messageJson) { | ||
const writePromise = writeMessage( | ||
@@ -606,3 +604,3 @@ channelState.channelName, | ||
*/ | ||
function emitOverFastPath(state, msgObj, messageJson) { | ||
export function emitOverFastPath(state, msgObj, messageJson) { | ||
if (!state.options.node.useFastPath) return; // disabled | ||
@@ -625,3 +623,3 @@ const others = OTHER_INSTANCES[state.channelName].filter(s => s !== state); | ||
function onMessage(channelState, fn, time = microSeconds()) { | ||
export function onMessage(channelState, fn, time = microSeconds()) { | ||
channelState.messagesCallbackTime = time; | ||
@@ -636,3 +634,3 @@ channelState.messagesCallback = fn; | ||
*/ | ||
function close(channelState) { | ||
export function close(channelState) { | ||
if (channelState.closed) return; | ||
@@ -673,3 +671,3 @@ channelState.closed = true; | ||
function canBeUsed() { | ||
export function canBeUsed() { | ||
return isNode; | ||
@@ -684,41 +682,8 @@ } | ||
*/ | ||
function averageResponseTime() { | ||
export function averageResponseTime() { | ||
return 200; | ||
} | ||
function microSeconds() { | ||
export function microSeconds() { | ||
return parseInt(micro.microseconds()); | ||
} | ||
module.exports = { | ||
TMP_FOLDER_BASE, | ||
cleanPipeName, | ||
getPaths, | ||
ensureFoldersExist, | ||
clearNodeFolder, | ||
socketPath, | ||
socketInfoPath, | ||
createSocketInfoFile, | ||
countChannelFolders, | ||
createSocketEventEmitter, | ||
openClientConnection, | ||
writeMessage, | ||
getReadersUuids, | ||
messagePath, | ||
getAllMessages, | ||
getSingleMessage, | ||
readMessage, | ||
cleanOldMessages, | ||
type, | ||
create, | ||
_filterMessage, | ||
handleMessagePing, | ||
refreshReaderClients, | ||
postMessage, | ||
emitOverFastPath, | ||
onMessage, | ||
close, | ||
canBeUsed, | ||
averageResponseTime, | ||
microSeconds | ||
}; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
449164
82
11714
10
5