@dodoex/wallet-web3 0.5.4 → 0.6.0

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.
Files changed (84) hide show
  1. package/dist/__tslib-cf28c574.js +1 -0
  2. package/dist/{alchemy-provider-5870b6fa-7183581f.js → alchemy-provider-5870b6fa-e4fa48d3.js} +1 -1
  3. package/dist/{alchemy-websocket-provider-213da986-d5a91aac.js → alchemy-websocket-provider-213da986-dc2bcf5c.js} +1 -1
  4. package/dist/{blocto-0ec2fc36.js → blocto-2fb1d4e9.js} +1 -1
  5. package/dist/browser-3f7e560e.js +1 -0
  6. package/dist/{ccip-d1141d3a.js → ccip-3c08ea13.js} +1 -1
  7. package/dist/cjs/__tslib-c375fca0.cjs +1 -0
  8. package/dist/cjs/{alchemy-provider-5870b6fa-94b8a05d.cjs → alchemy-provider-5870b6fa-00140867.cjs} +1 -1
  9. package/dist/cjs/{alchemy-websocket-provider-213da986-cb2dca69.cjs → alchemy-websocket-provider-213da986-b2e3ea59.cjs} +1 -1
  10. package/dist/cjs/{blocto-c4470598.cjs → blocto-b086f036.cjs} +1 -1
  11. package/dist/cjs/browser-d0e333da.cjs +1 -0
  12. package/dist/cjs/{ccip-466d4e59.cjs → ccip-248539f9.cjs} +1 -1
  13. package/dist/cjs/{draggabilly-53856a31.cjs → draggabilly-f7eacd66.cjs} +1 -1
  14. package/dist/cjs/id-a6c483f9.cjs +1 -0
  15. package/dist/cjs/{index-9075d9c2.cjs → index-1a09310e.cjs} +1 -1
  16. package/dist/cjs/{index-6aa1755b.cjs → index-24e8d66c.cjs} +2 -2
  17. package/dist/cjs/index-2659a245.cjs +2 -0
  18. package/dist/cjs/{index-63b5eebb.cjs → index-54591c6b.cjs} +1 -1
  19. package/dist/cjs/{index-9d9946f3.cjs → index-83b277b8.cjs} +7 -7
  20. package/dist/cjs/index-908a0281.cjs +27 -0
  21. package/dist/cjs/index-97619c59.cjs +15 -0
  22. package/dist/cjs/{index-86ef4f22.cjs → index-9dd3dd7e.cjs} +1 -1
  23. package/dist/cjs/{index-c4c73f44.cjs → index-ace56b81.cjs} +1 -1
  24. package/dist/cjs/index-b64e1d7e.cjs +1 -0
  25. package/dist/cjs/{index-56fff369.cjs → index-d297664c.cjs} +1 -1
  26. package/dist/cjs/index-d965eac9.cjs +1 -0
  27. package/dist/cjs/index-e65f9734.cjs +15 -0
  28. package/dist/cjs/{index-76cccf0c.cjs → index-fd28b030.cjs} +1 -1
  29. package/dist/cjs/index.cjs +1 -1
  30. package/dist/cjs/index.es-e98c5ee4.cjs +9 -0
  31. package/dist/cjs/{interface-d5ec613a.cjs → interface-eb633eac.cjs} +1 -1
  32. package/dist/cjs/{lib-typedarrays-afe9c8e7.cjs → lib-typedarrays-f699b687.cjs} +1 -1
  33. package/dist/cjs/mm-install-modal_2.entry-4950a7e9.cjs +1 -0
  34. package/dist/cjs/{portis-9af3489b.cjs → portis-0c036243.cjs} +1 -1
  35. package/dist/cjs/rainbow-57ada25b.cjs +1 -0
  36. package/dist/cjs/{sha224-8f3f5508.cjs → sha224-267753d8.cjs} +1 -1
  37. package/dist/cjs/{sha256-6785be1d.cjs → sha256-d6829c39.cjs} +1 -1
  38. package/dist/cjs/{typed-data-a102eb38.cjs → typed-data-12a9baf4.cjs} +1 -1
  39. package/dist/cjs/{uAuth-22dae0a4.cjs → uAuth-0858f962.cjs} +1 -1
  40. package/dist/cjs/{walletConnect-d4368503.cjs → walletConnect-c55b3f29.cjs} +1 -1
  41. package/dist/cjs/{walletLink-1b5e5056.cjs → walletLink-961041df.cjs} +2 -2
  42. package/dist/{draggabilly-96bd4e8a.js → draggabilly-921a68cb.js} +1 -1
  43. package/dist/id-d72ad2e3.js +1 -0
  44. package/dist/index-022bd88c.js +27 -0
  45. package/dist/{index-9a72391b.js → index-18f1c3bb.js} +1 -1
  46. package/dist/index-21067fcb.js +15 -0
  47. package/dist/index-2dc796bb.js +2 -0
  48. package/dist/{index-d9690f1f.js → index-3b7c9150.js} +1 -1
  49. package/dist/{index-aa09ffe2.js → index-621d68a7.js} +1 -1
  50. package/dist/index-6b5aff68.js +1 -0
  51. package/dist/index-7b0eeb5c.js +1 -0
  52. package/dist/{index-0534a22e.js → index-82e4bb0d.js} +3 -3
  53. package/dist/{index-de489272.js → index-a98e886d.js} +5 -5
  54. package/dist/{index-ec77233b.js → index-d3e54bda.js} +1 -1
  55. package/dist/{index-29d50f5e.js → index-d815c390.js} +1 -1
  56. package/dist/{index-b27ec2be.js → index-e0e62601.js} +1 -1
  57. package/dist/{index-25f5dd77.js → index-ff4c01ce.js} +1 -1
  58. package/dist/index.es-e17cf755.js +9 -0
  59. package/dist/index.js +1 -1
  60. package/dist/{interface-501ba1ce.js → interface-b09eb8d7.js} +1 -1
  61. package/dist/lib-typedarrays-8b3801fe.js +1 -0
  62. package/dist/mm-install-modal_2.entry-e9e33358.js +1 -0
  63. package/dist/{portis-59e75b95.js → portis-57c88ff3.js} +1 -1
  64. package/dist/rainbow-c820ccae.js +1 -0
  65. package/dist/sha224-5ae0e997.js +1 -0
  66. package/dist/{sha256-cdb06d7c.js → sha256-260a708c.js} +1 -1
  67. package/dist/{typed-data-d46cb643.js → typed-data-7ba4540a.js} +1 -1
  68. package/dist/{uAuth-a93ad1ec.js → uAuth-253510eb.js} +1 -1
  69. package/dist/{walletConnect-23af88ec.js → walletConnect-fc6f0e52.js} +1 -1
  70. package/dist/{walletLink-782b101e.js → walletLink-d75a8dc8.js} +2 -2
  71. package/package.json +2 -2
  72. package/dist/cjs/id-07cfd31e.cjs +0 -1
  73. package/dist/cjs/index-af8c9c8e.cjs +0 -15
  74. package/dist/cjs/index-b82ccec9.cjs +0 -9
  75. package/dist/cjs/index.es-d9e722ea.cjs +0 -9
  76. package/dist/cjs/rainbow-4b5d0839.cjs +0 -1
  77. package/dist/cjs/v4-3e682452.cjs +0 -1
  78. package/dist/id-6dc2a6aa.js +0 -1
  79. package/dist/index-66392fdc.js +0 -9
  80. package/dist/index.es-d60f6859.js +0 -9
  81. package/dist/lib-typedarrays-5ac4ff04.js +0 -1
  82. package/dist/rainbow-2c04e9df.js +0 -1
  83. package/dist/sha224-b20bdf3b.js +0 -1
  84. package/dist/v4-95658a31.js +0 -1
