@metamask/browser-playground 0.6.6 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/build/asset-manifest.json +9 -3
- package/build/index.html +1 -1
- package/build/static/js/127.6f28ac63.chunk.js +3 -0
- package/build/static/js/127.6f28ac63.chunk.js.LICENSE.txt +1 -0
- package/build/static/js/127.6f28ac63.chunk.js.map +1 -0
- package/build/static/js/288.51cc5192.chunk.js +3 -0
- package/build/static/js/288.51cc5192.chunk.js.LICENSE.txt +3 -0
- package/build/static/js/288.51cc5192.chunk.js.map +1 -0
- package/build/static/js/921.58d10f34.chunk.js +2 -0
- package/build/static/js/921.58d10f34.chunk.js.map +1 -0
- package/build/static/js/main.2f01c3f9.js +3 -0
- package/build/static/js/{main.8cb80a7d.js.LICENSE.txt → main.2f01c3f9.js.LICENSE.txt} +0 -6
- package/build/static/js/main.2f01c3f9.js.map +1 -0
- package/package.json +3 -3
- package/build/static/js/main.8cb80a7d.js +0 -3
- package/build/static/js/main.8cb80a7d.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";(self.webpackChunk_metamask_browser_playground=self.webpackChunk_metamask_browser_playground||[]).push([[921],{2027:(e,t,n)=>{n.r(t),n.d(t,{MAX:()=>s,NIL:()=>i,parse:()=>o,stringify:()=>c.A,v1:()=>l,v1ToV6:()=>d,v3:()=>C,v4:()=>k.A,v5:()=>N,v6:()=>A,v6ToV1:()=>D,v7:()=>j,validate:()=>r.A,version:()=>M});const s="ffffffff-ffff-ffff-ffff-ffffffffffff",i="00000000-0000-0000-0000-000000000000";var r=n(4282);const o=function(e){if(!(0,r.A)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};var c=n(2188),a=n(3648);const h={};function u(e,t,n,s,i,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0;if(e.length<16)throw new Error("Random bytes length must be >= 16");if(r){if(o<0||o+16>r.length)throw new RangeError("UUID byte range ".concat(o,":").concat(o+15," is out of buffer bounds"))}else r=new Uint8Array(16),o=0;null!==t&&void 0!==t||(t=Date.now()),null!==n&&void 0!==n||(n=0),null!==s&&void 0!==s||(s=16383&(e[8]<<8|e[9])),null!==i&&void 0!==i||(i=e.slice(10,16));const c=(1e4*(268435455&(t+=122192928e5))+n)%4294967296;r[o++]=c>>>24&255,r[o++]=c>>>16&255,r[o++]=c>>>8&255,r[o++]=255&c;const a=t/4294967296*1e4&268435455;r[o++]=a>>>8&255,r[o++]=255&a,r[o++]=a>>>24&15|16,r[o++]=a>>>16&255,r[o++]=s>>>8|128,r[o++]=255&s;for(let h=0;h<6;++h)r[o++]=i[h];return r}const l=function(e,t,n){var s,i;let r;const o=null!==(s=null===(i=e)||void 0===i?void 0:i._v6)&&void 0!==s&&s;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e){var l,d,_,f;r=u(null!==(l=null!==(d=e.random)&&void 0!==d?d:null===(_=(f=e).rng)||void 0===_?void 0:_.call(f))&&void 0!==l?l:(0,a.A)(),e.msecs,e.nsecs,e.clockseq,e.node,t,n)}else{const e=Date.now(),s=(0,a.A)();!function(e,t,n){var s,i;null!==(s=e.msecs)&&void 0!==s||(e.msecs=-1/0),null!==(i=e.nsecs)&&void 0!==i||(e.nsecs=0),t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0);e.node||(e.node=n.slice(10,16),e.node[0]|=1,e.clockseq=16383&(n[8]<<8|n[9]));e.msecs=t}(h,e,s),r=u(s,h.msecs,h.nsecs,o?void 0:h.clockseq,o?void 0:h.node,t,n)}return null!==t&&void 0!==t?t:(0,c.k)(r)};function d(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"===typeof e?o(e):e);return"string"===typeof e?(0,c.k)(t):t}function _(e){return 14+(e+64>>>9<<4)+1}function f(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function p(e,t,n,s,i,r){return f((o=f(f(t,e),f(s,r)))<<(c=i)|o>>>32-c,n);var o,c}function g(e,t,n,s,i,r,o){return p(t&n|~t&s,e,t,i,r,o)}function b(e,t,n,s,i,r,o){return p(t&s|n&~s,e,t,i,r,o)}function m(e,t,n,s,i,r,o){return p(t^n^s,e,t,i,r,o)}function v(e,t,n,s,i,r,o){return p(n^(t|~s),e,t,i,r,o)}const y=function(e){return function(e){const t=new Uint8Array(4*e.length);for(let n=0;n<4*e.length;n++)t[n]=e[n>>2]>>>n%4*8&255;return t}(function(e,t){const n=new Uint32Array(_(t)).fill(0);n.set(e),n[t>>5]|=128<<t%32,n[n.length-1]=t,e=n;let s=1732584193,i=-271733879,r=-1732584194,o=271733878;for(let c=0;c<e.length;c+=16){const t=s,n=i,a=r,h=o;s=g(s,i,r,o,e[c],7,-680876936),o=g(o,s,i,r,e[c+1],12,-389564586),r=g(r,o,s,i,e[c+2],17,606105819),i=g(i,r,o,s,e[c+3],22,-1044525330),s=g(s,i,r,o,e[c+4],7,-176418897),o=g(o,s,i,r,e[c+5],12,1200080426),r=g(r,o,s,i,e[c+6],17,-1473231341),i=g(i,r,o,s,e[c+7],22,-45705983),s=g(s,i,r,o,e[c+8],7,1770035416),o=g(o,s,i,r,e[c+9],12,-1958414417),r=g(r,o,s,i,e[c+10],17,-42063),i=g(i,r,o,s,e[c+11],22,-1990404162),s=g(s,i,r,o,e[c+12],7,1804603682),o=g(o,s,i,r,e[c+13],12,-40341101),r=g(r,o,s,i,e[c+14],17,-1502002290),i=g(i,r,o,s,e[c+15],22,1236535329),s=b(s,i,r,o,e[c+1],5,-165796510),o=b(o,s,i,r,e[c+6],9,-1069501632),r=b(r,o,s,i,e[c+11],14,643717713),i=b(i,r,o,s,e[c],20,-373897302),s=b(s,i,r,o,e[c+5],5,-701558691),o=b(o,s,i,r,e[c+10],9,38016083),r=b(r,o,s,i,e[c+15],14,-660478335),i=b(i,r,o,s,e[c+4],20,-405537848),s=b(s,i,r,o,e[c+9],5,568446438),o=b(o,s,i,r,e[c+14],9,-1019803690),r=b(r,o,s,i,e[c+3],14,-187363961),i=b(i,r,o,s,e[c+8],20,1163531501),s=b(s,i,r,o,e[c+13],5,-1444681467),o=b(o,s,i,r,e[c+2],9,-51403784),r=b(r,o,s,i,e[c+7],14,1735328473),i=b(i,r,o,s,e[c+12],20,-1926607734),s=m(s,i,r,o,e[c+5],4,-378558),o=m(o,s,i,r,e[c+8],11,-2022574463),r=m(r,o,s,i,e[c+11],16,1839030562),i=m(i,r,o,s,e[c+14],23,-35309556),s=m(s,i,r,o,e[c+1],4,-1530992060),o=m(o,s,i,r,e[c+4],11,1272893353),r=m(r,o,s,i,e[c+7],16,-155497632),i=m(i,r,o,s,e[c+10],23,-1094730640),s=m(s,i,r,o,e[c+13],4,681279174),o=m(o,s,i,r,e[c],11,-358537222),r=m(r,o,s,i,e[c+3],16,-722521979),i=m(i,r,o,s,e[c+6],23,76029189),s=m(s,i,r,o,e[c+9],4,-640364487),o=m(o,s,i,r,e[c+12],11,-421815835),r=m(r,o,s,i,e[c+15],16,530742520),i=m(i,r,o,s,e[c+2],23,-995338651),s=v(s,i,r,o,e[c],6,-198630844),o=v(o,s,i,r,e[c+7],10,1126891415),r=v(r,o,s,i,e[c+14],15,-1416354905),i=v(i,r,o,s,e[c+5],21,-57434055),s=v(s,i,r,o,e[c+12],6,1700485571),o=v(o,s,i,r,e[c+3],10,-1894986606),r=v(r,o,s,i,e[c+10],15,-1051523),i=v(i,r,o,s,e[c+1],21,-2054922799),s=v(s,i,r,o,e[c+8],6,1873313359),o=v(o,s,i,r,e[c+15],10,-30611744),r=v(r,o,s,i,e[c+6],15,-1560198380),i=v(i,r,o,s,e[c+13],21,1309151649),s=v(s,i,r,o,e[c+4],6,-145523070),o=v(o,s,i,r,e[c+11],10,-1120210379),r=v(r,o,s,i,e[c+2],15,718787259),i=v(i,r,o,s,e[c+9],21,-343485551),s=f(s,t),i=f(i,n),r=f(r,a),o=f(o,h)}return Uint32Array.of(s,i,r,o)}(function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(_(8*e.length)).fill(0);for(let n=0;n<e.length;n++)t[n>>2]|=(255&e[n])<<n%4*8;return t}(e),8*e.length))};const w="6ba7b810-9dad-11d1-80b4-00c04fd430c8",S="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function T(e,t,n,s,i,r){var a;const h="string"===typeof n?function(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}(n):n,u="string"===typeof s?o(s):s;if("string"===typeof s&&(s=o(s)),16!==(null===(a=s)||void 0===a?void 0:a.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+h.length);if(l.set(u),l.set(h,u.length),l=t(l),l[6]=15&l[6]|e,l[8]=63&l[8]|128,i){r=r||0;for(let e=0;e<16;++e)i[r+e]=l[e];return i}return(0,c.k)(l)}function E(e,t,n,s){return T(48,y,e,t,n,s)}E.DNS=w,E.URL=S;const C=E;var k=n(3563);function P(e,t,n,s){switch(e){case 0:return t&n^~t&s;case 1:case 3:return t^n^s;case 2:return t&n^t&s^n&s}}function R(e,t){return e<<t|e>>>32-t}const O=function(e){const t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],s=new Uint8Array(e.length+1);s.set(e),s[e.length]=128;const i=(e=s).length/4+2,r=Math.ceil(i/16),o=new Array(r);for(let c=0;c<r;++c){const t=new Uint32Array(16);for(let n=0;n<16;++n)t[n]=e[64*c+4*n]<<24|e[64*c+4*n+1]<<16|e[64*c+4*n+2]<<8|e[64*c+4*n+3];o[c]=t}o[r-1][14]=8*(e.length-1)/Math.pow(2,32),o[r-1][14]=Math.floor(o[r-1][14]),o[r-1][15]=8*(e.length-1)&4294967295;for(let c=0;c<r;++c){const e=new Uint32Array(80);for(let t=0;t<16;++t)e[t]=o[c][t];for(let t=16;t<80;++t)e[t]=R(e[t-3]^e[t-8]^e[t-14]^e[t-16],1);let s=n[0],i=n[1],r=n[2],a=n[3],h=n[4];for(let n=0;n<80;++n){const o=Math.floor(n/20),c=R(s,5)+P(o,i,r,a)+h+t[o]+e[n]>>>0;h=a,a=r,r=R(i,30)>>>0,i=s,s=c}n[0]=n[0]+s>>>0,n[1]=n[1]+i>>>0,n[2]=n[2]+r>>>0,n[3]=n[3]+a>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])};function I(e,t,n,s){return T(80,O,e,t,n,s)}I.DNS=w,I.URL=S;const N=I;var x=n(9740);const A=function(e,t,n){null!==e&&void 0!==e||(e={}),null!==n&&void 0!==n||(n=0);let s=l((0,x.A)((0,x.A)({},e),{},{_v6:!0}),new Uint8Array(16));if(s=d(s),t){for(let e=0;e<16;e++)t[n+e]=s[e];return t}return(0,c.k)(s)};function D(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"===typeof e?o(e):e);return"string"===typeof e?(0,c.k)(t):t}const L={};function U(e,t,n,s){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;if(e.length<16)throw new Error("Random bytes length must be >= 16");if(s){if(i<0||i+16>s.length)throw new RangeError("UUID byte range ".concat(i,":").concat(i+15," is out of buffer bounds"))}else s=new Uint8Array(16),i=0;return null!==t&&void 0!==t||(t=Date.now()),null!==n&&void 0!==n||(n=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9]),s[i++]=t/1099511627776&255,s[i++]=t/4294967296&255,s[i++]=t/16777216&255,s[i++]=t/65536&255,s[i++]=t/256&255,s[i++]=255&t,s[i++]=112|n>>>28&15,s[i++]=n>>>20&255,s[i++]=128|n>>>14&63,s[i++]=n>>>6&255,s[i++]=n<<2&255|3&e[10],s[i++]=e[11],s[i++]=e[12],s[i++]=e[13],s[i++]=e[14],s[i++]=e[15],s}const j=function(e,t,n){let s;if(e){var i,r,o;s=U(null!==(i=null!==(r=e.random)&&void 0!==r?r:null===(o=e.rng)||void 0===o?void 0:o.call(e))&&void 0!==i?i:(0,a.A)(),e.msecs,e.seq,t,n)}else{const e=Date.now(),i=(0,a.A)();!function(e,t,n){var s,i;null!==(s=e.msecs)&&void 0!==s||(e.msecs=-1/0),null!==(i=e.seq)&&void 0!==i||(e.seq=0),t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++)}(L,e,i),s=U(i,L.msecs,L.seq,t,n)}return null!==t&&void 0!==t?t:(0,c.k)(s)};const M=function(e){if(!(0,r.A)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}},5481:(e,t,n)=>{n.r(t),n.d(t,{E_ALREADY_LOCKED:()=>i,E_CANCELED:()=>r,E_TIMEOUT:()=>s,Mutex:()=>u,Semaphore:()=>c,tryAcquire:()=>f,withTimeout:()=>d});const s=new Error("timeout while waiting for mutex to become available"),i=new Error("mutex already locked"),r=new Error("request for lock canceled");var o=function(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{a(s.next(e))}catch(t){r(t)}}function c(e){try{a(s.throw(e))}catch(t){r(t)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}a((s=s.apply(e,t||[])).next())})};class c{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:r;this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));return new Promise((n,s)=>{const i={resolve:n,reject:s,weight:e,priority:t},r=a(this._queue,e=>t<=e.priority);-1===r&&e<=this._value?this._dispatchItem(i):this._queue.splice(r+1,0,i)})}runExclusive(e){return o(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return function*(){const[i,r]=yield t.acquire(n,s);try{return yield e(i)}finally{r()}}()})}waitForUnlock(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),function(e,t){const n=a(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;if(e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(0===this._queue.length)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const s=n.findIndex(t=>t.priority<=e);(-1===s?n:n.splice(0,s)).forEach(e=>e.resolve())}}}_couldLockImmediately(e,t){return(0===this._queue.length||this._queue[0].priority<t)&&e<=this._value}}function a(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var h=function(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{a(s.next(e))}catch(t){r(t)}}function c(e){try{a(s.throw(e))}catch(t){r(t)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}a((s=s.apply(e,t||[])).next())})};class u{constructor(e){this._semaphore=new c(1,e)}acquire(){return h(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){const[,n]=yield e._semaphore.acquire(1,t);return n}()})}runExclusive(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}var l=function(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{a(s.next(e))}catch(t){r(t)}}function c(e){try{a(s.throw(e))}catch(t){r(t)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}a((s=s.apply(e,t||[])).next())})};function d(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s;return{acquire:(s,i)=>{let r;if(_(e)?r=s:(r=void 0,i=s),void 0!==r&&r<=0)throw new Error("invalid weight ".concat(r,": must be positive"));return new Promise((s,o)=>l(this,void 0,void 0,function*(){let c=!1;const a=setTimeout(()=>{c=!0,o(n)},t);try{const t=yield _(e)?e.acquire(r,i):e.acquire(i);if(c){(Array.isArray(t)?t[1]:t)()}else clearTimeout(a),s(t)}catch(h){c||(clearTimeout(a),o(h))}}))},runExclusive(e,t,n){return l(this,void 0,void 0,function*(){let s=()=>{};try{const i=yield this.acquire(t,n);return Array.isArray(i)?(s=i[1],yield e(i[0])):(s=i,yield e())}finally{s()}})},release(t){e.release(t)},cancel:()=>e.cancel(),waitForUnlock:(s,i)=>{let r;if(_(e)?r=s:(r=void 0,i=s),void 0!==r&&r<=0)throw new Error("invalid weight ".concat(r,": must be positive"));return new Promise((s,o)=>{const c=setTimeout(()=>o(n),t);(_(e)?e.waitForUnlock(r,i):e.waitForUnlock(i)).then(()=>{clearTimeout(c),s()})})},isLocked:()=>e.isLocked(),getValue:()=>e.getValue(),setValue:t=>e.setValue(t)}}function _(e){return void 0!==e.getValue}function f(e){return d(e,0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:i)}},5921:(e,t,n)=>{function s(e){let t,n=e[0],s=1;for(;s<e.length;){const i=e[s],r=e[s+1];if(s+=2,("optionalAccess"===i||"optionalCall"===i)&&null==n)return;"access"===i||"optionalAccess"===i?(t=n,n=r(n)):"call"!==i&&"optionalCall"!==i||(n=r(function(){for(var e=arguments.length,s=new Array(e),i=0;i<e;i++)s[i]=arguments[i];return n.call(t,...s)}),t=void 0)}return n}var i,r,o,c,a;Object.defineProperty(t,"__esModule",{value:!0});var h,u=n(5806),l=(h=u)&&h.__esModule?h:{default:h},d=(e=>(e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.CONNECTED="CONNECTED",e))(d||{}),_=(e=>(e.SESSION_EXPIRED="SESSION_EXPIRED",e.SESSION_NOT_FOUND="SESSION_NOT_FOUND",e.SESSION_INVALID_STATE="SESSION_INVALID_STATE",e.SESSION_SAVE_FAILED="SESSION_SAVE_FAILED",e.TRANSPORT_DISCONNECTED="TRANSPORT_DISCONNECTED",e.TRANSPORT_PUBLISH_FAILED="TRANSPORT_PUBLISH_FAILED",e.TRANSPORT_SUBSCRIBE_FAILED="TRANSPORT_SUBSCRIBE_FAILED",e.TRANSPORT_HISTORY_FAILED="TRANSPORT_HISTORY_FAILED",e.TRANSPORT_PARSE_FAILED="TRANSPORT_PARSE_FAILED",e.TRANSPORT_RECONNECT_FAILED="TRANSPORT_RECONNECT_FAILED",e.DECRYPTION_FAILED="DECRYPTION_FAILED",e.INVALID_KEY="INVALID_KEY",e.REQUEST_EXPIRED="REQUEST_EXPIRED",e.OTP_INCORRECT="OTP_INCORRECT",e.OTP_MAX_ATTEMPTS_REACHED="OTP_MAX_ATTEMPTS_REACHED",e.OTP_ENTRY_TIMEOUT="OTP_ENTRY_TIMEOUT",e.UNKNOWN="UNKNOWN",e))(_||{}),f=class extends Error{constructor(e,t){super(t||e),this.code=e,this.name=e}},p=class extends f{},g=class extends f{},b=class extends f{},m=i=class extends l.default{__init(){this.session=null}__init2(){this._state="DISCONNECTED"}on(e,t){return super.on(e,t)}constructor(e,t,n){super(),i.prototype.__init.call(this),i.prototype.__init2.call(this),this.transport=e,this.keymanager=t,this.sessionstore=n,this.transport.on("error",e=>this.emit("error",e)),this.transport.on("message",async e=>{if(!s([this,"access",e=>e.session,"optionalAccess",e=>e.keyPair,"access",e=>e.privateKey]))return;if(await this.checkSessionExpiry())return void this.emit("error",new p("SESSION_EXPIRED","Session expired"));const t=await this.decryptMessage(e.data);t&&this.handleMessage(t)})}get state(){return this._state}set state(e){this._state=e}async reconnect(){if("CONNECTING"!==this.state&&this.session&&this.transport.reconnect)try{this.state="CONNECTING",await this.transport.reconnect(),this.state="CONNECTED",this.emit("connected")}catch(e){throw this.state="DISCONNECTED",new g("TRANSPORT_RECONNECT_FAILED","Failed to reconnect")}}async resume(e){if("DISCONNECTED"!==this.state)throw new p("SESSION_INVALID_STATE","Cannot resume when state is ".concat(this.state));this.state="CONNECTING";try{const t=await this.sessionstore.get(e);if(!t)throw new p("SESSION_NOT_FOUND","Session not found or expired");this.keymanager.validatePeerKey(t.theirPublicKey),this.session=t,await this.transport.connect(),await this.transport.subscribe(t.channel),this.state="CONNECTED",this.emit("connected")}catch(t){throw this.state="DISCONNECTED",this.session=null,t}}async disconnect(){if(!this.session)return;const e=this.session;this.session=null,this.state="DISCONNECTED",await this.transport.disconnect(),await this.transport.clear(e.channel),await this.sessionstore.delete(e.id),this.emit("disconnected")}async sendMessage(e,t){if(!this.session)throw new p("SESSION_INVALID_STATE","Cannot send message: session is not initialized.");if(await this.checkSessionExpiry())throw new p("SESSION_EXPIRED","Session expired");const n=JSON.stringify(t),s=await this.keymanager.encrypt(n,this.session.theirPublicKey);if(!await this.transport.publish(e,s))throw new g("TRANSPORT_DISCONNECTED","Message could not be sent because the transport is disconnected.")}async checkSessionExpiry(){return!(!this.session||this.session.expiresAt>=Date.now())&&(await this.disconnect(),!0)}async decryptMessage(e){if(!s([this,"access",e=>e.session,"optionalAccess",e=>e.keyPair,"access",e=>e.privateKey]))return null;try{const t=await this.keymanager.decrypt(e,this.session.keyPair.privateKey);return JSON.parse(t)}catch(t){const e=t instanceof Error?t.message:String(t);return this.emit("error",new b("DECRYPTION_FAILED","Decryption failed: ".concat(e))),null}}},v=["trusted","untrusted"];var y=n(5481),w=((r=class e{static __initStatic(){this.SESSION_PREFIX="session:"}static __initStatic2(){this.MASTER_LIST_KEY="sessions:master-list"}__init3(){this.mutex=new(0,y.Mutex)}static async create(t){const n=new e(t);return await n.garbageCollect(),n}constructor(e){r.prototype.__init3.call(this),this.kvstore=e}async set(e){if(Number.isNaN(e.expiresAt)||e.expiresAt<Date.now())throw new p("SESSION_SAVE_FAILED","Cannot save expired session");const t={id:e.id,channel:e.channel,keyPair:{publicKeyB64:Buffer.from(e.keyPair.publicKey).toString("base64"),privateKeyB64:Buffer.from(e.keyPair.privateKey).toString("base64")},theirPublicKeyB64:Buffer.from(e.theirPublicKey).toString("base64"),expiresAt:e.expiresAt},n=this.getSessionKey(e.id);await this.kvstore.set(n,JSON.stringify(t)),await this.addToMasterList(e.id)}async get(e){const t=this.getSessionKey(e),n=await this.kvstore.get(t);if(!n)return null;try{const t=JSON.parse(n);if("number"!==typeof t.expiresAt||!(t.expiresAt>=Date.now()))return await this.delete(e),null;return{id:t.id,channel:t.channel,keyPair:{publicKey:new Uint8Array(Buffer.from(t.keyPair.publicKeyB64,"base64")),privateKey:new Uint8Array(Buffer.from(t.keyPair.privateKeyB64,"base64"))},theirPublicKey:new Uint8Array(Buffer.from(t.theirPublicKeyB64,"base64")),expiresAt:t.expiresAt}}catch(s){return await this.delete(e),null}}async list(){const e=await this.getMasterList(),t=[];for(const n of e){const e=await this.get(n);e&&t.push(e)}return t}async delete(e){const t=this.getSessionKey(e);await this.kvstore.delete(t),await this.removeFromMasterList(e)}async garbageCollect(){const e=await this.getMasterList();await Promise.all(e.map(async e=>this.get(e)))}getSessionKey(t){return"".concat(e.SESSION_PREFIX).concat(t)}async getMasterList(){const t=await this.kvstore.get(e.MASTER_LIST_KEY);if(!t)return[];try{return JSON.parse(t)}catch(n){return[]}}async addToMasterList(t){await this.mutex.runExclusive(async()=>{const n=await this.getMasterList();n.includes(t)||(n.push(t),await this.kvstore.set(e.MASTER_LIST_KEY,JSON.stringify(n)))})}async removeFromMasterList(t){await this.mutex.runExclusive(async()=>{const n=(await this.getMasterList()).filter(e=>e!==t);await this.kvstore.set(e.MASTER_LIST_KEY,JSON.stringify(n))})}}).__initStatic(),r.__initStatic2(),r),S=n(8632),T=e=>new Promise(t=>setTimeout(t,e));var E=o=class{constructor(e,t){o.prototype.__init4.call(this),this.realSub=e,this.parent=t}__init4(){this.hasUnsubscribed=!1}get channel(){return this.realSub.channel}get state(){return this.realSub.state}subscribe(){this.realSub.subscribe()}unsubscribe(){this.hasUnsubscribed||(this.hasUnsubscribed=!0,this.parent.removeSubscription({channel:this.channel}))}async publish(e){return await this.realSub.publish(e)}history(e){return this.realSub.history(e)}on(e,t){return this.realSub.on(e,t),this}once(e,t){return this.realSub.once(e,t),this}off(e,t){return this.realSub.off(e,t),this}},C=((c=class e extends l.default{static __initStatic3(){this.contexts=new Map}__init5(){this.channels=new Set}__init6(){this.disconnected=!1}__init7(){this.eventListeners=new Map}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(super(),c.prototype.__init5.call(this),c.prototype.__init6.call(this),c.prototype.__init7.call(this),this.url=t,e.contexts.has(t)){const s=e.contexts.get(t);if(!s)throw new Error("No context found");this.validateOptions(s.options,n)}else{const s=new(0,S.Centrifuge)(t,n);e.contexts.set(t,{refcount:0,options:n,centrifuge:s,subscriptions:new Map,reconnectPromise:null})}const s=e.contexts.get(t);if(!s)throw new Error("No context found");s.refcount++,this.attachEventListeners()}connect(){const t=e.contexts.get(this.url);t&&("connected"===t.centrifuge.state?setImmediate(()=>this.emit("connected",{})):"connecting"===t.centrifuge.state||t.centrifuge.connect())}disconnect(){if(this.disconnected)return Promise.resolve();const t=e.contexts.get(this.url);if(!t)return Promise.resolve();this.disconnected=!0,this.emit("disconnected",{}),this.detachEventListeners();for(const e of this.channels)this.decrementChannelRef(e);return this.channels.clear(),t.refcount--,0===t.refcount?new Promise(n=>{t.centrifuge.once("disconnected",()=>{e.contexts.delete(this.url),n()}),t.centrifuge.disconnect()}):Promise.resolve()}reconnect(){const t=e.contexts.get(this.url);return t?(t.reconnectPromise||(t.reconnectPromise=(async()=>{try{"disconnected"!==t.centrifuge.state&&await new Promise(e=>{t.centrifuge.once("disconnected",()=>e()),t.centrifuge.disconnect()}),await new Promise((e,n)=>{t.centrifuge.once("connected",()=>e()),t.centrifuge.once("error",e=>n(e.error)),t.centrifuge.connect()})}finally{t.reconnectPromise=null}})()),t.reconnectPromise):Promise.resolve()}newSubscription(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=e.contexts.get(this.url);if(!s)throw new Error("No context found");const i=s.subscriptions;if(!this.channels.has(t))if(i.has(t)){const e=i.get(t);if(!e)throw new Error("Failed to get subscription info for channel ".concat(t));e.count++}else{const e=s.centrifuge.newSubscription(t,n);i.set(t,{count:1,sub:e})}this.channels.add(t);const r=i.get(t);if(!r)throw new Error("Failed to create or get subscription for channel ".concat(t));return new E(r.sub,this)}getSubscription(t){if(!this.channels.has(t))return;const n=e.contexts.get(this.url);if(!n)return;const s=n.subscriptions.get(t);return s?new E(s.sub,this):void 0}async publish(t,n){const s=e.contexts.get(this.url);s&&await s.centrifuge.publish(t,n)}subscriptions(){const t=e.contexts.get(this.url);if(!t)return{};const n={};for(const e of this.channels){const s=t.subscriptions.get(e);s&&(n[e]=new E(s.sub,this))}return n}get real(){return s([e.contexts.get(this.url),"optionalAccess",e=>e.centrifuge])}get state(){if(this.disconnected)return"disconnected";const t=e.contexts.get(this.url);return n=s([t,"optionalAccess",e=>e.centrifuge,"access",e=>e.state]),i=()=>"disconnected",null!=n?n:i();var n,i}attachEventListeners(){if(this.eventListeners.size>0)return;const t=e.contexts.get(this.url);if(!t)return;["connecting","connected","disconnected","error"].forEach(e=>{const n=t=>{this.disconnected||this.emit(e,t)};this.eventListeners.set(e,n),t.centrifuge.on(e,n)})}decrementChannelRef(t){const n=e.contexts.get(this.url);if(!n)return;const s=n.subscriptions,i=s.get(t);i&&(i.count--,0===i.count&&(i.sub.unsubscribe(),n.centrifuge.removeSubscription(i.sub),s.delete(t)))}detachEventListeners(){const t=e.contexts.get(this.url);if(t){for(const[e,n]of this.eventListeners)t.centrifuge.off(e,n);this.eventListeners.clear()}}validateOptions(e,t){const n=["token","websocket","minReconnectDelay","maxReconnectDelay"];for(const s of n){const n=e[s],i=t[s];void 0!==n&&void 0!==i&&n!==i&&console.warn("SharedCentrifuge: Option '".concat(s,"' mismatch for URL ").concat(this.url,". Using existing value: ").concat(n,", ignoring new value: ").concat(i))}}removeSubscription(e){e&&"channel"in e&&(this.decrementChannelRef(e.channel),this.channels.delete(e.channel))}}).__initStatic3(),c),k=n(2027),P=class e{static async create(t){const n=e.getClientIdKey();let s=await t.get(n);return s||(s=k.v4.call(void 0),await t.set(n,s)),new e(t,s)}constructor(e,t){this.kvstore=e,this.clientId=t}getClientId(){return this.clientId}async getNextNonce(e){const t=this.getNonceKey(e),n=await this.kvstore.get(t),s=(n?parseInt(n,10):0)+1;return await this.kvstore.set(t,s.toString()),s}async getLatestNonces(e){const t=this.getLatestNoncesKey(e),n=await this.kvstore.get(t);if(n){const e=JSON.parse(n);return new Map(Object.entries(e))}return new Map}async setLatestNonces(e,t){const n=this.getLatestNoncesKey(e),s=Object.fromEntries(t);await this.kvstore.set(n,JSON.stringify(s))}async clear(e){const t=this.getNonceKey(e),n=this.getLatestNoncesKey(e);await Promise.all([this.kvstore.delete(t),this.kvstore.delete(n)])}static getClientIdKey(){return"websocket-transport-client-id"}getNonceKey(e){return"nonce:".concat(this.clientId,":").concat(e)}getLatestNoncesKey(e){return"latest-nonces:".concat(this.clientId,":").concat(e)}},R=a=class e extends l.default{__init8(){this.queue=[]}__init9(){this.isProcessingQueue=!1}__init10(){this.state="disconnected"}static async create(t){const n=await P.create(t.kvstore);return new e(n,t)}constructor(e,t){super(),a.prototype.__init8.call(this),a.prototype.__init9.call(this),a.prototype.__init10.call(this),this.storage=e;const n={minReconnectDelay:100,maxReconnectDelay:3e4};void 0!==t.websocket&&(n.websocket=t.websocket),this.centrifuge=t.useSharedConnection?new C(t.url,n):new(0,S.Centrifuge)(t.url,n),this.centrifuge.on("connecting",()=>this.setState("connecting")),this.centrifuge.on("connected",()=>{this.setState("connected"),this._processQueue()}),this.centrifuge.on("disconnected",()=>this.setState("disconnected")),this.centrifuge.on("error",e=>this.emit("error",new g("UNKNOWN",e.error.message)))}connect(){return"connected"===this.state||"connecting"===this.state?Promise.resolve():(this.setState("connecting"),new Promise(e=>{this.centrifuge.once("connected",()=>e()),this.centrifuge.connect()}))}disconnect(){return this.queue.forEach(e=>e.resolve(!1)),this.queue.length=0,"disconnected"===this.state?Promise.resolve():new Promise(e=>{const t=this.centrifuge.subscriptions();for(const n of Object.values(t))this.centrifuge.removeSubscription(n);this.centrifuge.once("disconnected",()=>e()),this.centrifuge.disconnect()})}reconnect(){return this.centrifuge instanceof C&&"reconnect"in this.centrifuge?this.centrifuge.reconnect():"connecting"===this.state?new Promise(e=>this.centrifuge.once("connected",()=>e())):(this.centrifuge.disconnect(),new Promise((e,t)=>{this.centrifuge.once("connected",()=>e()),this.centrifuge.once("error",e=>t(new g("TRANSPORT_RECONNECT_FAILED",e.error.message))),this.centrifuge.connect()}))}subscribe(e){let t=this.centrifuge.getSubscription(e);if(!t){t=this.centrifuge.newSubscription(e,{recoverable:!0,positioned:!0});const n=t;t.on("subscribed",()=>{this._fetchHistory(n,e),this._processQueue()}),t.on("publication",t=>{this._handleIncomingMessage(e,t.data)}),t.on("error",e=>this.emit("error",new g("TRANSPORT_SUBSCRIBE_FAILED","Subscription error: ".concat(e.error.message))))}if("subscribed"===t.state)return Promise.resolve();const n=t;return new Promise(e=>{n.once("subscribed",()=>e()),n.subscribe()})}publish(e,t){const n=new Promise((n,s)=>{this.queue.push({channel:e,payload:t,resolve:n,reject:s})});return this._processQueue(),n}async clear(e){await this.storage.clear(e);const t=this.centrifuge.getSubscription(e);t&&this.centrifuge.removeSubscription(t)}setState(e){this.state!==e&&(this.state=e,this.emit(e))}async _handleIncomingMessage(e,t){try{const n=JSON.parse(t);if("string"!==typeof n.clientId||"number"!==typeof n.nonce||"string"!==typeof n.payload)throw new g("TRANSPORT_PARSE_FAILED","Invalid message format");if(n.clientId===this.storage.getClientId())return;const s=await this.storage.getLatestNonces(e),i=s.get(n.clientId)||0;n.nonce>i&&(s.set(n.clientId,n.nonce),await this.storage.setLatestNonces(e,s),this.emit("message",{channel:e,data:n.payload}))}catch(n){this.emit("error",new g("TRANSPORT_PARSE_FAILED","Failed to parse incoming message: ".concat(n instanceof Error?n.message:"Unknown error")))}}async _fetchHistory(e,t){try{const n=await e.history({limit:50});for(const e of n.publications)await this._handleIncomingMessage(t,e.data)}catch(n){if(11===s([n,"optionalAccess",e=>e.code]))return;this.emit("error",new g("TRANSPORT_HISTORY_FAILED","Failed to fetch history for channel ".concat(t,": ").concat(JSON.stringify(n))))}}async _process(e){const t={clientId:this.storage.getClientId(),nonce:await this.storage.getNextNonce(e.channel),payload:e.payload},n=JSON.stringify(t);return async function(e,t){for(let s=0;s<t.attempts;s++)try{return await e()}catch(n){if(s===t.attempts-1)throw n;const e=t.delay*2**s;await T(e)}throw new f("UNKNOWN","Retry logic failed unexpectedly.")}(async()=>{await this.centrifuge.publish(e.channel,n)},{attempts:5,delay:100})}async _processQueue(){if(!this.isProcessingQueue&&"connected"===this.state){this.isProcessingQueue=!0;try{for(;this.queue.length>0;){const t=this.queue[0];try{await this._process(t),this.queue.shift(),t.resolve(!0)}catch(e){this.queue.shift(),t.reject(e instanceof Error?e:new g("TRANSPORT_PUBLISH_FAILED","Failed to publish message after all retries"))}}}finally{this.isProcessingQueue=!1}}}};t.BaseClient=m,t.CONNECTION_MODES=v,t.ClientState=d,t.CryptoError=b,t.DEFAULT_SESSION_TTL=2592e6,t.ErrorCode=_,t.ProtocolError=f,t.SessionError=p,t.SessionStore=w,t.TransportError=g,t.WebSocketTransport=R,t.isValidConnectionMode=function(e){return"string"===typeof e&&v.includes(e)},t.timingSafeEqual=function(e,t){if(e.length!==t.length)return!1;let n=0;for(let s=0;s<e.length;s++)n|=e.charCodeAt(s)^t.charCodeAt(s);return 0===n}},8632:(e,t,n)=>{function s(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{a(s.next(e))}catch(t){r(t)}}function c(e){try{a(s.throw(e))}catch(t){r(t)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}a((s=s.apply(e,t||[])).next())})}function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}n.r(t),n.d(t,{Centrifuge:()=>V,State:()=>P,Subscription:()=>A,SubscriptionState:()=>R,UnauthorizedError:()=>J,connectingCodes:()=>S,disconnectedCodes:()=>T,errorCodes:()=>w,subscribingCodes:()=>E,subscriptionFlags:()=>k,unsubscribedCodes:()=>C}),"function"===typeof SuppressedError&&SuppressedError;var r,o={exports:{}},c="object"===typeof Reflect?Reflect:null,a=c&&"function"===typeof c.apply?c.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=c&&"function"===typeof c.ownKeys?c.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var h=Number.isNaN||function(e){return e!==e};function u(){u.init.call(this)}o.exports=u,o.exports.once=function(e,t){return new Promise(function(n,s){function i(n){e.removeListener(t,r),s(n)}function r(){"function"===typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}y(e,t,r,{once:!0}),"error"!==t&&function(e,t,n){"function"===typeof e.on&&y(e,"error",t,n)}(e,i,{once:!0})})},u.EventEmitter=u,u.prototype._events=void 0,u.prototype._eventsCount=0,u.prototype._maxListeners=void 0;var l=10;function d(e){if("function"!==typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function _(e){return void 0===e._maxListeners?u.defaultMaxListeners:e._maxListeners}function f(e,t,n,s){var i,r,o,c;if(d(n),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),r=e._events),o=r[t]),void 0===o)o=r[t]=n,++e._eventsCount;else if("function"===typeof o?o=r[t]=s?[n,o]:[o,n]:s?o.unshift(n):o.push(n),(i=_(e))>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,c=a,console&&console.warn&&console.warn(c)}return e}function p(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function g(e,t,n){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=p.bind(s);return i.listener=n,s.wrapFn=i,i}function b(e,t,n){var s=e._events;if(void 0===s)return[];var i=s[t];return void 0===i?[]:"function"===typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):v(i,i.length)}function m(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"===typeof n)return 1;if(void 0!==n)return n.length}return 0}function v(e,t){for(var n=new Array(t),s=0;s<t;++s)n[s]=e[s];return n}function y(e,t,n,s){if("function"===typeof e.on)s.once?e.once(t,n):e.on(t,n);else{if("function"!==typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(r){s.once&&e.removeEventListener(t,i),n(r)})}}Object.defineProperty(u,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(e){if("number"!==typeof e||e<0||h(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");l=e}}),u.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},u.prototype.setMaxListeners=function(e){if("number"!==typeof e||e<0||h(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},u.prototype.getMaxListeners=function(){return _(this)},u.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,i=this._events;if(void 0!==i)s=s&&void 0===i.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var o=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw o.context=r,o}var c=i[e];if(void 0===c)return!1;if("function"===typeof c)a(c,this,t);else{var h=c.length,u=v(c,h);for(n=0;n<h;++n)a(u[n],this,t)}return!0},u.prototype.addListener=function(e,t){return f(this,e,t,!1)},u.prototype.on=u.prototype.addListener,u.prototype.prependListener=function(e,t){return f(this,e,t,!0)},u.prototype.once=function(e,t){return d(t),this.on(e,g(this,e,t)),this},u.prototype.prependOnceListener=function(e,t){return d(t),this.prependListener(e,g(this,e,t)),this},u.prototype.removeListener=function(e,t){var n,s,i,r,o;if(d(t),void 0===(s=this._events))return this;if(void 0===(n=s[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!==typeof n){for(i=-1,r=n.length-1;r>=0;r--)if(n[r]===t||n[r].listener===t){o=n[r].listener,i=r;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(s[e]=n[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},u.prototype.off=u.prototype.removeListener,u.prototype.removeAllListeners=function(e){var t,n,s;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,r=Object.keys(n);for(s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"===typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},u.prototype.listeners=function(e){return b(this,e,!0)},u.prototype.rawListeners=function(e){return b(this,e,!1)},u.listenerCount=function(e,t){return"function"===typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},u.prototype.listenerCount=m,u.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]};var w,S,T,E,C,k,P,R,O=i(o.exports);function I(e){return void 0!==e&&null!==e&&"function"===typeof e}function N(e,t,n){e>31&&(e=31);const s=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)}(0,Math.min(n,t*Math.pow(2,e)));return Math.min(n,t+s)}function x(e){return Math.min(1e3*e,2147483647)}!function(e){e[e.timeout=1]="timeout",e[e.transportClosed=2]="transportClosed",e[e.clientDisconnected=3]="clientDisconnected",e[e.clientClosed=4]="clientClosed",e[e.clientConnectToken=5]="clientConnectToken",e[e.clientRefreshToken=6]="clientRefreshToken",e[e.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",e[e.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",e[e.subscriptionRefreshToken=9]="subscriptionRefreshToken",e[e.transportWriteError=10]="transportWriteError",e[e.connectionClosed=11]="connectionClosed",e[e.badConfiguration=12]="badConfiguration"}(w||(w={})),function(e){e[e.connectCalled=0]="connectCalled",e[e.transportClosed=1]="transportClosed",e[e.noPing=2]="noPing",e[e.subscribeTimeout=3]="subscribeTimeout",e[e.unsubscribeError=4]="unsubscribeError"}(S||(S={})),function(e){e[e.disconnectCalled=0]="disconnectCalled",e[e.unauthorized=1]="unauthorized",e[e.badProtocol=2]="badProtocol",e[e.messageSizeLimit=3]="messageSizeLimit"}(T||(T={})),function(e){e[e.subscribeCalled=0]="subscribeCalled",e[e.transportClosed=1]="transportClosed"}(E||(E={})),function(e){e[e.unsubscribeCalled=0]="unsubscribeCalled",e[e.unauthorized=1]="unauthorized",e[e.clientClosed=2]="clientClosed"}(C||(C={})),function(e){e[e.channelCompaction=1]="channelCompaction"}(k||(k={})),function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected"}(P||(P={})),function(e){e.Unsubscribed="unsubscribed",e.Subscribing="subscribing",e.Subscribed="subscribed"}(R||(R={}));class A extends O{constructor(e,t,n){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=R.Unsubscribed,this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValue=null,this._unsubPromise=Promise.resolve(),this._setOptions(n),this._centrifuge._debugEnabled?(this.on("state",e=>{this._debug("subscription state",t,e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("subscription error",t,e)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state===R.Unsubscribed?Promise.reject({code:w.subscriptionUnsubscribed,message:this.state}):this.state===R.Subscribed?Promise.resolve():new Promise((t,n)=>{const s={resolve:t,reject:n};e&&(s.timeout=setTimeout(function(){n({code:w.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(E.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(C.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return s(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return s(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return s(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return s(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e}setData(e){this._data=e}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:w.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const n=this._centrifuge._config.timeout,s=setTimeout(()=>{t({code:w.timeout,message:"timeout"})},n);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===R.Unsubscribed}_isSubscribing(){return this.state===R.Subscribing}_isSubscribed(){return this.state===R.Subscribed}_setState(e){if(this.state!==e){const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(!this._isSubscribing())return;this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,this._setState(R.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const n=e.publications;if(n&&n.length>0)for(const s in n)n.hasOwnProperty(s)&&this._handlePublication(n[s]);!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),x(e.ttl)))}_setSubscribing(e,t){return s(this,void 0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(R.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(e=>this._handleTokenResponse(e)).catch(e=>this._handleTokenError(e)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_getDataAndSubscribe(e){this._getData?this._getData({channel:this.channel}).then(t=>{this._isSubscribing()?(this._data=t,this._sendSubscribe(e)):this._inflight=!1}).catch(e=>this._handleGetDataError(e)):this._inflight=!1}_handleGetDataError(e){if(this._isSubscribing()){if(e instanceof J)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:w.badConfiguration,message:(null===e||void 0===e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(e){if(this._isSubscribing()){if(!e)return this._inflight=!1,void this._failUnauthorized();this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}else this._inflight=!1}_handleTokenError(e){if(this._isSubscribing()){if(e instanceof J)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:w.subscriptionSubscribeToken,message:(null===e||void 0===e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(e=>{this._inflight=!1;const t=e.reply.subscribe;this._handleSubscribeResponse(t),e.next&&e.next()},e=>{this._inflight=!1,this._handleSubscribeError(e.error),e.next&&e.next()}),t}_buildSubscribeCommand(e){const t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=k.channelCompaction,this._needRecover()){t.recover=!0;const e=this._getOffset();e&&(t.offset=e);const n=this._getEpoch();n&&(t.epoch=n)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(){this._centrifuge._debug(...arguments)}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==w.timeout?this._subscribeError(e):this._centrifuge._disconnect(S.subscribeTimeout,"subscribe timeout",!0))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,n){if(this._isUnsubscribed())return Promise.resolve();let s=Promise.resolve();return this._isSubscribed()?(n&&(s=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&n&&(s=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._setState(R.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:w.subscriptionUnsubscribed,message:this.state}),s}_handlePublication(e){if(this._delta&&this._delta_negotiated){const{newData:t,newPrevValue:n}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValue);e.data=t,this._prevValue=n}const t=this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),e.offset&&(this._offset=e.offset)}_handleJoin(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||109===e.code||!0===e.temporary){109===e.code&&(this._token="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===P.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=N(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=e.since.offset||0,this._epoch=e.since.epoch||"",this._recover=!0),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),!0===e.positioned&&(this._positioned=!0),!0===e.recoverable&&(this._recoverable=!0),!0===e.joinLeave&&(this._joinLeave=!0),e.delta){if("fossil"!==e.delta)throw new Error("unsupported delta format");this._delta=e.delta}if(e.tagsFilter&&(this._tagsFilter=e.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together")}}_getOffset(){const e=this._offset;return null!==e?e:0}_getEpoch(){const e=this._epoch;return null!==e?e:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const e={channel:this.channel},t=this._getToken;return null===t?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:w.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new J(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t)return void e._failUnauthorized();e._token=t;const n={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(n).then(t=>{const n=t.reply.sub_refresh;e._refreshResponse(n),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){t instanceof J?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:w.subscriptionRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay()))})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),x(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return N(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(C.unauthorized,"unauthorized",!0)}}class D{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class L{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(e,t){let n="";"protobuf"===e&&(n="centrifuge-protobuf"),this._transport=""!==n?new this.options.websocket(this.endpoint,n):new this.options.websocket(this.endpoint),"protobuf"===e&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class U{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,n){const s=new EventTarget;return(0,e.options.fetch)(t,n).then(e._handleErrors).then(t=>{s.dispatchEvent(new Event("open"));let n="",i=0,r=new Uint8Array;const o=t.body.getReader();return new e.options.readableStream({start:t=>function c(){return o.read().then(o=>{let{done:a,value:h}=o;if(a)return s.dispatchEvent(new Event("close")),void t.close();try{if("json"===e._protocol)for(n+=e._utf8decoder.decode(h);i<n.length;)if("\n"===n[i]){const e=n.substring(0,i);s.dispatchEvent(new MessageEvent("message",{data:e})),n=n.substring(i+1),i=0}else++i;else{const t=new Uint8Array(r.length+h.length);for(t.set(r),t.set(h,r.length),r=t;;){const t=e.options.decoder.decodeReply(r);if(t.ok){const e=r.slice(0,t.pos);s.dispatchEvent(new MessageEvent("message",{data:e})),r=r.slice(t.pos);continue}break}}}catch(u){return s.dispatchEvent(new Event("error",{detail:u})),s.dispatchEvent(new Event("close")),void t.close()}c()}).catch(function(e){s.dispatchEvent(new Event("error",{detail:e})),s.dispatchEvent(new Event("close")),t.close()})}()})}).catch(e=>{s.dispatchEvent(new Event("error",{detail:e})),s.dispatchEvent(new Event("close"))}),s}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!==typeof TextDecoder&&"undefined"!==typeof AbortController&&"undefined"!==typeof EventTarget&&"undefined"!==typeof Event&&"undefined"!==typeof MessageEvent&&"undefined"!==typeof Error}initialize(e,t,n){let s,i;this._protocol=e,this._abortController=new AbortController,"json"===e?(s={Accept:"application/json","Content-Type":"application/json"},i=n):(s={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},i=n);const r={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},o=this._fetchEventTarget(this,this.endpoint,r);o.addEventListener("open",()=>{t.onOpen()}),o.addEventListener("error",e=>{this._abortController.abort(),t.onError(e)}),o.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),o.addEventListener("message",e=>{t.onMessage(e.data)})}close(){this._abortController.abort()}send(e,t,n){let s,i;const r={session:t,node:n,data:e};"json"===this._protocol?(s={"Content-Type":"application/json"},i=JSON.stringify(r)):(s={"Content-Type":"application/octet-stream"},i=this.options.encoder.encodeEmulationRequest(r));const o={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,o)}}class j{constructor(e,t){this.endpoint=e,this.options=t,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,n){let s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),s.searchParams.append("cf_connect",n);const i=new this.options.eventsource(s.toString(),{});this._transport=i;i.onopen=function(){t.onOpen()},i.onerror=function(e){i.close(),t.onError(e),t.onClose({code:4,reason:"connection closed"})},i.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,n){const s={session:t,node:n,data:e},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,i)}}class M{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(e,t){return s(this,void 0,void 0,function*(){let n;n=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===e&&n.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const s=new EventTarget;this._transport=new this.options.webtransport(n.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(r){return void this.close()}let i;try{i=yield this._transport.createBidirectionalStream()}catch(o){return void this.close()}this._stream=i,this._writer=this._stream.writable.getWriter(),s.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),s.addEventListener("message",e=>{t.onMessage(e.data)}),this._startReading(s),t.onOpen()})}_startReading(e){return s(this,void 0,void 0,function*(){const t=this._stream.readable.getReader();let n="",s=0,i=new Uint8Array;try{for(;;){const{done:r,value:o}=yield t.read();if(o.length>0)if("json"===this._protocol)for(n+=this._utf8decoder.decode(o);s<n.length;)if("\n"===n[s]){const t=n.substring(0,s);e.dispatchEvent(new MessageEvent("message",{data:t})),n=n.substring(s+1),s=0}else++s;else{const t=new Uint8Array(i.length+o.length);for(t.set(i),t.set(o,i.length),i=t;;){const t=this.options.decoder.decodeReply(i);if(t.ok){const n=i.slice(0,t.pos);e.dispatchEvent(new MessageEvent("message",{data:n})),i=i.slice(t.pos);continue}break}}if(r)break}}catch(r){e.dispatchEvent(new Event("close"))}})}close(){return s(this,void 0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return s(this,void 0,void 0,function*(){let t;t="json"===this._protocol?(new TextEncoder).encode(e+"\n"):e;try{yield this._writer.write(t)}catch(n){this.close()}})}}const F=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class q{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e,t=0;for(;this.haveBytes()&&(e=F[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class z{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,n){for(let s=t;s<n;s++)this.a.push(e[s])}}function K(e){let t=0,n=0,s=0,i=0,r=0,o=e.length;for(;o>=16;)t=t+e[r+0]|0,n=n+e[r+1]|0,s=s+e[r+2]|0,i=i+e[r+3]|0,t=t+e[r+4]|0,n=n+e[r+5]|0,s=s+e[r+6]|0,i=i+e[r+7]|0,t=t+e[r+8]|0,n=n+e[r+9]|0,s=s+e[r+10]|0,i=i+e[r+11]|0,t=t+e[r+12]|0,n=n+e[r+13]|0,s=s+e[r+14]|0,i=i+e[r+15]|0,r+=16,o-=16;for(;o>=4;)t=t+e[r+0]|0,n=n+e[r+1]|0,s=s+e[r+2]|0,i=i+e[r+3]|0,r+=4,o-=4;switch(i=((i+(s<<8)|0)+(n<<16)|0)+(t<<24)|0,o){case 3:i=i+(e[r+2]<<8)|0;case 2:i=i+(e[r+1]<<16)|0;case 1:i=i+(e[r+0]<<24)|0}return i>>>0}class W{name(){return"json"}encodeCommands(e){return e.map(e=>JSON.stringify(e)).join("\n")}decodeReplies(e){return e.trim().split("\n").map(e=>JSON.parse(e))}applyDeltaIfNeeded(e,t){let n,s;if(e.delta){const i=function(e,t){let n=0;const s=new q(t),i=e.length,r=t.length,o=s.getInt();if("\n"!==s.getChar())throw new Error("size integer not terminated by '\\n'");const c=new z;for(;s.haveBytes();){const t=s.getInt();let a;switch(s.getChar()){case"@":if(a=s.getInt(),s.haveBytes()&&","!==s.getChar())throw new Error("copy command not terminated by ','");if(n+=t,n>o)throw new Error("copy exceeds output file size");if(a+t>i)throw new Error("copy extends past end of input");c.putArray(e,a,a+t);break;case":":if(n+=t,n>o)throw new Error("insert command gives an output larger than predicted");if(t>r)throw new Error("insert count exceeds size of delta");c.putArray(s.a,s.pos,s.pos+t),s.pos+=t;break;case";":{const s=c.toByteArray(e);if(t!==K(s))throw new Error("bad checksum");if(n!==o)throw new Error("generated size does not match predicted size");return s}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(t,(new TextEncoder).encode(e.data));n=JSON.parse((new TextDecoder).decode(i)),s=i}else n=JSON.parse(e.data),s=(new TextEncoder).encode(e.data);return{newData:n,newPrevValue:s}}}const B={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class J extends Error{constructor(e){super(e),this.name=this.constructor.name}}class V extends O{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=P.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new W,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},B),t),this._configure(),this._debugEnabled?(this.on("state",e=>{this._debug("client state",e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("client error",e)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const n=new A(this,e,t);return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==R.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return s(this,void 0,void 0,function*(){switch(this.state){case P.Disconnected:throw{code:w.clientDisconnected,message:"client disconnected"};case P.Connected:return;default:return new Promise((t,n)=>{const s={resolve:t,reject:n};e&&(s.timeout=setTimeout(()=>{n({code:w.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(T.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return s(this,void 0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(w.transportWriteError,"transport write error")})}rpc(e,t){return s(this,void 0,void 0,function*(){const n={rpc:{method:e,data:t}};yield this._methodCall();return{data:(yield this._callPromise(n,e=>e.rpc)).data}})}publish(e,t){return s(this,void 0,void 0,function*(){const n={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,t){return s(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,t)};yield this._methodCall();const s=yield this._callPromise(n,e=>e.history),i=[];if(s.publications)for(let t=0;t<s.publications.length;t++)i.push(this._getPublicationContext(e,s.publications[t]));return{publications:i,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return s(this,void 0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const n=(yield this._callPromise(t,e=>e.presence)).presence;for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){const t=n[e],s=t.conn_info,i=t.chan_info;s&&(t.connInfo=s),i&&(t.chanInfo=i)}return{clients:n}})}presenceStats(e){return s(this,void 0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(t,e=>e.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(){if(this._debugEnabled){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];!function(e,t){if(globalThis.console){const n=globalThis.console[e];I(n)&&n.apply(globalThis.console,t)}}("debug",t)}}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new W,this._formatOverride(),(!0===this._config.debug||"undefined"!==typeof localStorage&&"function"===typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"===typeof this._endpoint);else{if(!("object"===typeof this._endpoint&&this._endpoint instanceof Array))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const n=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===P.Disconnected}_isConnecting(){return this.state===P.Connecting}_isConnected(){return this.state===P.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:"undefined"!==typeof globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==P.Connected&&this.state!==P.Connecting||(this._disconnect(S.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===P.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=N(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const n=t.errback;if(!n)continue;n({error:this._createErrorObject(w.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===R.Subscribed&&t._setSubscribing(E.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const e=t.id;if(!(e in this._callbacks))continue;const n=this._callbacks[e];clearTimeout(this._callbacks[e].timeout),delete this._callbacks[e];(0,n.errback)({error:this._createErrorObject(w.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;null!==this._config.websocket?e=this._config.websocket:"function"!==typeof globalThis.WebSocket&&"object"!==typeof globalThis.WebSocket||(e=globalThis.WebSocket);let t=null;null!==this._config.sockjs?t=this._config.sockjs:"undefined"!==typeof globalThis.SockJS&&(t=globalThis.SockJS);let n=null;null!==this._config.eventsource?n=this._config.eventsource:"undefined"!==typeof globalThis.EventSource&&(n=globalThis.EventSource);let s=null;null!==this._config.fetch?s=this._config.fetch:"undefined"!==typeof globalThis.fetch&&(s=globalThis.fetch);let i=null;if(null!==this._config.readableStream?i=this._config.readableStream:"undefined"!==typeof globalThis.ReadableStream&&(i=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let r=0;for(;;){if(r>=this._transports.length)throw new Error("no supported transport found");const o=this._transports[this._currentTransportIndex],c=o.transport,a=o.endpoint;if("websocket"===c){if(this._debug("trying websocket transport"),this._transport=new L(a,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,r++;continue}}else if("webtransport"===c){if(this._debug("trying webtransport transport"),this._transport=new M(a,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,r++;continue}}else if("http_stream"===c){if(this._debug("trying http_stream transport"),this._transport=new U(a,{fetch:s,readableStream:i,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,r++;continue}}else if("sse"===c){if(this._debug("trying sse transport"),this._transport=new j(a,{eventsource:n,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,r++;continue}}else{if("sockjs"!==c)throw new Error("unknown transport "+c);if(this._debug("trying sockjs"),this._transport=new D(a,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,r++;continue}}break}}else{if(r=this._endpoint,o="http",0===r.lastIndexOf(o,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new L(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var r,o;const c=this,a=this._transport,h=this._nextTransportId();c._debug("id of transport",h);let u=!1;const l=[];if(this._transport.emulation()){const e=c._sendConnect(!0);l.push(e)}this._setNetworkEvents();const d=this._codec.encodeCommands(l);let _;this._transportClosed=!1,_=setTimeout(function(){a.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(_&&(clearTimeout(_),_=null),c._transportId!=h)return c._debug("open callback from non-actual transport"),void a.close();u=!0,c._debug(a.subName(),"transport open"),a.emulation()||(c._transportIsOpen=!0,c._transportWasOpen=!0,c.startBatching(),c._sendConnect(!1),c._sendSubscribeCommands(),c.stopBatching(),c.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(e){c._transportId==h?c._debug("transport level error",e):c._debug("error callback from non-actual transport")},onClose:function(e){if(_&&(clearTimeout(_),_=null),c._transportId!=h)return void c._debug("close callback from non-actual transport");c._debug(a.subName(),"transport closed"),c._transportClosed=!0,c._transportIsOpen=!1;let t="connection closed",n=!0,s=0;if(e&&"code"in e&&e.code&&(s=e.code),e&&e.reason)try{const s=JSON.parse(e.reason);t=s.reason,n=s.reconnect}catch(i){t=e.reason,(s>=3500&&s<4e3||s>=4500&&s<5e3)&&(n=!1)}s<3e3?(1009===s?(s=T.messageSizeLimit,t="message size limit exceeded",n=!1):(s=S.transportClosed,t="transport closed"),c._emulation&&!c._transportWasOpen&&(c._currentTransportIndex++,c._currentTransportIndex>=c._transports.length&&(c._triedAllTransports=!0,c._currentTransportIndex=0))):c._transportWasOpen=!0,c._isConnecting()&&!u&&c.emit("error",{type:"transport",error:{code:w.transportClosed,message:"transport closed"},transport:a.name()}),c._reconnecting=!1,c._disconnect(s,t,n)},onMessage:function(e){c._dataReceived(e)}},d),c.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),n=this;return this._call(t,e).then(e=>{const t=e.reply.connect;n._connectResponse(t),e.next&&e.next()},e=>{n._connectError(e.error),e.next&&e.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const e=""===this._token;if(!(this._refreshRequired||e&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(e=>{this._isConnecting()&&(this._data=e,this._initializeTransport())}).catch(e=>this._handleGetDataError(e)):this._initializeTransport());const t=this;this._getToken().then(function(e){t._isConnecting()&&(null!=e&&void 0!=e?(t._token=e,t._debug("connection token refreshed"),t._config.getData?t._config.getData().then(function(e){t._isConnecting()&&(t._data=e,t._initializeTransport())}).catch(e=>t._handleGetDataError(e)):t._initializeTransport()):t._failUnauthorized())}).catch(function(e){if(!t._isConnecting())return;if(e instanceof J)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:w.clientConnectToken,message:void 0!==e?e.toString():""}});const n=t._getReconnectDelay();t._debug("error on getting connection token, reconnect after "+n+" milliseconds",e),t._reconnecting=!1,t._reconnectTimeout=setTimeout(()=>{t._startReconnecting()},n)})}_handleGetDataError(e){if(e instanceof J)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:w.badConfiguration,message:(null===e||void 0===e?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===P.Connecting&&(109===e.code&&(this._refreshRequired=!0),e.code<100||!0===e.temporary||109===e.code?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let n=!1;for(const s in this._serverSubs)if(this._serverSubs.hasOwnProperty(s)&&this._serverSubs[s].recoverable){n=!0;const e={recover:!0};this._serverSubs[s].offset&&(e.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(e.epoch=this._serverSubs[s].epoch),t[s]=e}return n&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const n={channel:e};return void 0!==t&&(t.since&&(n.since={offset:t.since.offset},t.since.epoch&&(n.since.epoch=t.since.epoch)),void 0!==t.limit&&(n.limit=t.limit),!0===t.reverse&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const n=setTimeout(function(){t({code:w.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((n,s)=>{this._call(e,!1).then(e=>{var s;const i=t(e.reply);n(i),null===(s=e.next)||void 0===s||s.call(e)},e=>{var t;s(e.error),null===(t=e.next)||void 0===t||t.call(e)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let e;this._dispatchPromise=new Promise(t=>{e=t}),this._dispatchSynchronized(t,e)})}_dispatchSynchronized(e,t){let n=Promise.resolve();for(const s in e)e.hasOwnProperty(s)&&(n=n.then(()=>this._dispatchReply(e[s])));n=n.then(()=>{t()})}_dispatchReply(e){let t;const n=new Promise(e=>{t=e});if(void 0===e||null===e)return this._debug("dispatch: got undefined or null reply"),t(),n;const s=e.id;return s&&s>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),n}_call(e,t){return new Promise((n,s)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,s),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(P.Connecting)&&this.emit("connecting",{code:S.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,n){if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const i={code:e,reason:t};let r=!1;if(n?r=this._setState(P.Connecting):(r=this._setState(P.Disconnected),this._rejectPromises({code:w.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===P.Connecting&&this._clearReconnectTimeout(),s===P.Connected&&this._clearConnectedState(),r&&(this._isConnecting()?this.emit("connecting",i):this.emit("disconnected",i)),this._transport){this._debug("closing existing transport");const e=this._transport;this._transport=null,e.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(T.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:w.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new J("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(n){if(e!==t._client)return;if(!n)return void t._failUnauthorized();if(t._token=n,t._debug("connection token refreshed"),!t._isConnected())return;const s={refresh:{token:t._token}};t._call(s,!1).then(e=>{const n=e.reply.refresh;t._refreshResponse(n),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){t._isConnected()&&(e instanceof J?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:w.clientRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())))})}_refreshError(e){e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return N(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),x(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const t={unsubscribe:{channel:e.channel}},n=this;return new Promise((e,s)=>{this._call(t,!1).then(t=>{e(),t.next&&t.next()},t=>{e(),t.next&&t.next(),n._disconnect(S.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const e in this._subs)if(this._subs.hasOwnProperty(e)){const n=this._subs[e];if(n._id===t)return n}return null}const n=this._subs[e];return n||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const n=this._subs[t];if(!0!==n._inflight&&n.state===R.Subscribing){const t=n._subscribe();t&&e.push(t)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(P.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),x(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=!0===e.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];this._serverSubs[t]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const s=this._getSubscribeContext(t,n);this.emit("subscribed",s)}for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];if(n.recovered){const e=n.publications;if(e&&e.length>0)for(const n in e)e.hasOwnProperty(n)&&this._handlePublication(t,e[n])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(S.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(n.recovered=!0),t.positioned&&(n.positioned=!0),t.recoverable&&(n.recoverable=!0),t.was_recovering&&(n.wasRecovering=!0);let s="";"epoch"in t&&(s=t.epoch);let i=0;return"offset"in t&&(i=t.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:i,epoch:s}),Array.isArray(t.publications)&&t.publications.length>0&&(n.hasRecoveredPublications=!0),t.data&&(n.data=t.data),n}_handleReply(e,t){const n=e.id;if(!(n in this._callbacks))return void t();const s=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],"error"in(i=e)&&null!==i.error){const n=s.errback;if(!n)return void t();n({error:{code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1},next:t})}else{const n=s.callback;if(!n)return;n({reply:e,next:t})}var i}_handleJoin(e,t,n){const s=this._getSub(e,n);if(s||!e)s._handleJoin(t);else if(this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",n)}}_handleLeave(e,t,n){const s=this._getSub(e,n);if(s||!e)s._handleLeave(t);else if(this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",n)}}_handleUnsubscribe(e,t){const n=this._getSub(e,0);n||!e?t.code<2500?n._setUnsubscribed(t.code,t.reason,!1):n._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let n=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(n=!1),this._disconnect(t,e.reason,n)}_getPublicationContext(e,t){const n={channel:e,data:t.data};return t.offset&&(n.offset=t.offset),t.info&&(n.info=this._getJoinLeaveContext(t.info)),t.tags&&(n.tags=t.tags),n}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},n=e.conn_info;n&&(t.connInfo=n);const s=e.chan_info;return s&&(t.chanInfo=s),t}_handlePublication(e,t,n){const s=this._getSub(e,n);if(s||!e)s._handlePublication(t);else if(this._isServerSub(e)){const n=this._getPublicationContext(e,t);this.emit("publication",n),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const e={};this._transportSendCommands([e])}e()}_handlePush(e,t){const n=e.channel,s=e.id;e.pub?this._handlePublication(n,e.pub,s):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,s):e.leave?this._handleLeave(n,e.leave,s):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,n){const s={code:e,message:t};return n&&(s.temporary=!0),s}_registerCall(e,t,n){this._callbacks[e]={callback:t,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],I(n)&&n({error:this._createErrorObject(w.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}V.SubscriptionState=R,V.State=P,V.UnauthorizedError=J}}]);
|
|
2
|
+
//# sourceMappingURL=921.58d10f34.chunk.js.map
|