UNPKG

redux-state-sync

Version:

A middleware for redux to sync state in different tabs

2 lines 19.2 kB
!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.reduxStateSync=n():e.reduxStateSync=n()}(window,(function(){return function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=3)}([function(e,n,t){"use strict";(function(e){function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise((function(n){return setTimeout(n,e)}))}function i(e,n){return Math.floor(Math.random()*(n-e+1)+e)}function a(){return Math.random().toString(36).substring(2)}t.d(n,"b",(function(){return r})),t.d(n,"f",(function(){return o})),t.d(n,"d",(function(){return i})),t.d(n,"e",(function(){return a})),t.d(n,"c",(function(){return c})),t.d(n,"a",(function(){return l}));var s=0,u=0;function c(){var e=(new Date).getTime();return e===s?1e3*e+ ++u:(s=e,u=0,1e3*e)}var l="[object process]"===Object.prototype.toString.call(void 0!==e?e:0)}).call(this,t(4))},function(e,n){e.exports=!1},function(e,n){},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initMessageListener=n.initStateWithPrevTab=n.withReduxStateSync=n.createReduxStateSync=n.createStateSyncMiddleware=n.WINDOW_STATE_SYNC_ID=n.INIT_MESSAGE_LISTENER=n.RECEIVE_INIT_STATE=n.SEND_INIT_STATE=n.GET_INIT_STATE=void 0,n.generateUuidForAction=h,n.isActionAllowed=p,n.isActionSynced=function(e){return!!e.$isSync},n.MessageListener=m;var r=t(6),o=0,i=n.GET_INIT_STATE="&_GET_INIT_STATE",a=n.SEND_INIT_STATE="&_SEND_INIT_STATE",s=n.RECEIVE_INIT_STATE="&_RECEIVE_INIT_STATE",u=n.INIT_MESSAGE_LISTENER="&_INIT_MESSAGE_LISTENER",c={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:void 0,prepareState:function(e){return e},receiveState:function(e,n){return n}};function l(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function f(){return""+l()+l()+"-"+l()+"-"+l()+"-"+l()+"-"+l()+l()+l()}var d=n.WINDOW_STATE_SYNC_ID=f();function h(e){var n=e;return n.$uuid=f(),n.$wuid=d,n}function p(e){var n=e.predicate,t=e.blacklist,r=e.whitelist,o=function(){return!0};return n&&"function"==typeof n?o=n:Array.isArray(t)?o=function(e){return t.indexOf(e.type)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e.type)>=0}),o}function m(e){var n=e.channel,t=e.dispatch,r=e.allowed,u=!1,c={};this.handleOnMessage=function(e){var n;e.$wuid!==d&&(e.type!==s&&e.$uuid&&e.$uuid!==o&&(e.type!==i||c[e.$wuid]?e.type!==a||c[e.$wuid]?r(e)&&(o=e.$uuid,t(Object.assign(e,{$isSync:!0}))):u||(u=!0,t((n=e.payload,{type:s,payload:n}))):(c[e.$wuid]=!0,t({type:a}))))},this.messageChannel=n,this.messageChannel.onmessage=this.handleOnMessage}n.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,n=p(e),t=new r.BroadcastChannel(e.channel,e.broadcastChannelOption),s=e.prepareState||c.prepareState,u=null;return function(e){var r=e.getState,c=e.dispatch;return function(e){return function(l){if(u||(u=new m({channel:t,dispatch:c,allowed:n})),l&&!l.$uuid){var f=h(l);o=f.$uuid;try{if(l.type===a)return r()&&(f.payload=s(r()),t.postMessage(f)),e(l);(n(f)||l.type===i)&&t.postMessage(f)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(Object.assign(l,{$isSync:void 0!==l.$isSync&&l.$isSync}))}}}};var v=n.createReduxStateSync=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.receiveState;return function(t,r){var o=t;return r.type===s&&(o=n(t,r.payload)),e(o,r)}};n.withReduxStateSync=v,n.initStateWithPrevTab=function(e){(0,e.dispatch)({type:i})},n.initMessageListener=function(e){(0,e.dispatch)({type:u})}},function(e,n){var t,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,c=[],l=!1,f=-1;function d(){l&&u&&(l=!1,u.length?c=u.concat(c):f=-1,c.length&&h())}function h(){if(!l){var e=s(d);l=!0;for(var n=c.length;n;){for(u=c,c=[];++f<n;)u&&u[f].run();f=-1,n=c.length}u=null,l=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(n){try{return r.call(null,e)}catch(n){return r.call(this,e)}}}(e)}}function p(e,n){this.fun=e,this.array=n}function m(){}o.nextTick=function(e){var n=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)n[t-1]=arguments[t];c.push(new p(e,n)),1!==c.length||l||s(h)},p.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=m,o.addListener=m,o.once=m,o.off=m,o.removeListener=m,o.removeAllListeners=m,o.emit=m,o.prependListener=m,o.prependOnceListener=m,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,n){},function(e,n,t){"use strict";t.r(n),t.d(n,"BroadcastChannel",(function(){return I})),t.d(n,"clearNodeFolder",(function(){return k})),t.d(n,"enforceOptions",(function(){return L})),t.d(n,"createLeaderElection",(function(){return U}));var r=t(0);var o={create:function(e){var n={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return n.bc.onmessage=function(e){n.messagesCallback&&n.messagesCallback(e.data)},n},close:function(e){e.bc.close(),e.subFns=[]},onMessage:function(e,n){e.messagesCallback=n},postMessage:function(e,n){e.bc.postMessage(n,!1)},canBeUsed:function(){if(r.a&&"undefined"==typeof window)return!1;if("function"==typeof BroadcastChannel){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}return!1},type:"native",averageResponseTime:function(){return 150},microSeconds:r.c};function i(){return(new Date).getTime()}var a=function(e){var n=new Set,t=new Map;this.has=n.has.bind(n),this.add=function(r){t.set(r,i()),n.add(r),function(){var r=i()-e,o=n[Symbol.iterator]();for(;;){var a=o.next().value;if(!a)return;if(!(t.get(a)<r))return;t.delete(a),n.delete(a)}}()},this.clear=function(){n.clear(),t.clear()}};function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=JSON.parse(JSON.stringify(e));return void 0===n.webWorkerSupport&&(n.webWorkerSupport=!0),n.idb||(n.idb={}),n.idb.ttl||(n.idb.ttl=45e3),n.idb.fallbackInterval||(n.idb.fallbackInterval=150),n.localstorage||(n.localstorage={}),n.localstorage.removeTimeout||(n.localstorage.removeTimeout=6e4),e.methods&&(n.methods=e.methods),n.node||(n.node={}),n.node.ttl||(n.node.ttl=12e4),void 0===n.node.useFastPath&&(n.node.useFastPath=!0),n}var u=r.c;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,n){return function(e,n){var t=(new Date).getTime()-n,r=e.transaction("messages").objectStore("messages"),o=[];return new Promise((function(e){r.openCursor().onsuccess=function(n){var r=n.target.result;if(r){var i=r.value;if(!(i.time<t))return void e(o);o.push(i),r.continue()}else e(o)}}))}(e,n).then((function(n){return Promise.all(n.map((function(n){return function(e,n){var t=e.transaction(["messages"],"readwrite").objectStore("messages").delete(n);return new Promise((function(e){t.onsuccess=function(){return e()}}))}(e,n.id)})))}))}function f(e){return e.closed?Promise.resolve():e.messagesCallback?(n=e.db,t=e.lastCursorId,r=n.transaction("messages").objectStore("messages"),o=[],i=IDBKeyRange.bound(t+1,1/0),new Promise((function(e){r.openCursor(i).onsuccess=function(n){var t=n.target.result;t?(o.push(t.value),t.continue()):e(o)}}))).then((function(n){return n.filter((function(e){return!!e})).map((function(n){return n.id>e.lastCursorId&&(e.lastCursorId=n.id),n})).filter((function(n){return function(e,n){return e.uuid!==n.uuid&&(!n.eMIs.has(e.id)&&!(e.data.time<n.messagesCallbackTime))}(n,e)})).sort((function(e,n){return e.time-n.time})).forEach((function(n){e.messagesCallback&&(e.eMIs.add(n.id),e.messagesCallback(n.data))})),Promise.resolve()})):Promise.resolve();var n,t,r,o,i}var d={create:function(e,n){return n=s(n),function(e){var n="pubkey.broadcast-channel-0-"+e,t=c().open(n,1);return t.onupgradeneeded=function(e){e.target.result.createObjectStore("messages",{keyPath:"id",autoIncrement:!0})},new Promise((function(e,n){t.onerror=function(e){return n(e)},t.onsuccess=function(){e(t.result)}}))}(e).then((function(t){var o={closed:!1,lastCursorId:0,channelName:e,options:n,uuid:Object(r.e)(),eMIs:new a(2*n.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:t};return function e(n){if(n.closed)return;f(n).then((function(){return Object(r.f)(n.options.idb.fallbackInterval)})).then((function(){return e(n)}))}(o),o}))},close:function(e){e.closed=!0,e.db.close()},onMessage:function(e,n,t){e.messagesCallbackTime=t,e.messagesCallback=n,f(e)},postMessage:function(e,n){return e.writeBlockPromise=e.writeBlockPromise.then((function(){return function(e,n,t){var r={uuid:n,time:(new Date).getTime(),data:t},o=e.transaction(["messages"],"readwrite");return new Promise((function(e,n){o.oncomplete=function(){return e()},o.onerror=function(e){return n(e)},o.objectStore("messages").add(r)}))}(e.db,e.uuid,n)})).then((function(){0===Object(r.d)(0,10)&&l(e.db,e.options.idb.ttl)})),e.writeBlockPromise},canBeUsed:function(){return!r.a&&!!c()},type:"idb",averageResponseTime:function(e){return 2*e.idb.fallbackInterval},microSeconds:u},h=r.c;function p(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function m(e){return"pubkey.broadcastChannel-"+e}function v(){if(r.a)return!1;var e=p();if(!e)return!1;try{var n="__broadcastchannel_check";e.setItem(n,"works"),e.removeItem(n)}catch(e){return!1}return!0}var g={create:function(e,n){if(n=s(n),!v())throw new Error("BroadcastChannel: localstorage cannot be used");var t=Object(r.e)(),o=new a(n.localstorage.removeTimeout),i={channelName:e,uuid:t,eMIs:o};return i.listener=function(e,n){var t=m(e),r=function(e){e.key===t&&n(JSON.parse(e.newValue))};return window.addEventListener("storage",r),r}(e,(function(e){i.messagesCallback&&e.uuid!==t&&e.token&&!o.has(e.token)&&(e.data.time&&e.data.time<i.messagesCallbackTime||(o.add(e.token),i.messagesCallback(e.data)))})),i},close:function(e){var n;n=e.listener,window.removeEventListener("storage",n)},onMessage:function(e,n,t){e.messagesCallbackTime=t,e.messagesCallback=n},postMessage:function(e,n){return new Promise((function(t){Object(r.f)().then((function(){var o=m(e.channelName),i={token:Object(r.e)(),time:(new Date).getTime(),data:n,uuid:e.uuid},a=JSON.stringify(i);p().setItem(o,a);var s=document.createEvent("Event");s.initEvent("storage",!0,!0),s.key=o,s.newValue=a,window.dispatchEvent(s),t()}))}))},canBeUsed:v,type:"localstorage",averageResponseTime:function(){var e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")?240:120},microSeconds:h},y=r.c,b=new Set;var w={create:function(e){var n={name:e,messagesCallback:null};return b.add(n),n},close:function(e){b.delete(e)},onMessage:function(e,n){e.messagesCallback=n},postMessage:function(e,n){return new Promise((function(t){return setTimeout((function(){Array.from(b).filter((function(n){return n.name===e.name})).filter((function(n){return n!==e})).filter((function(e){return!!e.messagesCallback})).forEach((function(e){return e.messagesCallback(n)})),t()}),5)}))},canBeUsed:function(){return!0},type:"simulate",averageResponseTime:function(){return 5},microSeconds:y},_=[o,d,g];if(r.a){var S=t(5);"function"==typeof S.canBeUsed&&_.push(S)}function E(e){var n=[].concat(e.methods,_).filter(Boolean);if(e.type){if("simulate"===e.type)return w;var t=n.find((function(n){return n.type===e.type}));if(t)return t;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||r.a||(n=n.filter((function(e){return"idb"!==e.type})));var o=n.find((function(e){return e.canBeUsed()}));if(o)return o;throw new Error("No useable methode found:"+JSON.stringify(_.map((function(e){return e.type}))))}var T,I=function(e,n){var t,o;this.name=e,T&&(n=T),this.options=s(n),this.method=E(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._befC=[],this._prepP=null,o=(t=this).method.create(t.name,t.options),Object(r.b)(o)?(t._prepP=o,o.then((function(e){t._state=e}))):t._state=o};function k(e){var n=E(e=s(e));return"node"===n.type?n.clearNodeFolder().then((function(){return!0})):Promise.resolve(!1)}function L(e){T=e}function P(e,n,t){var r={time:e.method.microSeconds(),type:n,data:t};return(e._prepP?e._prepP:Promise.resolve()).then((function(){return e.method.postMessage(e._state,r)}))}function C(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function M(e,n,t){e._addEL[n].push(t),function(e){if(!e._iL&&C(e)){var n=function(n){e._addEL[n.type].forEach((function(e){n.time>=e.time&&e.fn(n.data)}))},t=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,n,t)})):(e._iL=!0,e.method.onMessage(e._state,n,t))}}(e)}function O(e,n,t){e._addEL[n]=e._addEL[n].filter((function(e){return e!==t})),function(e){if(e._iL&&!C(e)){e._iL=!1;var n=e.method.microSeconds();e.method.onMessage(e._state,null,n)}}(e)}I._pubkey=!0,I.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return P(this,"message",e)},postInternal:function(e){return P(this,"internal",e)},set onmessage(e){var n={time:this.method.microSeconds(),fn:e};O(this,"message",this._onML),e&&"function"==typeof e?(this._onML=n,M(this,"message",n)):this._onML=null},addEventListener:function(e,n){M(this,e,{time:this.method.microSeconds(),fn:n})},removeEventListener:function(e,n){O(this,e,this._addEL[e].find((function(e){return e.fn===n})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var n=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],n.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}};var A=t(1),N=t.n(A);var x={add:function(e){if("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope);else{if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",(function(){e()}),!0),window.addEventListener("unload",(function(){e()}),!0)}}},j=t(2),B=t.n(j),D=N.a?B.a:x,R=new Set,$=!1;function W(){var e=[];return R.forEach((function(n){e.push(n()),R.delete(n)})),Promise.all(e)}var G={add:function(e){if($||($=!0,D.add(W)),"function"!=typeof e)throw new Error("Listener is no function");return R.add(e),{remove:function(){return R.delete(e)},run:function(){return R.delete(e),e()}}},runAll:W,removeAll:function(){R.clear()},getSize:function(){return R.size}},F=function(e,n){this._channel=e,this._options=n,this.isLeader=!1,this.isDead=!1,this.token=Object(r.e)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function J(e,n){var t={context:"leader",action:n,token:e.token};return e._channel.postInternal(t)}function U(e,n){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");n=function(e,n){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=n.method.averageResponseTime(n.options)),e}(n,e);var t=new F(e,n);return e._befC.push((function(){return t.die()})),e._leaderElector=t,t}F.prototype={applyOnce:function(){var e=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);this._isApl=!0;var n=!1,t=[],o=function(r){"leader"===r.context&&r.token!=e.token&&(t.push(r),"apply"===r.action&&r.token>e.token&&(n=!0),"tell"===r.action&&(n=!0))};return this._channel.addEventListener("internal",o),J(this,"apply").then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return n?Promise.reject(new Error):J(e,"apply")})).then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return n?Promise.reject(new Error):J(e)})).then((function(){return function(e){e.isLeader=!0;var n=G.add((function(){return e.die()}));e._unl.push(n);var t=function(n){"leader"===n.context&&"apply"===n.action&&J(e,"tell")};return e._channel.addEventListener("internal",t),e._lstns.push(t),J(e,"tell")}(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(n){return e._channel.removeEventListener("internal",o),e._isApl=!1,!n&&e._reApply?(e._reApply=!1,e.applyOnce()):n}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(n){var t=!1,r=function(){t||(t=!0,clearInterval(o),e._channel.removeEventListener("internal",i),n(!0))};e.applyOnce().then((function(){e.isLeader&&r()}));var o=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&r()}))}),e._options.fallbackInterval);e._invs.push(o);var i=function(n){"leader"===n.context&&"death"===n.action&&e.applyOnce().then((function(){e.isLeader&&r()}))};e._channel.addEventListener("internal",i),e._lstns.push(i)}))),this._aLP},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(n){return e._channel.removeEventListener("internal",n)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),J(this,"death")}}}])})); //# sourceMappingURL=syncState.umd.min.js.map