@@ -0,0 +1 @@
1
+ "use strict";var e=require("./index-83b277b8.cjs"),t=require("./__tslib-c375fca0.cjs");function s(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(s){if("default"!==s&&!(s in e)){var n=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,n.get?n:{enumerable:!0,get:function(){return t[s]}})}}))})),Object.freeze(e)}var n,i={},r={},o={},a={},c={};function h(){return n||(n=1,Object.defineProperty(c,"__esModule",{value:!0}),c.E_CANCELED=c.E_ALREADY_LOCKED=c.E_TIMEOUT=void 0,c.E_TIMEOUT=new Error("timeout while waiting for mutex to become available"),c.E_ALREADY_LOCKED=new Error("mutex already locked"),c.E_CANCELED=new Error("request for lock canceled")),c}Object.defineProperty(a,"__esModule",{value:!0});var u=t.require$$0,l=h(),d=function(){function e(e,t){void 0===t&&(t=l.E_CANCELED),this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}return e.prototype.acquire=function(e,t){var s=this;if(void 0===e&&(e=1),void 0===t&&(t=0),e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));return new Promise((function(n,i){var r={resolve:n,reject:i,weight:e,priority:t},o=_(s._queue,(function(e){return t<=e.priority}));-1===o&&e<=s._value?s._dispatchItem(r):s._queue.splice(o+1,0,r)}))},e.prototype.runExclusive=function(e){return u.__awaiter(this,arguments,void 0,(function(e,t,s){var n,i,r;return void 0===t&&(t=1),void 0===s&&(s=0),u.__generator(this,(function(o){switch(o.label){case 0:return[4,this.acquire(t,s)];case 1:n=o.sent(),i=n[0],r=n[1],o.label=2;case 2:return o.trys.push([2,,4,5]),[4,e(i)];case 3:return[2,o.sent()];case 4:return r(),[7];case 5:return[2]}}))}))},e.prototype.waitForUnlock=function(e,t){var s=this;if(void 0===e&&(e=1),void 0===t&&(t=0),e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));return this._couldLockImmediately(e,t)?Promise.resolve():new Promise((function(n){var i,r,o;s._weightedWaiters[e-1]||(s._weightedWaiters[e-1]=[]),i=s._weightedWaiters[e-1],r={resolve:n,priority:t},o=_(i,(function(e){return r.priority<=e.priority})),i.splice(o+1,0,r)}))},e.prototype.isLocked=function(){return this._value<=0},e.prototype.getValue=function(){return this._value},e.prototype.setValue=function(e){this._value=e,this._dispatchQueue()},e.prototype.release=function(e){if(void 0===e&&(e=1),e<=0)throw new Error("invalid weight ".concat(e,": must be positive"));this._value+=e,this._dispatchQueue()},e.prototype.cancel=function(){var e=this;this._queue.forEach((function(t){return t.reject(e._cancelError)})),this._queue=[]},e.prototype._dispatchQueue=function(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()},e.prototype._dispatchItem=function(e){var t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])},e.prototype._newReleaser=function(e){var t=this,s=!1;return function(){s||(s=!0,t.release(e))}},e.prototype._drainUnlockWaiters=function(){if(0===this._queue.length)for(var e=this._value;e>0;e--){(s=this._weightedWaiters[e-1])&&(s.forEach((function(e){return e.resolve()})),this._weightedWaiters[e-1]=[])}else{var t=this._queue[0].priority;for(e=this._value;e>0;e--){var s;if(s=this._weightedWaiters[e-1]){var n=s.findIndex((function(e){return e.priority<=t}));(-1===n?s:s.splice(0,n)).forEach((function(e){return e.resolve()}))}}}},e.prototype._couldLockImmediately=function(e,t){return(0===this._queue.length||this._queue[0].priority<t)&&e<=this._value},e}();function _(e,t){for(var s=e.length-1;s>=0;s--)if(t(e[s]))return s;return-1}a.default=d,Object.defineProperty(o,"__esModule",{value:!0});var f=t.require$$0,p=a,b=function(){function e(e){this._semaphore=new p.default(1,e)}return e.prototype.acquire=function(){return f.__awaiter(this,arguments,void 0,(function(e){var t;return void 0===e&&(e=0),f.__generator(this,(function(s){switch(s.label){case 0:return[4,this._semaphore.acquire(1,e)];case 1:return t=s.sent(),[2,t[1]]}}))}))},e.prototype.runExclusive=function(e,t){return void 0===t&&(t=0),this._semaphore.runExclusive((function(){return e()}),1,t)},e.prototype.isLocked=function(){return this._semaphore.isLocked()},e.prototype.waitForUnlock=function(e){return void 0===e&&(e=0),this._semaphore.waitForUnlock(1,e)},e.prototype.release=function(){this._semaphore.isLocked()&&this._semaphore.release()},e.prototype.cancel=function(){return this._semaphore.cancel()},e}();o.default=b;var g={};Object.defineProperty(g,"__esModule",{value:!0}),g.withTimeout=void 0;var m=t.require$$0,v=h();function y(e){return void 0!==e.getValue}g.withTimeout=function(e,t,s){var n=this;return void 0===s&&(s=v.E_TIMEOUT),{acquire:function(i,r){var o;if(y(e)?o=i:(o=void 0,r=i),void 0!==o&&o<=0)throw new Error("invalid weight ".concat(o,": must be positive"));return new Promise((function(i,a){return m.__awaiter(n,void 0,void 0,(function(){var n,c,h,u;return m.__generator(this,(function(l){switch(l.label){case 0:n=!1,c=setTimeout((function(){n=!0,a(s)}),t),l.label=1;case 1:return l.trys.push([1,3,,4]),[4,y(e)?e.acquire(o,r):e.acquire(r)];case 2:return h=l.sent(),n?(Array.isArray(h)?h[1]:h)():(clearTimeout(c),i(h)),[3,4];case 3:return u=l.sent(),n||(clearTimeout(c),a(u)),[3,4];case 4:return[2]}}))}))}))},runExclusive:function(e,t,s){return m.__awaiter(this,void 0,void 0,(function(){var n,i;return m.__generator(this,(function(r){switch(r.label){case 0:n=function(){},r.label=1;case 1:return r.trys.push([1,,7,8]),[4,this.acquire(t,s)];case 2:return i=r.sent(),Array.isArray(i)?(n=i[1],[4,e(i[0])]):[3,4];case 3:return[2,r.sent()];case 4:return n=i,[4,e()];case 5:return[2,r.sent()];case 6:return[3,8];case 7:return n(),[7];case 8:return[2]}}))}))},release:function(t){e.release(t)},cancel:function(){return e.cancel()},waitForUnlock:function(n,i){var r;if(y(e)?r=n:(r=void 0,i=n),void 0!==r&&r<=0)throw new Error("invalid weight ".concat(r,": must be positive"));return new Promise((function(n,o){var a=setTimeout((function(){return o(s)}),t);(y(e)?e.waitForUnlock(r,i):e.waitForUnlock(i)).then((function(){clearTimeout(a),n()}))}))},isLocked:function(){return e.isLocked()},getValue:function(){return e.getValue()},setValue:function(t){return e.setValue(t)}}};var S={};Object.defineProperty(S,"__esModule",{value:!0}),S.tryAcquire=void 0;var w=h(),T=g;S.tryAcquire=function(e,t){return void 0===t&&(t=w.E_ALREADY_LOCKED),(0,T.withTimeout)(e,0,t)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tryAcquire=e.withTimeout=e.Semaphore=e.Mutex=void 0;var s=t.require$$0,n=o;Object.defineProperty(e,"Mutex",{enumerable:!0,get:function(){return n.default}});var i=a;Object.defineProperty(e,"Semaphore",{enumerable:!0,get:function(){return i.default}});var r=g;Object.defineProperty(e,"withTimeout",{enumerable:!0,get:function(){return r.withTimeout}});var c=S;Object.defineProperty(e,"tryAcquire",{enumerable:!0,get:function(){return c.tryAcquire}}),s.__exportStar(h(),e)}(r);var P={};!function(e){function t(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var n,i={exports:{}};var r,o,a,c,h,u,l,d,_,f=function(){if(n)return i.exports;n=1;var e,t="object"==typeof Reflect?Reflect:null,s=t&&"function"==typeof t.apply?t.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}i.exports=o,i.exports.once=function(e,t){return new Promise((function(s,n){function i(s){e.removeListener(t,r),n(s)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",i),s([].slice.call(arguments))}b(e,t,r,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&b(e,"error",t,s)}(e,i,{once:!0})}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,s,n){var i,r,o,a;if(c(s),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),r=e._events),o=r[t]),void 0===o)o=r[t]=s,++e._eventsCount;else if("function"==typeof o?o=r[t]=n?[s,o]:[o,s]:n?o.unshift(s):o.push(s),(i=h(e))>0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,a=u,console&&console.warn&&console.warn(a)}return e}function l(){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 d(e,t,s){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},i=l.bind(n);return i.listener=s,n.wrapFn=i,i}function _(e,t,s){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?s?[i.listener||i]:[i]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(i):p(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function p(e,t){for(var s=new Array(t),n=0;n<t;++n)s[n]=e[n];return s}function b(e,t,s,n){if("function"==typeof e.on)n.once?e.once(t,s):e.on(t,s);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){n.once&&e.removeEventListener(t,i),s(r)}))}}return Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.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},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(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},o.prototype.getMaxListeners=function(){return h(this)},o.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,r=this._events;if(void 0!==r)i=i&&void 0===r.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var h=c.length,u=p(c,h);for(n=0;n<h;++n)s(u[n],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return c(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var s,n,i,r,o;if(c(t),void 0===(n=this._events))return this;if(void 0===(s=n[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(i=-1,r=s.length-1;r>=0;r--)if(s[r]===t||s[r].listener===t){o=s[r].listener,i=r;break}if(i<0)return this;0===i?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,i),1===s.length&&(n[e]=s[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,s,n;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var i,r=Object.keys(s);for(n=0;n<r.length;++n)"removeListener"!==(i=r[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return _(this,e,!0)},o.prototype.rawListeners=function(e){return _(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},i.exports}(),p=s(f);function b(e){return null!=e&&"function"==typeof e}function g(e,t,s){e>31&&(e=31);const n=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)}(0,Math.min(s,t*Math.pow(2,e)));return Math.min(s,t+n)}function m(e){return Math.min(1e3*e,2147483647)}e.errorCodes=void 0,(r=e.errorCodes||(e.errorCodes={}))[r.timeout=1]="timeout",r[r.transportClosed=2]="transportClosed",r[r.clientDisconnected=3]="clientDisconnected",r[r.clientClosed=4]="clientClosed",r[r.clientConnectToken=5]="clientConnectToken",r[r.clientRefreshToken=6]="clientRefreshToken",r[r.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",r[r.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",r[r.subscriptionRefreshToken=9]="subscriptionRefreshToken",r[r.transportWriteError=10]="transportWriteError",r[r.connectionClosed=11]="connectionClosed",r[r.badConfiguration=12]="badConfiguration",r[r.subscriptionGetState=13]="subscriptionGetState",r[r.sharedPollGetSignature=14]="sharedPollGetSignature",e.connectingCodes=void 0,(o=e.connectingCodes||(e.connectingCodes={}))[o.connectCalled=0]="connectCalled",o[o.transportClosed=1]="transportClosed",o[o.noPing=2]="noPing",o[o.subscribeTimeout=3]="subscribeTimeout",o[o.unsubscribeError=4]="unsubscribeError",e.disconnectedCodes=void 0,(a=e.disconnectedCodes||(e.disconnectedCodes={}))[a.disconnectCalled=0]="disconnectCalled",a[a.unauthorized=1]="unauthorized",a[a.badProtocol=2]="badProtocol",a[a.messageSizeLimit=3]="messageSizeLimit",e.subscribingCodes=void 0,(c=e.subscribingCodes||(e.subscribingCodes={}))[c.subscribeCalled=0]="subscribeCalled",c[c.transportClosed=1]="transportClosed",e.unsubscribedCodes=void 0,(h=e.unsubscribedCodes||(e.unsubscribedCodes={}))[h.unsubscribeCalled=0]="unsubscribeCalled",h[h.unauthorized=1]="unauthorized",h[h.clientClosed=2]="clientClosed",e.subscriptionFlags=void 0,(u=e.subscriptionFlags||(e.subscriptionFlags={}))[u.channelCompaction=1]="channelCompaction",u[u.rejectUnrecovered=2]="rejectUnrecovered",e.State=void 0,(l=e.State||(e.State={})).Disconnected="disconnected",l.Connecting="connecting",l.Connected="connected",e.SubscriptionState=void 0,(d=e.SubscriptionState||(e.SubscriptionState={})).Unsubscribed="unsubscribed",d.Subscribing="subscribing",d.Subscribed="subscribed",function(e){e[e.Live=0]="Live",e[e.Stream=1]="Stream",e[e.State=2]="State"}(_||(_={}));class v extends p{constructor(t,s,n){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this._getState=null,this._map=!1,this._mapPresenceType=1,this._mapPhase=null,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPageSize=0,this._mapUnrecoverableStrategy="from_scratch",this._debounceMs=0,this._debouncePending=new Map,this._sharedPoll=!1,this._sharedPollEpoch="",this._sharedPollTrackedItems=new Map,this._sharedPollGetSignature=null,this._sharedPollSignatureRefreshTimeout=null,this._sharedPollSignatureRefreshAttempts=0,this._sharedPollTrackRetryTimeout=null,this._sharedPollTrackRetryAttempts=0,this._sharedPollReplayRetryTimeout=null,this._sharedPollReplayRetryAttempts=0,this._sharedPollSignatures=[],this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1,this.channel=s,this.state=e.SubscriptionState.Unsubscribed,this._centrifuge=t,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._prevValueMap=new Map,this._unsubPromise=Promise.resolve(),this._deltaNumPubs=0,this._deltaNumFull=0,this._deltaNumDelta=0,this._deltaBytesReceived=0,this._deltaBytesDecoded=0,this._setOptions(n),this.type=this._sharedPoll?"shared_poll":this._map?"map":"stream",this._centrifuge._debugEnabled?(this.on("state",(e=>{this._debug("subscription state",s,e.oldState,"->",e.newState)})),this.on("error",(e=>{this._debug("subscription error",s,e)}))):this.on("error",(function(){Function.prototype()}))}ready(t){return this.state===e.SubscriptionState.Unsubscribed?Promise.reject({code:e.errorCodes.subscriptionUnsubscribed,message:this.state}):this.state===e.SubscriptionState.Subscribed?Promise.resolve():new Promise(((s,n)=>{const i={resolve:s,reject:n};t&&(i.timeout=setTimeout((function(){n({code:e.errorCodes.timeout,message:"timeout"})}),t)),this._promises[this._nextPromiseId()]=i}))}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(e.subscribingCodes.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(e.unsubscribedCodes.unsubscribeCalled,"unsubscribe called",!0)}_debouncedPublish(e,t,s){const n=this._debouncePending.get(e);if(n)return n.data=t,n.dirty=!0,Promise.resolve({});const i={data:t,dirty:!1,timer:null};i.timer=setTimeout((()=>{const t=this._debouncePending.get(e);if(!t||!t.dirty)return void this._debouncePending.delete(e);t.dirty=!1;const n=t.data;(s?this._centrifuge.mapPublish(this.channel,e,n):this._centrifuge.publish(this.channel,n)).catch((()=>{})),t.timer=setTimeout((()=>{const t=this._debouncePending.get(e);t&&t.dirty?(this._debouncePending.delete(e),this._debouncedPublish(e,t.data,s)):this._debouncePending.delete(e)}),this._debounceMs)}),this._debounceMs),this._debouncePending.set(e,i);return s?this._centrifuge.mapPublish(this.channel,e,t):this._centrifuge.publish(this.channel,t)}_cancelDebounce(e){const t=this._debouncePending.get(e);t&&(clearTimeout(t.timer),this._debouncePending.delete(e))}_cancelAllDebounce(){for(const[,e]of this._debouncePending)clearTimeout(e.timer);this._debouncePending.clear()}presence(){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)}))}presenceStats(){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)}))}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e,this._map&&(this._recover=!1,this._offset=null,this._epoch=null)}setData(e){this._data=e}deltaStats(){const e=this._deltaBytesDecoded;return{numPublications:this._deltaNumPubs,numFullPayloads:this._deltaNumFull,numDeltaPayloads:this._deltaNumDelta,bytesReceived:this._deltaBytesReceived,bytesDecoded:e,compressionRatio:e>0?1-this._deltaBytesReceived/e:0}}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:e.errorCodes.subscriptionUnsubscribed,message:this.state}):new Promise(((t,s)=>{const n=this._centrifuge._config.timeout,i=setTimeout((()=>{s({code:e.errorCodes.timeout,message:"timeout"})}),n);this._promises[this._nextPromiseId()]={timeout:i,resolve:t,reject:s}}))}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===e.SubscriptionState.Unsubscribed}_isSubscribing(){return this.state===e.SubscriptionState.Subscribing}_isSubscribed(){return this.state===e.SubscriptionState.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(),this._clearSharedPollSignatureRefresh(),this._clearSharedPollTrackRetry(),this._clearSharedPollReplayRetry(),this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1}_invalidateState(){this._token="",this._prevValueMap=new Map,this._map&&(this._offset=null,this._epoch=null,this._recover=!1,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPhase=null)}_setSubscribed(t){if(!this._isSubscribing())return;if(this._clearSubscribingState(),t.id&&(this._id=t.id),t.recoverable&&(this._recover=!0,this._offset=t.offset||0,this._epoch=t.epoch||""),t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._sharedPoll){const e=t.epoch||"";if(""!==this._sharedPollEpoch&&this._sharedPollEpoch!==e)for(const e of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(e,0);this._sharedPollEpoch=e}this._setState(e.SubscriptionState.Subscribed);const s=this._centrifuge._getSubscribeContext(this.channel,t);this.emit("subscribed",s),this._resolvePromises();const n=t.publications;if(n&&n.length>0)for(const e in n)n.hasOwnProperty(e)&&this._handlePublication(n[e]);!0===t.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),m(t.ttl)))}_setSubscribing(s,n){return t(this,void 0,void 0,(function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(e.SubscriptionState.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:s,reason:n}),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._map?(this._mapSubscribe(),null):this._getState&&null===this._offset?(this._loadStreamState(),null):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)}_loadStreamState(){this._isSubscribing()?this._getState().then((e=>{this._isSubscribing()?(this._offset=e.offset,this._epoch=e.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():this._getSubscriptionToken().then((e=>this._handleTokenResponse(e))).catch((e=>this._handleTokenError(e)))):this._inflight=!1})).catch((t=>{this._isSubscribing()?(this._inflight=!1,this._subscribeError({code:e.errorCodes.subscriptionGetState,message:(null==t?void 0:t.toString())||"getState failed",temporary:!0})):this._inflight=!1})):this._inflight=!1}_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(t){if(this._isSubscribing()){if(t instanceof A)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:e.errorCodes.badConfiguration,message:(null==t?void 0:t.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(t){if(this._isSubscribing()){if(t instanceof A)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:e.errorCodes.subscriptionSubscribeToken,message:(null==t?void 0:t.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(t){const s={channel:this.channel};if(t&&(s.token=t),this._data&&(s.data=this._data),this._sharedPoll)return s.type=4,this._delta&&(s.delta=this._delta),{subscribe:s};if(this._positioned&&(s.positioned=!0),this._recoverable&&(s.recoverable=!0),this._joinLeave&&(s.join_leave=!0),s.flag=e.subscriptionFlags.channelCompaction,this._getState&&(s.flag|=e.subscriptionFlags.rejectUnrecovered),this._needRecover()){s.recover=!0;const e=this._getOffset();e&&(s.offset=e);const t=this._getEpoch();t&&(s.epoch=t)}return this._delta&&(s.delta=this._delta),this._tagsFilter&&(s.tf=this._tagsFilter),{subscribe:s}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(t){if(this._isSubscribing()){if(t.code!==e.errorCodes.timeout)return 112===t.code&&this._getState?(this._offset=null,this._epoch=null,this._recover=!1,this._prevValueMap=new Map,void this._scheduleResubscribe()):void this._subscribeError(t);this._centrifuge._disconnect(e.connectingCodes.subscribeTimeout,"subscribe timeout",!0)}}_handleSubscribeResponse(e){this._isSubscribing()&&(this._setSubscribed(e),this._sharedPoll&&this._sharedPollReplayTrack())}_setUnsubscribed(t,s,n){if(this._isUnsubscribed())return Promise.resolve();let i=Promise.resolve();return this._isSubscribed()?(n&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&n&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState(e.SubscriptionState.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:t,reason:s}),this._rejectPromises({code:e.errorCodes.subscriptionUnsubscribed,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){const t=(this._map||this._sharedPoll)&&e.key||"",{newData:s,newPrevValue:n,isDelta:i,wireBytes:r,fullBytes:o}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(t));e.data=s,this._deltaNumPubs++,this._deltaBytesReceived+=r,this._deltaBytesDecoded+=o,i?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(t):this._prevValueMap.set(t,n)}let t;if(this._sharedPoll){if(e.key&&!this._sharedPollTrackedItems.has(e.key))return;e.key&&(e.removed?this._sharedPollTrackedItems.delete(e.key):e.version&&this._sharedPollTrackedItems.set(e.key,e.version)),t=this._getSharedPollUpdateContext(e)}else t=this._map?this._getMapUpdateContext(e):this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),(this._map||this._sharedPoll)&&this.emit("update",t),e.offset&&(this._offset=e.offset),e.epoch&&(this._epoch=e.epoch)}_seedDeltaTracking(e){if(this._delta&&e.key)if("string"==typeof e.data){const t=e.data;e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,(new TextEncoder).encode(t));const s=t.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=s,this._deltaBytesDecoded+=s,e.data=JSON.parse(t)}else if(e.data instanceof Uint8Array){e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,e.data);const t=e.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=t,this._deltaBytesDecoded+=t}}_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(t){if(this._isSubscribing())if(t.code<100||109===t.code||!0===t.temporary){109===t.code&&(this._token="");const s={channel:this.channel,type:"subscribe",error:t};this._centrifuge.state===e.State.Connected&&this.emit("error",s),this._scheduleResubscribe()}else this._setUnsubscribed(t.code,t.message,!1)}_getResubscribeDelay(){const e=g(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");e.getState&&(this._getState=e.getState,this._recover=!0),!0===e.map&&(this._map=!0),void 0!==e.mapPageSize&&(this._mapPageSize=e.mapPageSize),void 0!==e.mapPresenceType&&(this._mapPresenceType=e.mapPresenceType,this._map=!0),e.mapUnrecoverableStrategy&&(this._mapUnrecoverableStrategy=e.mapUnrecoverableStrategy),!0===e.sharedPoll&&(this._sharedPoll=!0),e.sharedPollGetSignature&&(this._sharedPollGetSignature=e.sharedPollGetSignature)}}_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 t={channel:this.channel},s=this._getToken;return null===s?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:e.errorCodes.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new A(""))):s(t)}_refresh(){this._clearRefreshTimeout();const t=this;this._getSubscriptionToken().then((function(e){if(!t._isSubscribed())return;if(!e)return void t._failUnauthorized();t._token=e;const s={sub_refresh:{channel:t.channel,token:e}};t._centrifuge._call(s).then((e=>{const s=e.reply.sub_refresh;t._refreshResponse(s),e.next&&e.next()}),(e=>{t._refreshError(e.error),e.next&&e.next()}))})).catch((function(s){s instanceof A?t._failUnauthorized():(t.emit("error",{type:"refreshToken",channel:t.channel,error:{code:e.errorCodes.subscriptionRefreshToken,message:void 0!==s?s.toString():""}}),t._refreshTimeout=setTimeout((()=>t._refresh()),t._getRefreshRetryDelay()))}))}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),m(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 g(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(e.unsubscribedCodes.unauthorized,"unauthorized",!0)}_sendTrackRequest(e,t){if(0===e.length)return Promise.resolve();const s=[];let n=[],i=100;if(t&&t.length>0)for(const e of t)i+=e.length+4;for(const t of e){let e=100;for(const s of t.items)e+=s.key.length+16;n.length>0&&i+e>6e4&&(s.push(n),n=[],i=100),n.push(t),i+=e}n.length>0&&s.push(n);const r=(e,t)=>new Promise(((s,n)=>{const i={channel:this.channel,type:1,track:e.map((e=>({signature:e.signature,items:e.items.map((e=>e.version>0?e:{key:e.key}))})))};t&&t.length>0&&(i.untrack=t);const r={sub_refresh:i};this._centrifuge._call(r).then((e=>{this._handleTrackResponse(e.reply.sub_refresh),e.next&&e.next(),s()}),(e=>{e.next&&e.next(),n(e.error)}))}));return s.reduce(((e,s,n)=>e.then((()=>r(s,0===n?t:void 0)))),Promise.resolve())}_sendUntrackRequest(e){return new Promise(((t,s)=>{const n={sub_refresh:{channel:this.channel,type:2,untrack:e}};this._centrifuge._call(n).then((e=>{e.next&&e.next(),t()}),(e=>{e.next&&e.next(),s(e.error)}))}))}_handleTrackResponse(e){if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(const t of e.items)this._handlePublication(t);if(e&&!0===e.expires&&e.ttl>0){const t=Date.now()+1e3*e.ttl;this._maybeScheduleSharedPollSignatureRefresh(t)}}_maybeScheduleSharedPollSignatureRefresh(e){if(null===e)return this._sharedPollSignatureRefreshTargetMs=null,void this._clearSharedPollSignatureRefresh();this._isSubscribed()&&(null!==this._sharedPollSignatureRefreshTargetMs&&e>=this._sharedPollSignatureRefreshTargetMs||(this._sharedPollSignatureRefreshTargetMs=e,this._clearSharedPollSignatureRefresh(),this._sharedPollSignatureRefreshTimeout=setTimeout((()=>this._sharedPollRefreshSignature()),Math.max(0,e-Date.now()))))}_clearSharedPollSignatureRefresh(){null!==this._sharedPollSignatureRefreshTimeout&&(clearTimeout(this._sharedPollSignatureRefreshTimeout),this._sharedPollSignatureRefreshTimeout=null),this._sharedPollSignatureRefreshAttempts=0}_clearSharedPollTrackRetry(){null!==this._sharedPollTrackRetryTimeout&&(clearTimeout(this._sharedPollTrackRetryTimeout),this._sharedPollTrackRetryTimeout=null),this._sharedPollTrackRetryAttempts=0}_clearSharedPollReplayRetry(){null!==this._sharedPollReplayRetryTimeout&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_handleTrackError(e){this._isSubscribed()&&(this.emit("error",{type:"track",channel:this.channel,error:e}),109!==e.code?(e.code<100||!0===e.temporary)&&(this._sharedPollTrackRetryTimeout=setTimeout((()=>this._sharedPollReplayTrack()),g(this._sharedPollTrackRetryAttempts++,1e3,15e3))):this._sharedPollRefreshSignature())}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed())return;if(!this._sharedPollGetSignature)return;if(0===this._sharedPollTrackedItems.size)return;if(this._sharedPollSignatureRefreshInFlight)return;this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;const t=Array.from(this._sharedPollTrackedItems.keys()),s=this;this._sharedPollGetSignature({keys:t}).then((e=>{if(s._sharedPollSignatureRefreshInFlight=!1,!s._isSubscribed())return;s._sharedPollSignatureRefreshAttempts=0;const n=new Set(e.keys),i=[];for(const e of t)n.has(e)||(s._sharedPollTrackedItems.delete(e),i.push(e),s.emit("update",{channel:s.channel,key:e,data:null,removed:!0}));i.length>0&&s._sendUntrackRequest(i).catch((e=>{s.emit("error",{type:"untrack",channel:s.channel,error:e})}));const r=[];for(const t of e.keys){const e=s._sharedPollTrackedItems.get(t);void 0!==e&&r.push({key:t,version:e})}const o=new Set(e.keys),a=s._sharedPollSignatures.filter((e=>e.keys.some((e=>s._sharedPollTrackedItems.has(e)&&!o.has(e)))));s._sharedPollSignatures=r.length>0?[{keys:e.keys,signature:e.signature},...a]:a,0!==r.length&&s._sendTrackRequest([{items:r,signature:e.signature}]).catch((e=>{s._handleTrackError(e)}))})).catch((t=>{s._sharedPollSignatureRefreshInFlight=!1,s.emit("error",{type:"signatureRefresh",channel:s.channel,error:{code:e.errorCodes.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),s._sharedPollSignatureRefreshTimeout=setTimeout((()=>s._sharedPollRefreshSignature()),g(s._sharedPollSignatureRefreshAttempts++,5e3,3e4))}))}_sharedPollReplayTrack(){if(!this._isSubscribed())return;if(0===this._sharedPollTrackedItems.size&&0===this._sharedPollSignatures.length)return;const t=new Set,s=[],n=[];for(const e of this._sharedPollSignatures){const i=e.keys.map((e=>{var t;return{key:e,version:null!==(t=this._sharedPollTrackedItems.get(e))&&void 0!==t?t:0}}));s.push({items:i,signature:e.signature});for(const s of e.keys)this._sharedPollTrackedItems.has(s)?t.add(s):n.push(s)}s.length>0&&this._sendTrackRequest(s,n).catch((e=>{this._handleTrackError(e)}));const i=[];for(const e of this._sharedPollTrackedItems.keys())t.has(e)||i.push(e);if(0===i.length)return;if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:e.errorCodes.sharedPollGetSignature,message:"getSignature callback required for tracked keys without an explicit signature"}});const r=this;this._sharedPollGetSignature({keys:i}).then((e=>{if(!r._isSubscribed())return;r._clearSharedPollReplayRetry();const t=new Set(e.keys),s=[];for(const e of i)t.has(e)||(r._sharedPollTrackedItems.delete(e),s.push(e),r.emit("update",{channel:r.channel,key:e,data:null,removed:!0}));s.length>0&&r._sendUntrackRequest(s).catch((e=>{r.emit("error",{type:"untrack",channel:r.channel,error:e})}));const n=[];for(const t of e.keys){const e=r._sharedPollTrackedItems.get(t);void 0!==e&&n.push({key:t,version:e})}0!==n.length&&(r._sharedPollSignatures.push({keys:e.keys,signature:e.signature}),r._sendTrackRequest([{items:n,signature:e.signature}]).catch((e=>{r._handleTrackError(e)})))})).catch((t=>{r.emit("error",{type:"signatureRefresh",channel:r.channel,error:{code:e.errorCodes.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),r._sharedPollReplayRetryTimeout=setTimeout((()=>r._sharedPollReplayTrack()),g(r._sharedPollReplayRetryAttempts++,5e3,3e4))}))}_mapSubscribe(){if(this._debug("starting map subscribe on",this.channel),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._recover&&null!==this._offset&&null!==this._epoch||(this._prevValueMap=new Map),this._mapPhase=_.State,this._recover&&null!==this._offset&&null!==this._epoch)return this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=_.Stream,void this._fetchStream();this._canSubscribeWithoutGettingToken()?this._fetchSnapshot():this._getSubscriptionToken().then((e=>{if(this._isSubscribing()){if(!e)return this._inflight=!1,void this._failUnauthorized();this._token=e,this._fetchSnapshot()}else this._inflight=!1})).catch((e=>this._handleTokenError(e)))}_fetchSnapshot(e){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const t=this._buildMapSubscribeCommand(_.State,e);this._debug("map subscribe: fetching snapshot page",e?`cursor=${e}`:"initial"),this._centrifuge._call(t).then((e=>{const t=e.reply.subscribe;this._handleMapStateResponse(t),e.next&&e.next()}),(e=>{this._handleMapSubscribeError(e.error),e.next&&e.next()}))}_handleMapStateResponse(e){if(this._isSubscribing()){if(!e.phase)return this._debug("map subscribe: server forced LIVE transition during state pagination"),void this._handleMapLiveResponse(e);if(!this._epoch&&e.epoch&&(this._epoch=e.epoch,this._offset=e.offset||0),this._epoch&&e.epoch&&this._epoch!==e.epoch)return this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._mapStateBuffer=[],this._mapCursor="",this._epoch=null,this._offset=null,this._prevValueMap=new Map,void this._fetchSnapshot();if(e.state&&e.state.length>0)for(const t of e.state)this._seedDeltaTracking(t),this._mapStateBuffer.push(this._getMapUpdateContext(t));if(e.cursor)return this._mapCursor=e.cursor,void this._fetchSnapshot(this._mapCursor);this._transitionFromSnapshot()}else this._inflight=!1}_transitionFromSnapshot(){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=_.Stream,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const e=this._buildMapSubscribeCommand(_.Stream);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(e).then((e=>{const t=e.reply.subscribe;this._handleMapStreamResponse(t),e.next&&e.next()}),(e=>{this._handleMapSubscribeError(e.error),e.next&&e.next()}))}_handleMapStreamResponse(e){if(this._isSubscribing()){if(!e.phase)return this._debug("map subscribe: server forced LIVE transition during stream"),void this._handleMapLiveResponse(e);if(this._epoch&&e.epoch&&this._epoch!==e.epoch)return this._debug("map subscribe: epoch changed during stream, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._mapPhase=_.State,void this._fetchSnapshot();if(e.publications&&e.publications.length>0)for(const t of e.publications)this._seedDeltaTracking(t),this._mapStreamBuffer.push(this._getMapUpdateContext(t));void 0!==e.offset&&(this._offset=e.offset),this._fetchStream()}else this._inflight=!1}_handleMapLiveResponse(t){if(!this._isSubscribing())return void(this._inflight=!1);if(this._inflight=!1,this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during live transition, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._inflight=!0,this._mapPhase=_.State,void this._fetchSnapshot();if(t.state&&t.state.length>0)for(const e of t.state)this._seedDeltaTracking(e),this._mapStateBuffer.push(this._getMapUpdateContext(e));if(t.publications&&t.publications.length>0)for(const e of t.publications){if(this._delta&&t.delta){const t=e.key||"",{newData:s,newPrevValue:n,isDelta:i,wireBytes:r,fullBytes:o}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(t));e.data=s,this._deltaNumPubs++,this._deltaBytesReceived+=r,this._deltaBytesDecoded+=o,i?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(t):this._prevValueMap.set(t,n)}else this._delta&&e.key&&(e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,e.data));this._mapStreamBuffer.push(this._getMapUpdateContext(e))}this._offset=t.offset||0,this._epoch=t.epoch||"",this._clearSubscribingState(),t.id&&(this._id=t.id),this._recover=!0===t.recoverable,t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._setState(e.SubscriptionState.Subscribed);const s=this._centrifuge._getSubscribeContext(this.channel,t);if(s.state=this._mapStateBuffer,this.emit("subscribed",s),this._resolvePromises(),!s.recovered){if(this._mapStreamBuffer.length>0){const e=new Map;for(const t of this._mapStateBuffer)e.set(t.key,t);for(const t of this._mapStreamBuffer)t.removed?e.delete(t.key):e.set(t.key,t);this._mapStateBuffer=Array.from(e.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(const e of this._mapStreamBuffer)this.emit("publication",e),this.emit("update",e);this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,!0===t.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),m(t.ttl)))}_handleMapSubscribeError(t){if(this._inflight=!1,this._isSubscribing())if(t.code!==e.errorCodes.timeout){if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,this._prevValueMap=new Map,112===t.code&&"from_scratch"===this._mapUnrecoverableStrategy)return this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._offset=null,this._epoch=null,this._recover=!1,void this._scheduleResubscribe();this._subscribeError(t)}else this._centrifuge._disconnect(e.connectingCodes.subscribeTimeout,"subscribe timeout",!0)}_buildMapSubscribeCommand(t,s){const n={channel:this.channel,type:this._mapPresenceType||1,phase:t};return this._token&&(n.token=this._token),this._tagsFilter&&(n.tf=this._tagsFilter),this._delta&&(n.delta=this._delta),n.flag=e.subscriptionFlags.channelCompaction,t===_.State&&(this._mapPageSize>0&&(n.limit=this._mapPageSize),s&&(n.cursor=s),this._epoch?(n.offset=this._offset,n.epoch=this._epoch):this._data&&(n.data=this._data)),t===_.Stream&&(this._mapPageSize>0&&(n.limit=this._mapPageSize),n.offset=this._offset,n.epoch=this._epoch,this._recover&&(n.recover=!0,0===this._mapStreamBuffer.length&&this._data&&(n.data=this._data))),{subscribe:n}}_getMapUpdateContext(e){const t={channel:this.channel,data:e.data,key:e.key||""};return!0===e.removed&&(t.removed=!0),void 0!==e.offset&&(t.offset=e.offset),e.info&&(t.info=this._centrifuge._getJoinLeaveContext(e.info)),e.tags&&(t.tags=e.tags),t}_getSharedPollUpdateContext(e){const t={channel:this.channel,key:e.key||"",data:e.data};return!0===e.removed&&(t.removed=!0),void 0!==e.version&&(t.version=e.version),t}}class y extends v{publish(e){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish("",e,!1):this._centrifuge.publish(this.channel,e)}))}history(e){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)}))}}class S extends v{publish(e,s){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish(e,s,!0):this._centrifuge.mapPublish(this.channel,e,s)}))}remove(e){return t(this,void 0,void 0,(function*(){return yield this._methodCall(),this._cancelDebounce(e),this._centrifuge.mapRemove(this.channel,e)}))}}class w extends v{track(t,s){if(0===t.length)return;let n;const i=s;if("string"==typeof t[0]){n=t.map((e=>({key:e,version:0})))}else n=t;for(const e of n){const t=this._sharedPollTrackedItems.get(e.key);(void 0===t||e.version>t)&&this._sharedPollTrackedItems.set(e.key,e.version)}if(void 0!==i)return this._sharedPollSignatures.push({keys:n.map((e=>e.key)),signature:i}),void(this._isSubscribed()&&this._sendTrackRequest([{items:n,signature:i}]).catch((e=>{this._handleTrackError(e)})));if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:e.errorCodes.sharedPollGetSignature,message:"getSignature callback required for track(keys)"}});if(!this._isSubscribed())return;const r=n.map((e=>e.key));this._sharedPollGetSignature({keys:r}).then((e=>{if(!this._isSubscribed())return;const t=new Set(e.keys),s=[];for(const e of r)t.has(e)||(this._sharedPollTrackedItems.delete(e),s.push(e),this.emit("update",{channel:this.channel,key:e,data:null,removed:!0}));s.length>0&&this._sendUntrackRequest(s).catch((e=>{this.emit("error",{type:"untrack",channel:this.channel,error:e})}));const n=[];for(const t of e.keys){const e=this._sharedPollTrackedItems.get(t);void 0!==e&&n.push({key:t,version:e})}0!==n.length&&(this._sharedPollSignatures.push({keys:e.keys,signature:e.signature}),this._sendTrackRequest([{items:n,signature:e.signature}]).catch((e=>{this._handleTrackError(e)})))})).catch((t=>{this.emit("error",{type:"track",channel:this.channel,error:{code:e.errorCodes.sharedPollGetSignature,message:void 0!==t?t.toString():"getSignature failed"}})}))}untrack(e){for(const t of e)this._sharedPollTrackedItems.delete(t);this._sharedPollSignatures=this._sharedPollSignatures.filter((e=>e.keys.some((e=>this._sharedPollTrackedItems.has(e))))),this._isSubscribed()&&this._sendUntrackRequest(e).catch((e=>{this.emit("error",{type:"untrack",channel:this.channel,error:e})}))}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}}class T{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 P{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 s="";"protobuf"===e&&(s="centrifuge-protobuf"),this._transport=""!==s?new this.options.websocket(this.endpoint,s):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 E{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,s){const n=new EventTarget;return(0,e.options.fetch)(t,s).then(e._handleErrors).then((t=>{n.dispatchEvent(new Event("open"));let s="",i=0,r=new Uint8Array;const o=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return o.read().then((({done:o,value:c})=>{if(o)return n.dispatchEvent(new Event("close")),void t.close();try{if("json"===e._protocol)for(s+=e._utf8decoder.decode(c);i<s.length;)if("\n"===s[i]){const e=s.substring(0,i);n.dispatchEvent(new MessageEvent("message",{data:e})),s=s.substring(i+1),i=0}else++i;else{const t=new Uint8Array(r.length+c.length);for(t.set(r),t.set(c,r.length),r=t;;){const t=e.options.decoder.decodeReply(r);if(!t.ok)break;{const e=r.slice(0,t.pos);n.dispatchEvent(new MessageEvent("message",{data:e})),r=r.slice(t.pos)}}}}catch(e){return n.dispatchEvent(new Event("error",{detail:e})),n.dispatchEvent(new Event("close")),void t.close()}a()})).catch((function(e){n.dispatchEvent(new Event("error",{detail:e})),n.dispatchEvent(new Event("close")),t.close()}))}()})})).catch((e=>{n.dispatchEvent(new Event("error",{detail:e})),n.dispatchEvent(new Event("close"))})),n}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,s){let n,i;this._protocol=e,this._abortController=new AbortController,"json"===e?(n={Accept:"application/json","Content-Type":"application/json"},i=s):(n={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},i=s);const r={method:"POST",headers:n,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,s){let n,i;const r={session:t,node:s,data:e};"json"===this._protocol?(n={"Content-Type":"application/json"},i=JSON.stringify(r)):(n={"Content-Type":"application/octet-stream"},i=this.options.encoder.encodeEmulationRequest(r));const o={method:"POST",headers:n,body:i,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,o)}}class k{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,s){let n;n=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),n.searchParams.append("cf_connect",s);const i=new this.options.eventsource(n.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,s){const n={session:t,node:s,data:e},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,i)}}class C{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,s){return t(this,void 0,void 0,(function*(){let t;t=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===e&&t.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const n=new EventTarget;this._transport=new this.options.webtransport(t.toString()),this._transport.closed.then((()=>{s.onClose({code:4,reason:"connection closed"})})).catch((()=>{s.onClose({code:4,reason:"connection closed"})}));try{yield this._transport.ready}catch(e){return void this.close()}let i;try{i=yield this._transport.createBidirectionalStream()}catch(e){return void this.close()}this._stream=i,this._writer=this._stream.writable.getWriter(),n.addEventListener("close",(()=>{s.onClose({code:4,reason:"connection closed"})})),n.addEventListener("message",(e=>{s.onMessage(e.data)})),this._startReading(n),s.onOpen()}))}_startReading(e){return t(this,void 0,void 0,(function*(){const t=this._stream.readable.getReader();let s="",n=0,i=new Uint8Array;try{for(;;){const{done:r,value:o}=yield t.read();if(o.length>0)if("json"===this._protocol)for(s+=this._utf8decoder.decode(o);n<s.length;)if("\n"===s[n]){const t=s.substring(0,n);e.dispatchEvent(new MessageEvent("message",{data:t})),s=s.substring(n+1),n=0}else++n;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)break;{const s=i.slice(0,t.pos);e.dispatchEvent(new MessageEvent("message",{data:s})),i=i.slice(t.pos)}}}if(r)break}}catch(t){e.dispatchEvent(new Event("close"))}}))}close(){return t(this,void 0,void 0,(function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}}))}send(e){return t(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(e){this.close()}}))}}const R=[-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 O{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=R[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class I{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,s){for(let n=t;n<s;n++)this.a.push(e[n])}}function x(e){let t=0,s=0,n=0,i=0,r=0,o=e.length;for(;o>=16;)t=t+e[r+0]|0,s=s+e[r+1]|0,n=n+e[r+2]|0,i=i+e[r+3]|0,t=t+e[r+4]|0,s=s+e[r+5]|0,n=n+e[r+6]|0,i=i+e[r+7]|0,t=t+e[r+8]|0,s=s+e[r+9]|0,n=n+e[r+10]|0,i=i+e[r+11]|0,t=t+e[r+12]|0,s=s+e[r+13]|0,n=n+e[r+14]|0,i=i+e[r+15]|0,r+=16,o-=16;for(;o>=4;)t=t+e[r+0]|0,s=s+e[r+1]|0,n=n+e[r+2]|0,i=i+e[r+3]|0,r+=4,o-=4;switch(i=((i+(n<<8)|0)+(s<<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 D{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 s,n,i;if(e.delta){i=!0;const r=function(e,t){let s=0;const n=new O(t),i=e.length,r=t.length,o=n.getInt();if("\n"!==n.getChar())throw new Error("size integer not terminated by '\\n'");const a=new I;for(;n.haveBytes();){const t=n.getInt();let c;switch(n.getChar()){case"@":if(c=n.getInt(),n.haveBytes()&&","!==n.getChar())throw new Error("copy command not terminated by ','");if(s+=t,s>o)throw new Error("copy exceeds output file size");if(c+t>i)throw new Error("copy extends past end of input");a.putArray(e,c,c+t);break;case":":if(s+=t,s>o)throw new Error("insert command gives an output larger than predicted");if(t>r)throw new Error("insert count exceeds size of delta");a.putArray(n.a,n.pos,n.pos+t),n.pos+=t;break;case";":{const n=a.toByteArray(e);if(t!==x(n))throw new Error("bad checksum");if(s!==o)throw new Error("generated size does not match predicted size");return n}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(t,(new TextEncoder).encode(e.data));s=JSON.parse((new TextDecoder).decode(r)),n=r}else i=!1,s=JSON.parse(e.data),n=(new TextEncoder).encode(e.data);return{newData:s,newPrevValue:n,isDelta:i,wireBytes:e.data.length,fullBytes:n.length}}}const N={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 A extends Error{constructor(e){super(e),this.name=this.constructor.name}}class L extends p{constructor(t,s){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=e.State.Disconnected,this._transportIsOpen=!1,this._endpoint=t,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 D,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({},N),s),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 s=new y(this,e,t);return this._subs[e]=s,s}newMapSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new S(this,e,{token:null==t?void 0:t.token,getToken:null==t?void 0:t.getToken,data:null==t?void 0:t.data,minResubscribeDelay:null==t?void 0:t.minResubscribeDelay,maxResubscribeDelay:null==t?void 0:t.maxResubscribeDelay,delta:null==t?void 0:t.delta,tagsFilter:null==t?void 0:t.tagsFilter,map:!0,mapPageSize:null==t?void 0:t.pageSize,mapUnrecoverableStrategy:null==t?void 0:t.unrecoverableStrategy});return this._subs[e]=s,s}newMapClientsSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new S(this,e,{token:null==t?void 0:t.token,getToken:null==t?void 0:t.getToken,data:null==t?void 0:t.data,minResubscribeDelay:null==t?void 0:t.minResubscribeDelay,maxResubscribeDelay:null==t?void 0:t.maxResubscribeDelay,delta:null==t?void 0:t.delta,tagsFilter:null==t?void 0:t.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:null==t?void 0:t.pageSize,mapUnrecoverableStrategy:null==t?void 0:t.unrecoverableStrategy});return this._subs[e]=s,s}newMapUsersSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new S(this,e,{token:null==t?void 0:t.token,getToken:null==t?void 0:t.getToken,data:null==t?void 0:t.data,minResubscribeDelay:null==t?void 0:t.minResubscribeDelay,maxResubscribeDelay:null==t?void 0:t.maxResubscribeDelay,delta:null==t?void 0:t.delta,tagsFilter:null==t?void 0:t.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:null==t?void 0:t.pageSize,mapUnrecoverableStrategy:null==t?void 0:t.unrecoverableStrategy});return this._subs[e]=s,s}newSharedPollSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new w(this,e,{token:null==t?void 0:t.token,getToken:null==t?void 0:t.getToken,data:null==t?void 0:t.data,minResubscribeDelay:null==t?void 0:t.minResubscribeDelay,maxResubscribeDelay:null==t?void 0:t.maxResubscribeDelay,delta:null==t?void 0:t.delta,sharedPoll:!0,sharedPollGetSignature:null==t?void 0:t.getSignature});return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(t){t&&(t.state!==e.SubscriptionState.Unsubscribed&&t.unsubscribe(),this._removeSubscription(t))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[t,s]of Object.entries(this._subs))"map"===s.type&&(e[t]=s);return e}sharedPollSubscriptions(){const e={};for(const[t,s]of Object.entries(this._subs))"shared_poll"===s.type&&(e[t]=s);return e}ready(s){return t(this,void 0,void 0,(function*(){switch(this.state){case e.State.Disconnected:throw{code:e.errorCodes.clientDisconnected,message:"client disconnected"};case e.State.Connected:return;default:return new Promise(((t,n)=>{const i={resolve:t,reject:n};s&&(i.timeout=setTimeout((()=>{n({code:e.errorCodes.timeout,message:"timeout"})}),s)),this._promises[this._nextPromiseId()]=i}))}}))}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(e.disconnectedCodes.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(s){return t(this,void 0,void 0,(function*(){const t={send:{data:s}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(e.errorCodes.transportWriteError,"transport write error")}))}rpc(e,s){return t(this,void 0,void 0,(function*(){const t={rpc:{method:e,data:s}};yield this._methodCall();return{data:(yield this._callPromise(t,(e=>e.rpc))).data}}))}publish(e,s){return t(this,void 0,void 0,(function*(){const t={publish:{channel:e,data:s}};return yield this._methodCall(),yield this._callPromise(t,(()=>({}))),{}}))}mapPublish(e,s,n){return t(this,void 0,void 0,(function*(){const t={publish:{channel:e,type:1,key:s,data:n}};return yield this._methodCall(),yield this._callPromise(t,(()=>({}))),{}}))}mapRemove(e,s){return t(this,void 0,void 0,(function*(){const t={publish:{channel:e,type:1,key:s,removed:!0}};return yield this._methodCall(),yield this._callPromise(t,(()=>({}))),{}}))}history(e,s){return t(this,void 0,void 0,(function*(){const t={history:this._getHistoryRequest(e,s)};yield this._methodCall();const n=yield this._callPromise(t,(e=>e.history)),i=[];if(n.publications)for(let t=0;t<n.publications.length;t++)i.push(this._getPublicationContext(e,n.publications[t]));return{publications:i,epoch:n.epoch||"",offset:n.offset||0}}))}presence(e){return t(this,void 0,void 0,(function*(){const t={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(t,(e=>e.presence))).presence;for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){const t=s[e],n=t.conn_info,i=t.chan_info;n&&(t.connInfo=n),i&&(t.chanInfo=i)}return{clients:s}}))}presenceStats(e){return t(this,void 0,void 0,(function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const s=yield this._callPromise(t,(e=>e.presence_stats));return{numUsers:s.num_users,numClients:s.num_clients}}))}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then((function(){Promise.resolve().then((function(){e._batching=!1,e._flush()}))}))}_debug(...e){this._debugEnabled&&function(e,t){if(globalThis.console){const s=globalThis.console[e];b(s)&&s.apply(globalThis.console,t)}}("debug",e)}_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 D,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(!Array.isArray(this._endpoint))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 s=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(s)<0)throw new Error("unsupported transport name: "+s)}}}_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===e.State.Disconnected}_isConnecting(){return this.state===e.State.Connecting}_isConnected(){return this.state===e.State.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let t=null;null!==this._config.networkEventTarget?t=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(t=globalThis),t&&(t.addEventListener("offline",(()=>{this._debug("offline event triggered"),this.state!==e.State.Connected&&this.state!==e.State.Connecting||(this._disconnect(e.connectingCodes.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)})),t.addEventListener("online",(()=>{this._debug("online event triggered"),this.state===e.State.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())})),this._networkEventsSet=!0)}_getReconnectDelay(){const e=g(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const t in this._callbacks)if(this._callbacks.hasOwnProperty(t)){const s=this._callbacks[t];clearTimeout(s.timeout);const n=s.errback;if(!n)continue;n({error:this._createErrorObject(e.errorCodes.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const s=this._subs[t];s.state===e.SubscriptionState.Subscribed&&s._setSubscribing(e.subscribingCodes.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(t){for(const s of t){const t=s.id;if(!(t in this._callbacks))continue;const n=this._callbacks[t];clearTimeout(this._callbacks[t].timeout),delete this._callbacks[t];(0,n.errback)({error:this._createErrorObject(e.errorCodes.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 t;null!==this._config.websocket?t=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(t=globalThis.WebSocket);let s=null;null!==this._config.sockjs?s=this._config.sockjs:void 0!==globalThis.SockJS&&(s=globalThis.SockJS);let n=null;null!==this._config.eventsource?n=this._config.eventsource:void 0!==globalThis.EventSource&&(n=globalThis.EventSource);let i=null;null!==this._config.fetch?i=this._config.fetch:void 0!==globalThis.fetch&&(i=globalThis.fetch);let r=null;if(null!==this._config.readableStream?r=this._config.readableStream:void 0!==globalThis.ReadableStream&&(r=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let e=0;for(;;){if(e>=this._transports.length)throw new Error("no supported transport found");const o=this._transports[this._currentTransportIndex],a=o.transport,c=o.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new P(c,{websocket:t}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,e++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new C(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,e++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new E(c,{fetch:i,readableStream:r,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,e++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new k(c,{eventsource:n,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,e++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new T(c,{sockjs:s,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,e++;continue}}break}}else{if(o=this._endpoint,a="http",0===o.lastIndexOf(a,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 P(this._endpoint,{websocket:t}),!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 o,a;const c=this,h=this._transport,u=this._nextTransportId();c._debug("id of transport",u);let l=!1;const d=[];if(this._transport.emulation()){const e=c._sendConnect(!0);d.push(e)}this._setNetworkEvents();const _=this._codec.encodeCommands(d);let f;this._transportClosed=!1,f=setTimeout((function(){h.close()}),this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(f&&(clearTimeout(f),f=null),c._transportId!=u)return c._debug("open callback from non-actual transport"),void h.close();l=!0,c._debug(h.subName(),"transport open"),h.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==u?c._debug("transport level error",e):c._debug("error callback from non-actual transport")},onClose:function(t){if(f&&(clearTimeout(f),f=null),c._transportId!=u)return void c._debug("close callback from non-actual transport");c._debug(h.subName(),"transport closed"),c._transportClosed=!0,c._transportIsOpen=!1;let s="connection closed",n=!0,i=0;if(t&&"code"in t&&t.code&&(i=t.code),t&&t.reason)try{const e=JSON.parse(t.reason);s=e.reason,n=e.reconnect}catch(e){s=t.reason,(i>=3500&&i<4e3||i>=4500&&i<5e3)&&(n=!1)}i<3e3?(1009===i?(i=e.disconnectedCodes.messageSizeLimit,s="message size limit exceeded",n=!1):(i=e.connectingCodes.transportClosed,s="transport closed"),c._emulation&&!c._transportWasOpen&&(c._currentTransportIndex++,c._currentTransportIndex>=c._transports.length&&(c._triedAllTransports=!0,c._currentTransportIndex=0))):c._transportWasOpen=!0,c._isConnecting()&&!l&&c.emit("error",{type:"transport",error:{code:e.errorCodes.transportClosed,message:"transport closed"},transport:h.name()}),c._reconnecting=!1,c._disconnect(i,s,n)},onMessage:function(e){c._dataReceived(e)}},_),c.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),s=this;return this._call(t,e).then((e=>{const t=e.reply.connect;s._connectResponse(t),e.next&&e.next()}),(e=>{s._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 t=""===this._token;if(!(this._refreshRequired||t&&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 s=this;this._getToken().then((function(e){s._isConnecting()&&(null!=e&&null!=e?(s._token=e,s._debug("connection token refreshed"),s._config.getData?s._config.getData().then((function(e){s._isConnecting()&&(s._data=e,s._initializeTransport())})).catch((e=>s._handleGetDataError(e))):s._initializeTransport()):s._failUnauthorized())})).catch((function(t){if(!s._isConnecting())return;if(t instanceof A)return void s._failUnauthorized();s.emit("error",{type:"connectToken",error:{code:e.errorCodes.clientConnectToken,message:void 0!==t?t.toString():""}});const n=s._getReconnectDelay();s._debug("error on getting connection token, reconnect after "+n+" milliseconds",t),s._reconnecting=!1,s._reconnectTimeout=setTimeout((()=>{s._startReconnecting()}),n)}))}_handleGetDataError(t){if(t instanceof A)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:e.errorCodes.badConfiguration,message:(null==t?void 0:t.toString())||""}});const s=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+s+" milliseconds",t),this._reconnecting=!1,this._reconnectTimeout=setTimeout((()=>{this._startReconnecting()}),s)}_connectError(t){this.state===e.State.Connecting&&(109===t.code&&(this._refreshRequired=!0),t.code<100||!0===t.temporary||109===t.code?(this.emit("error",{type:"connect",error:t}),this._debug("closing transport due to connect error"),this._disconnect(t.code,t.message,!0)):this._disconnect(t.code,t.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 s=!1;for(const e in this._serverSubs)if(this._serverSubs.hasOwnProperty(e)&&this._serverSubs[e].recoverable){s=!0;const n={recover:!0};this._serverSubs[e].offset&&(n.offset=this._serverSubs[e].offset),this._serverSubs[e].epoch&&(n.epoch=this._serverSubs[e].epoch),t[e]=n}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const s={channel:e};return void 0!==t&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),void 0!==t.limit&&(s.limit=t.limit),!0===t.reverse&&(s.reverse=!0)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise(((t,s)=>{const n=setTimeout((function(){s({code:e.errorCodes.timeout,message:"timeout"})}),this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:t,reject:s}}))}_callPromise(e,t){return new Promise(((s,n)=>{this._call(e,!1).then((e=>{var n;const i=t(e.reply);s(i),null===(n=e.next)||void 0===n||n.call(e)}),(e=>{var t;n(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 s=Promise.resolve();for(const t in e)e.hasOwnProperty(t)&&(s=s.then((()=>this._dispatchReply(e[t]))));s=s.then((()=>{t()}))}_dispatchReply(e){let t;const s=new Promise((e=>{t=e}));if(null==e)return this._debug("dispatch: got undefined or null reply"),t(),s;const n=e.id;return n&&n>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise(((s,n)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,n),t||this._addCommand(e)}))}_startConnecting(){this._debug("start connecting"),this._setState(e.State.Connecting)&&this.emit("connecting",{code:e.connectingCodes.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(t,s,n){if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const r={code:t,reason:s};let o=!1;if(n?o=this._setState(e.State.Connecting):(o=this._setState(e.State.Disconnected),this._rejectPromises({code:e.errorCodes.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===e.State.Connecting&&this._clearReconnectTimeout(),i===e.State.Connected&&this._clearConnectedState(),o&&(this._isConnecting()?this.emit("connecting",r):this.emit("disconnected",r)),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(e.disconnectedCodes.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:e.errorCodes.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new A("")))}_refresh(){const t=this._client,s=this;this._getToken().then((function(e){if(t!==s._client)return;if(!e)return void s._failUnauthorized();if(s._token=e,s._debug("connection token refreshed"),!s._isConnected())return;const n={refresh:{token:s._token}};s._call(n,!1).then((e=>{const t=e.reply.refresh;s._refreshResponse(t),e.next&&e.next()}),(e=>{s._refreshError(e.error),e.next&&e.next()}))})).catch((function(t){s._isConnected()&&(t instanceof A?s._failUnauthorized():(s.emit("error",{type:"refreshToken",error:{code:e.errorCodes.clientRefreshToken,message:void 0!==t?t.toString():""}}),s._refreshTimeout=setTimeout((()=>s._refresh()),s._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 g(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout((()=>this._refresh()),m(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(t){if(!this._transportIsOpen)return Promise.resolve();const s={unsubscribe:{channel:t.channel}},n=this;return new Promise(((t,i)=>{this._call(s,!1).then((e=>{t(),e.next&&e.next()}),(s=>{t(),s.next&&s.next(),n._disconnect(e.connectingCodes.unsubscribeError,"unsubscribe error",!0)}))}))}_getSub(e,t){if(t&&t>0){for(const e in this._subs)if(this._subs.hasOwnProperty(e)){const s=this._subs[e];if(s._id===t)return s}return null}const s=this._subs[e];return s||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){const t=[];for(const s in this._subs){if(!this._subs.hasOwnProperty(s))continue;const n=this._subs[s];if(!0!==n._inflight&&n.state===e.SubscriptionState.Subscribing){const e=n._subscribe();e&&t.push(e)}}return t}_connectResponse(t){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=t.client,this._setState(e.State.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),t.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),m(t.ttl))),this._session=t.session,this._node=t.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const s={client:t.client,transport:this._transport.subName()};t.data&&(s.data=t.data),this.emit("connected",s),this._resolvePromises(),this._processServerSubs(t.subs||{}),t.ping&&t.ping>0?(this._serverPing=1e3*t.ping,this._sendPong=!0===t.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||!1};const n=this._getSubscribeContext(t,s);this.emit("subscribed",n)}for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];if(s.recovered){const e=s.publications;if(e&&e.length>0)for(const s in e)e.hasOwnProperty(s)&&this._handlePublication(t,e[s])}}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(e.connectingCodes.noPing,"no ping",!0)}),this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const s={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(s.recovered=!0),t.positioned&&(s.positioned=!0),t.recoverable&&(s.recoverable=!0),t.was_recovering&&(s.wasRecovering=!0);let n="";"epoch"in t&&(n=t.epoch);let i=0;return"offset"in t&&(i=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:i,epoch:n}),Array.isArray(t.publications)&&t.publications.length>0&&(s.hasRecoveredPublications=!0),t.data&&(s.data=t.data),s}_handleReply(e,t){const s=e.id;if(!(s in this._callbacks))return void t();const n=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],"error"in(i=e)&&null!==i.error){const s=n.errback;if(!s)return void t();s({error:{code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1},next:t})}else{const s=n.callback;if(!s)return;s({reply:e,next:t})}var i}_handleJoin(e,t,s){const n=this._getSub(e,s);if(n||!e)n._handleJoin(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",s)}}_handleLeave(e,t,s){const n=this._getSub(e,s);if(n||!e)n._handleLeave(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",s)}}_handleUnsubscribe(e,t){const s=this._getSub(e,0);s||!e?t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):(2502===t.code&&s._invalidateState(),s._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 s=!0;if((t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),3014===t){this._token="",this._refreshRequired=!0;for(const e in this._subs)this._subs.hasOwnProperty(e)&&this._subs[e]._invalidateState()}this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){const s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);const n=e.chan_info;return n&&(t.chanInfo=n),t}_handlePublication(e,t,s){const n=this._getSub(e,s);if(n||!e)n._handlePublication(t);else if(this._isServerSub(e)){const s=this._getPublicationContext(e,t);this.emit("publication",s),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 s=e.channel,n=e.id;e.pub?this._handlePublication(s,e.pub,n):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join,n):e.leave?this._handleLeave(s,e.leave,n):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){const n={code:e,message:t};return s&&(n.temporary=!0),n}_registerCall(t,s,n){this._callbacks[t]={callback:s,errback:n,timeout:null},this._callbacks[t].timeout=setTimeout((()=>{delete this._callbacks[t],b(n)&&n({error:this._createErrorObject(e.errorCodes.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])}}L.SubscriptionState=e.SubscriptionState,L.State=e.State,L.UnauthorizedError=A,e.Centrifuge=L,e.Subscription=y,e.UnauthorizedError=A}(P);var E={},k={};Object.defineProperty(k,"__esModule",{value:!0}),k.default="ffffffff-ffff-ffff-ffff-ffffffffffff";var C={};Object.defineProperty(C,"__esModule",{value:!0}),C.default="00000000-0000-0000-0000-000000000000";var R={},O={},I={};Object.defineProperty(I,"__esModule",{value:!0}),I.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,Object.defineProperty(O,"__esModule",{value:!0});const x=I;O.default=function(e){return"string"==typeof e&&x.default.test(e)},Object.defineProperty(R,"__esModule",{value:!0});const D=O;R.default=function(e){if(!(0,D.default)(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 N={};Object.defineProperty(N,"__esModule",{value:!0}),N.unsafeStringify=void 0;const A=O,L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));function U(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}N.unsafeStringify=U,N.default=function(e,t=0){const s=U(e,t);if(!(0,A.default)(s))throw TypeError("Stringified UUID is invalid");return s};var M={},j={};let F;Object.defineProperty(j,"__esModule",{value:!0});const B=new Uint8Array(16);j.default=function(){if(!F){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");F=crypto.getRandomValues.bind(crypto)}return F(B)},Object.defineProperty(M,"__esModule",{value:!0}),M.updateV1State=void 0;const q=j,z=N,V={};function K(e,t,s){return e.msecs??=-1/0,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=s.slice(10,16),e.node[0]|=1,e.clockseq=16383&(s[8]<<8|s[9])),e.msecs=t,e}function W(e,t,s,n,i,r,o=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 ${o}:${o+15} is out of buffer bounds`)}else r=new Uint8Array(16),o=0;t??=Date.now(),s??=0,n??=16383&(e[8]<<8|e[9]),i??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+s)%4294967296;r[o++]=a>>>24&255,r[o++]=a>>>16&255,r[o++]=a>>>8&255,r[o++]=255&a;const c=t/4294967296*1e4&268435455;r[o++]=c>>>8&255,r[o++]=255&c,r[o++]=c>>>24&15|16,r[o++]=c>>>16&255,r[o++]=n>>>8|128,r[o++]=255&n;for(let e=0;e<6;++e)r[o++]=i[e];return r}M.updateV1State=K,M.default=function(e,t,s){let n;const i=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)n=W(e.random??e.rng?.()??(0,q.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,s);else{const e=Date.now(),r=(0,q.default)();K(V,e,r),n=W(r,V.msecs,V.nsecs,i?void 0:V.clockseq,i?void 0:V.node,t,s)}return t??(0,z.unsafeStringify)(n)};var $={};Object.defineProperty($,"__esModule",{value:!0});const G=R,J=N;$.default=function(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?(0,G.default)(e):e);return"string"==typeof e?(0,J.unsafeStringify)(t):t};var Y={},H={};function Q(e){return 14+(e+64>>>9<<4)+1}function X(e,t){const s=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(s>>16)<<16|65535&s}function Z(e,t,s,n,i,r){return X((o=X(X(t,e),X(n,r)))<<(a=i)|o>>>32-a,s);var o,a}function ee(e,t,s,n,i,r,o){return Z(t&s|~t&n,e,t,i,r,o)}function te(e,t,s,n,i,r,o){return Z(t&n|s&~n,e,t,i,r,o)}function se(e,t,s,n,i,r,o){return Z(t^s^n,e,t,i,r,o)}function ne(e,t,s,n,i,r,o){return Z(s^(t|~n),e,t,i,r,o)}Object.defineProperty(H,"__esModule",{value:!0}),H.default=function(e){return function(e){const t=new Uint8Array(4*e.length);for(let s=0;s<4*e.length;s++)t[s]=e[s>>2]>>>s%4*8&255;return t}(function(e,t){const s=new Uint32Array(Q(t)).fill(0);s.set(e),s[t>>5]|=128<<t%32,s[s.length-1]=t,e=s;let n=1732584193,i=-271733879,r=-1732584194,o=271733878;for(let t=0;t<e.length;t+=16){const s=n,a=i,c=r,h=o;n=ee(n,i,r,o,e[t],7,-680876936),o=ee(o,n,i,r,e[t+1],12,-389564586),r=ee(r,o,n,i,e[t+2],17,606105819),i=ee(i,r,o,n,e[t+3],22,-1044525330),n=ee(n,i,r,o,e[t+4],7,-176418897),o=ee(o,n,i,r,e[t+5],12,1200080426),r=ee(r,o,n,i,e[t+6],17,-1473231341),i=ee(i,r,o,n,e[t+7],22,-45705983),n=ee(n,i,r,o,e[t+8],7,1770035416),o=ee(o,n,i,r,e[t+9],12,-1958414417),r=ee(r,o,n,i,e[t+10],17,-42063),i=ee(i,r,o,n,e[t+11],22,-1990404162),n=ee(n,i,r,o,e[t+12],7,1804603682),o=ee(o,n,i,r,e[t+13],12,-40341101),r=ee(r,o,n,i,e[t+14],17,-1502002290),i=ee(i,r,o,n,e[t+15],22,1236535329),n=te(n,i,r,o,e[t+1],5,-165796510),o=te(o,n,i,r,e[t+6],9,-1069501632),r=te(r,o,n,i,e[t+11],14,643717713),i=te(i,r,o,n,e[t],20,-373897302),n=te(n,i,r,o,e[t+5],5,-701558691),o=te(o,n,i,r,e[t+10],9,38016083),r=te(r,o,n,i,e[t+15],14,-660478335),i=te(i,r,o,n,e[t+4],20,-405537848),n=te(n,i,r,o,e[t+9],5,568446438),o=te(o,n,i,r,e[t+14],9,-1019803690),r=te(r,o,n,i,e[t+3],14,-187363961),i=te(i,r,o,n,e[t+8],20,1163531501),n=te(n,i,r,o,e[t+13],5,-1444681467),o=te(o,n,i,r,e[t+2],9,-51403784),r=te(r,o,n,i,e[t+7],14,1735328473),i=te(i,r,o,n,e[t+12],20,-1926607734),n=se(n,i,r,o,e[t+5],4,-378558),o=se(o,n,i,r,e[t+8],11,-2022574463),r=se(r,o,n,i,e[t+11],16,1839030562),i=se(i,r,o,n,e[t+14],23,-35309556),n=se(n,i,r,o,e[t+1],4,-1530992060),o=se(o,n,i,r,e[t+4],11,1272893353),r=se(r,o,n,i,e[t+7],16,-155497632),i=se(i,r,o,n,e[t+10],23,-1094730640),n=se(n,i,r,o,e[t+13],4,681279174),o=se(o,n,i,r,e[t],11,-358537222),r=se(r,o,n,i,e[t+3],16,-722521979),i=se(i,r,o,n,e[t+6],23,76029189),n=se(n,i,r,o,e[t+9],4,-640364487),o=se(o,n,i,r,e[t+12],11,-421815835),r=se(r,o,n,i,e[t+15],16,530742520),i=se(i,r,o,n,e[t+2],23,-995338651),n=ne(n,i,r,o,e[t],6,-198630844),o=ne(o,n,i,r,e[t+7],10,1126891415),r=ne(r,o,n,i,e[t+14],15,-1416354905),i=ne(i,r,o,n,e[t+5],21,-57434055),n=ne(n,i,r,o,e[t+12],6,1700485571),o=ne(o,n,i,r,e[t+3],10,-1894986606),r=ne(r,o,n,i,e[t+10],15,-1051523),i=ne(i,r,o,n,e[t+1],21,-2054922799),n=ne(n,i,r,o,e[t+8],6,1873313359),o=ne(o,n,i,r,e[t+15],10,-30611744),r=ne(r,o,n,i,e[t+6],15,-1560198380),i=ne(i,r,o,n,e[t+13],21,1309151649),n=ne(n,i,r,o,e[t+4],6,-145523070),o=ne(o,n,i,r,e[t+11],10,-1120210379),r=ne(r,o,n,i,e[t+2],15,718787259),i=ne(i,r,o,n,e[t+9],21,-343485551),n=X(n,s),i=X(i,a),r=X(r,c),o=X(o,h)}return Uint32Array.of(n,i,r,o)}(function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(Q(8*e.length)).fill(0);for(let s=0;s<e.length;s++)t[s>>2]|=(255&e[s])<<s%4*8;return t}(e),8*e.length))};var ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.URL=ie.DNS=ie.stringToBytes=void 0;const re=R,oe=N;function ae(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let s=0;s<e.length;++s)t[s]=e.charCodeAt(s);return t}ie.stringToBytes=ae,ie.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ie.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",ie.default=function(e,t,s,n,i,r){const o="string"==typeof s?ae(s):s,a="string"==typeof n?(0,re.default)(n):n;if("string"==typeof n&&(n=(0,re.default)(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(a),c.set(o,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,i){if((r=r||0)<0||r+16>i.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[r+e]=c[e];return i}return(0,oe.unsafeStringify)(c)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=H,s=ie;var n=ie;function i(e,n,i,r){return(0,s.default)(48,t.default,e,n,i,r)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=s.DNS,i.URL=s.URL,e.default=i}(Y);var ce={},he={};Object.defineProperty(he,"__esModule",{value:!0});const ue="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);he.default={randomUUID:ue},Object.defineProperty(ce,"__esModule",{value:!0});const le=he,de=j,_e=N;ce.default=function(e,t,s){if(le.default.randomUUID&&!t&&!e)return le.default.randomUUID();const n=(e=e||{}).random??e.rng?.()??(0,de.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((s=s||0)<0||s+16>t.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[s+e]=n[e];return t}return(0,_e.unsafeStringify)(n)};var fe={},pe={};function be(e,t,s,n){switch(e){case 0:return t&s^~t&n;case 1:case 3:return t^s^n;case 2:return t&s^t&n^s&n}}function ge(e,t){return e<<t|e>>>32-t}Object.defineProperty(pe,"__esModule",{value:!0}),pe.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],s=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const i=(e=n).length/4+2,r=Math.ceil(i/16),o=new Array(r);for(let t=0;t<r;++t){const s=new Uint32Array(16);for(let n=0;n<16;++n)s[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];o[t]=s}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 e=0;e<r;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=o[e][t];for(let e=16;e<80;++e)n[e]=ge(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let i=s[0],r=s[1],a=s[2],c=s[3],h=s[4];for(let e=0;e<80;++e){const s=Math.floor(e/20),o=ge(i,5)+be(s,r,a,c)+h+t[s]+n[e]>>>0;h=c,c=a,a=ge(r,30)>>>0,r=i,i=o}s[0]=s[0]+i>>>0,s[1]=s[1]+r>>>0,s[2]=s[2]+a>>>0,s[3]=s[3]+c>>>0,s[4]=s[4]+h>>>0}return Uint8Array.of(s[0]>>24,s[0]>>16,s[0]>>8,s[0],s[1]>>24,s[1]>>16,s[1]>>8,s[1],s[2]>>24,s[2]>>16,s[2]>>8,s[2],s[3]>>24,s[3]>>16,s[3]>>8,s[3],s[4]>>24,s[4]>>16,s[4]>>8,s[4])},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=pe,s=ie;var n=ie;function i(e,n,i,r){return(0,s.default)(80,t.default,e,n,i,r)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=s.DNS,i.URL=s.URL,e.default=i}(fe);var me={};Object.defineProperty(me,"__esModule",{value:!0});const ve=N,ye=M,Se=$;me.default=function(e,t,s){e??={},s??=0;let n=(0,ye.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,Se.default)(n),t){if(s<0||s+16>t.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let e=0;e<16;e++)t[s+e]=n[e];return t}return(0,ve.unsafeStringify)(n)};var we={};Object.defineProperty(we,"__esModule",{value:!0});const Te=R,Pe=N;we.default=function(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?(0,Te.default)(e):e);return"string"==typeof e?(0,Pe.unsafeStringify)(t):t};var Ee={};Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.updateV7State=void 0;const ke=j,Ce=N,Re={};function Oe(e,t,s){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function Ie(e,t,s,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),s??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|s>>>28&15,n[i++]=s>>>20&255,n[i++]=128|s>>>14&63,n[i++]=s>>>6&255,n[i++]=s<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}Ee.updateV7State=Oe,Ee.default=function(e,t,s){let n;if(e)n=Ie(e.random??e.rng?.()??(0,ke.default)(),e.msecs,e.seq,t,s);else{const e=Date.now(),i=(0,ke.default)();Oe(Re,e,i),n=Ie(i,Re.msecs,Re.seq,t,s)}return t??(0,Ce.unsafeStringify)(n)};var xe={};Object.defineProperty(xe,"__esModule",{value:!0});const De=O;function Ne(e){let t,s=e[0],n=1;for(;n<e.length;){const i=e[n],r=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==s)return;"access"===i||"optionalAccess"===i?(t=s,s=r(s)):"call"!==i&&"optionalCall"!==i||(s=r(((...e)=>s.call(t,...e))),t=void 0)}return s}var Ae,Le,Ue,Me,je;xe.default=function(e){if(!(0,De.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=k;Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var s=C;Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return s.default}});var n=R;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return n.default}});var i=N;Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var r=M;Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return r.default}});var o=$;Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var a=Y;Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return a.default}});var c=ce;Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var h=fe;Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return h.default}});var u=me;Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return u.default}});var l=we;Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return l.default}});var d=Ee;Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return d.default}});var _=O;Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return _.default}});var f=xe;Object.defineProperty(e,"version",{enumerable:!0,get:function(){return f.default}})}(E),Object.defineProperty(i,"__esModule",{value:!0});var Fe,Be=e.eventemitter3.exports,qe=(Fe=Be)&&Fe.__esModule?Fe:{default:Fe},ze=(e=>(e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.CONNECTED="CONNECTED",e))(ze||{}),Ve=(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))(Ve||{}),Ke=class extends Error{constructor(e,t){super(t||e),this.code=e,this.name=e}},We=class extends Ke{},$e=class extends Ke{},Ge=class extends Ke{},Je=Ae=class extends qe.default{__init(){this.session=null}__init2(){this._state="DISCONNECTED"}on(e,t){return super.on(e,t)}constructor(e,t,s){super(),Ae.prototype.__init.call(this),Ae.prototype.__init2.call(this),this.transport=e,this.keymanager=t,this.sessionstore=s,this.transport.on("error",(e=>this.emit("error",e))),this.transport.on("message",(async e=>{if(!Ne([this,"access",e=>e.session,"optionalAccess",e=>e.keyPair,"access",e=>e.privateKey]))return;if(await this.checkSessionExpiry())return void this.emit("error",new We("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 $e("TRANSPORT_RECONNECT_FAILED","Failed to reconnect")}}async resume(e){if("DISCONNECTED"!==this.state)throw new We("SESSION_INVALID_STATE",`Cannot resume when state is ${this.state}`);this.state="CONNECTING";try{const t=await this.sessionstore.get(e);if(!t)throw new We("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(e){throw this.state="DISCONNECTED",this.session=null,e}}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 We("SESSION_INVALID_STATE","Cannot send message: session is not initialized.");if(await this.checkSessionExpiry())throw new We("SESSION_EXPIRED","Session expired");const s=JSON.stringify(t),n=await this.keymanager.encrypt(s,this.session.theirPublicKey);if(!await this.transport.publish(e,n))throw new $e("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(!Ne([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(e){const t=e instanceof Error?e.message:String(e);return this.emit("error",new Ge("DECRYPTION_FAILED",`Decryption failed: ${t}`)),null}}},Ye=["trusted","untrusted"];var He=r,Qe=((Le=class e{static __initStatic(){this.SESSION_PREFIX="session:"}static __initStatic2(){this.MASTER_LIST_KEY="sessions:master-list"}__init3(){this.mutex=new He.Mutex}static async create(t){const s=new e(t);return await s.garbageCollect(),s}constructor(e){Le.prototype.__init3.call(this),this.kvstore=e}async set(e){if(Number.isNaN(e.expiresAt)||e.expiresAt<Date.now())throw new We("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},s=this.getSessionKey(e.id);await this.kvstore.set(s,JSON.stringify(t)),await this.addToMasterList(e.id)}async get(e){const t=this.getSessionKey(e),s=await this.kvstore.get(t);if(!s)return null;try{const t=JSON.parse(s);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(t){return await this.delete(e),null}}async list(){const e=await this.getMasterList(),t=[];for(const s of e){const e=await this.get(s);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`${e.SESSION_PREFIX}${t}`}async getMasterList(){const t=await this.kvstore.get(e.MASTER_LIST_KEY);if(!t)return[];try{return JSON.parse(t)}catch(e){return[]}}async addToMasterList(t){await this.mutex.runExclusive((async()=>{const s=await this.getMasterList();s.includes(t)||(s.push(t),await this.kvstore.set(e.MASTER_LIST_KEY,JSON.stringify(s)))}))}async removeFromMasterList(t){await this.mutex.runExclusive((async()=>{const s=(await this.getMasterList()).filter((e=>e!==t));await this.kvstore.set(e.MASTER_LIST_KEY,JSON.stringify(s))}))}}).__initStatic(),Le.__initStatic2(),Le),Xe=P,Ze=e=>new Promise((t=>setTimeout(t,e)));var et=Ue=class{constructor(e,t){Ue.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}},tt=((Me=class e extends qe.default{static __initStatic3(){this.contexts=new Map}__init5(){this.channels=new Set}__init6(){this.disconnected=!1}__init7(){this.eventListeners=new Map}constructor(t,s={}){if(super(),Me.prototype.__init5.call(this),Me.prototype.__init6.call(this),Me.prototype.__init7.call(this),this.url=t,e.contexts.has(t)){const n=e.contexts.get(t);if(!n)throw new Error("No context found");this.validateOptions(n.options,s)}else{const n=new Xe.Centrifuge(t,s);e.contexts.set(t,{refcount:0,options:s,centrifuge:n,subscriptions:new Map,reconnectPromise:null})}const n=e.contexts.get(t);if(!n)throw new Error("No context found");n.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((s=>{t.centrifuge.once("disconnected",(()=>{e.contexts.delete(this.url),s()})),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,s)=>{t.centrifuge.once("connected",(()=>e())),t.centrifuge.once("error",(e=>s(e.error))),t.centrifuge.connect()}))}finally{t.reconnectPromise=null}})()),t.reconnectPromise):Promise.resolve()}newSubscription(t,s={}){const n=e.contexts.get(this.url);if(!n)throw new Error("No context found");const i=n.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 ${t}`);e.count++}else{const e=n.centrifuge.newSubscription(t,s);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 ${t}`);return new et(r.sub,this)}getSubscription(t){if(!this.channels.has(t))return;const s=e.contexts.get(this.url);if(!s)return;const n=s.subscriptions.get(t);return n?new et(n.sub,this):void 0}async publish(t,s){const n=e.contexts.get(this.url);n&&await n.centrifuge.publish(t,s)}subscriptions(){const t=e.contexts.get(this.url);if(!t)return{};const s={};for(const e of this.channels){const n=t.subscriptions.get(e);n&&(s[e]=new et(n.sub,this))}return s}get real(){return Ne([e.contexts.get(this.url),"optionalAccess",e=>e.centrifuge])}get state(){if(this.disconnected)return"disconnected";const t=e.contexts.get(this.url);return s=Ne([t,"optionalAccess",e=>e.centrifuge,"access",e=>e.state]),n=()=>"disconnected",null!=s?s:n();var s,n}attachEventListeners(){if(this.eventListeners.size>0)return;const t=e.contexts.get(this.url);if(!t)return;["connecting","connected","disconnected","error"].forEach((e=>{const s=t=>{this.disconnected||this.emit(e,t)};this.eventListeners.set(e,s),t.centrifuge.on(e,s)}))}decrementChannelRef(t){const s=e.contexts.get(this.url);if(!s)return;const n=s.subscriptions,i=n.get(t);i&&(i.count--,0===i.count&&(i.sub.unsubscribe(),s.centrifuge.removeSubscription(i.sub),n.delete(t)))}detachEventListeners(){const t=e.contexts.get(this.url);if(t){for(const[e,s]of this.eventListeners)t.centrifuge.off(e,s);this.eventListeners.clear()}}validateOptions(e,t){const s=["token","websocket","minReconnectDelay","maxReconnectDelay"];for(const n of s){const s=e[n],i=t[n];void 0!==s&&void 0!==i&&s!==i&&console.warn(`SharedCentrifuge: Option '${n}' mismatch for URL ${this.url}. Using existing value: ${s}, ignoring new value: ${i}`)}}removeSubscription(e){e&&"channel"in e&&(this.decrementChannelRef(e.channel),this.channels.delete(e.channel))}}).__initStatic3(),Me),st=E,nt=class e{static async create(t){const s=e.getClientIdKey();let n=await t.get(s);return n||(n=st.v4.call(void 0),await t.set(s,n)),new e(t,n)}constructor(e,t){this.kvstore=e,this.clientId=t}getClientId(){return this.clientId}async getNextNonce(e){const t=this.getNonceKey(e),s=await this.kvstore.get(t),n=(s?parseInt(s,10):0)+1;return await this.kvstore.set(t,n.toString()),n}async getLatestNonces(e){const t=this.getLatestNoncesKey(e),s=await this.kvstore.get(t);if(s){const e=JSON.parse(s);return new Map(Object.entries(e))}return new Map}async setLatestNonces(e,t){const s=this.getLatestNoncesKey(e),n=Object.fromEntries(t);await this.kvstore.set(s,JSON.stringify(n))}async clear(e){const t=this.getNonceKey(e),s=this.getLatestNoncesKey(e);await Promise.all([this.kvstore.delete(t),this.kvstore.delete(s)])}static getClientIdKey(){return"websocket-transport-client-id"}getNonceKey(e){return`nonce:${this.clientId}:${e}`}getLatestNoncesKey(e){return`latest-nonces:${this.clientId}:${e}`}},it=je=class e extends qe.default{__init8(){this.queue=[]}__init9(){this.isProcessingQueue=!1}__init10(){this.state="disconnected"}static async create(t){const s=await nt.create(t.kvstore);return new e(s,t)}constructor(e,t){super(),je.prototype.__init8.call(this),je.prototype.__init9.call(this),je.prototype.__init10.call(this),this.storage=e;const s={minReconnectDelay:100,maxReconnectDelay:3e4};void 0!==t.websocket&&(s.websocket=t.websocket),this.centrifuge=t.useSharedConnection?new tt(t.url,s):new Xe.Centrifuge(t.url,s),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 $e("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 e of Object.values(t))this.centrifuge.removeSubscription(e);this.centrifuge.once("disconnected",(()=>e())),this.centrifuge.disconnect()}))}reconnect(){return this.centrifuge instanceof tt&&"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 $e("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 s=t;t.on("subscribed",(()=>{this._fetchHistory(s,e),this._processQueue()})),t.on("publication",(t=>{this._handleIncomingMessage(e,t.data)})),t.on("error",(e=>this.emit("error",new $e("TRANSPORT_SUBSCRIBE_FAILED",`Subscription error: ${e.error.message}`))))}if("subscribed"===t.state)return Promise.resolve();const s=t;return new Promise((e=>{s.once("subscribed",(()=>e())),s.subscribe()}))}publish(e,t){const s=new Promise(((s,n)=>{this.queue.push({channel:e,payload:t,resolve:s,reject:n})}));return this._processQueue(),s}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 s=JSON.parse(t);if("string"!=typeof s.clientId||"number"!=typeof s.nonce||"string"!=typeof s.payload)throw new $e("TRANSPORT_PARSE_FAILED","Invalid message format");if(s.clientId===this.storage.getClientId())return;const n=await this.storage.getLatestNonces(e),i=n.get(s.clientId)||0;s.nonce>i&&(n.set(s.clientId,s.nonce),await this.storage.setLatestNonces(e,n),this.emit("message",{channel:e,data:s.payload}))}catch(e){this.emit("error",new $e("TRANSPORT_PARSE_FAILED",`Failed to parse incoming message: ${e instanceof Error?e.message:"Unknown error"}`))}}async _fetchHistory(e,t){try{const s=await e.history({limit:50});for(const e of s.publications)await this._handleIncomingMessage(t,e.data)}catch(e){if(11===Ne([e,"optionalAccess",e=>e.code]))return;this.emit("error",new $e("TRANSPORT_HISTORY_FAILED",`Failed to fetch history for channel ${t}: ${JSON.stringify(e)}`))}}async _process(e){const t={clientId:this.storage.getClientId(),nonce:await this.storage.getNextNonce(e.channel),payload:e.payload},s=JSON.stringify(t);return async function(e,t){for(let s=0;s<t.attempts;s++)try{return await e()}catch(e){if(s===t.attempts-1)throw e;const n=t.delay*2**s;await Ze(n)}throw new Ke("UNKNOWN","Retry logic failed unexpectedly.")}((async()=>{await this.centrifuge.publish(e.channel,s)}),{attempts:5,delay:100})}async _processQueue(){if(!this.isProcessingQueue&&"connected"===this.state){this.isProcessingQueue=!0;try{for(;this.queue.length>0;){const e=this.queue[0];try{await this._process(e),this.queue.shift(),e.resolve(!0)}catch(t){this.queue.shift(),e.reject(t instanceof Error?t:new $e("TRANSPORT_PUBLISH_FAILED","Failed to publish message after all retries"))}}}finally{this.isProcessingQueue=!1}}}};var rt=i.BaseClient=Je,ot=i.CONNECTION_MODES=Ye,at=i.ClientState=ze,ct=i.CryptoError=Ge,ht=i.DEFAULT_SESSION_TTL=2592e6,ut=i.ErrorCode=Ve,lt=i.ProtocolError=Ke,dt=i.SessionError=We,_t=i.SessionStore=Qe,ft=i.TransportError=$e,pt=i.WebSocketTransport=it,bt=i.isValidConnectionMode=function(e){return"string"==typeof e&&Ye.includes(e)},gt=i.timingSafeEqual=function(e,t){if(e.length!==t.length)return!1;let s=0;for(let n=0;n<e.length;n++)s|=e.charCodeAt(n)^t.charCodeAt(n);return 0===s},mt=s({__proto__:null,BaseClient:rt,CONNECTION_MODES:ot,ClientState:at,CryptoError:ct,DEFAULT_SESSION_TTL:ht,ErrorCode:ut,ProtocolError:lt,SessionError:dt,SessionStore:_t,TransportError:ft,WebSocketTransport:pt,isValidConnectionMode:bt,timingSafeEqual:gt,default:i},[i]);exports.BaseClient_1=rt,exports.ClientState_1=at,exports.DEFAULT_SESSION_TTL_1=ht,exports.ErrorCode_1=ut,exports.SessionError_1=dt,exports.index=mt,exports.isValidConnectionMode_1=bt,exports.timingSafeEqual_1=gt;