centrifuge
Version:
JavaScript client SDK for bidirectional communication with Centrifugo and Centrifuge-based server from browser, NodeJS and React Native
9 lines • 77.2 kB
JavaScript
"use strict";(()=>{var he=Object.create;var G=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var fe=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var _e=(o,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of ue(n))!pe.call(o,s)&&s!==e&&G(o,s,{get:()=>n[s],enumerable:!(t=le(n,s))||t.enumerable});return o};var V=(o,n,e)=>(e=o!=null?he(de(o)):{},_e(n||!o||!o.__esModule?G(e,"default",{value:o,enumerable:!0}):e,o));var F=fe((De,N)=>{"use strict";var T=typeof Reflect=="object"?Reflect:null,J=T&&typeof T.apply=="function"?T.apply:function(n,e,t){return Function.prototype.apply.call(n,e,t)},E;T&&typeof T.ownKeys=="function"?E=T.ownKeys:Object.getOwnPropertySymbols?E=function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:E=function(n){return Object.getOwnPropertyNames(n)};function be(o){console&&console.warn&&console.warn(o)}var K=Number.isNaN||function(n){return n!==n};function d(){d.init.call(this)}N.exports=d;N.exports.once=ye;d.EventEmitter=d;d.prototype._events=void 0;d.prototype._eventsCount=0;d.prototype._maxListeners=void 0;var H=10;function C(o){if(typeof o!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof o)}Object.defineProperty(d,"defaultMaxListeners",{enumerable:!0,get:function(){return H},set:function(o){if(typeof o!="number"||o<0||K(o))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+o+".");H=o}});d.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};d.prototype.setMaxListeners=function(n){if(typeof n!="number"||n<0||K(n))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".");return this._maxListeners=n,this};function $(o){return o._maxListeners===void 0?d.defaultMaxListeners:o._maxListeners}d.prototype.getMaxListeners=function(){return $(this)};d.prototype.emit=function(n){for(var e=[],t=1;t<arguments.length;t++)e.push(arguments[t]);var s=n==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=i[n];if(c===void 0)return!1;if(typeof c=="function")J(c,this,e);else for(var h=c.length,l=ee(c,h),t=0;t<h;++t)J(l[t],this,e);return!0};function Q(o,n,e,t){var s,i,r;if(C(e),i=o._events,i===void 0?(i=o._events=Object.create(null),o._eventsCount=0):(i.newListener!==void 0&&(o.emit("newListener",n,e.listener?e.listener:e),i=o._events),r=i[n]),r===void 0)r=i[n]=e,++o._eventsCount;else if(typeof r=="function"?r=i[n]=t?[e,r]:[r,e]:t?r.unshift(e):r.push(e),s=$(o),s>0&&r.length>s&&!r.warned){r.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(n)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=o,a.type=n,a.count=r.length,be(a)}return o}d.prototype.addListener=function(n,e){return Q(this,n,e,!1)};d.prototype.on=d.prototype.addListener;d.prototype.prependListener=function(n,e){return Q(this,n,e,!0)};function me(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function X(o,n,e){var t={fired:!1,wrapFn:void 0,target:o,type:n,listener:e},s=me.bind(t);return s.listener=e,t.wrapFn=s,s}d.prototype.once=function(n,e){return C(e),this.on(n,X(this,n,e)),this};d.prototype.prependOnceListener=function(n,e){return C(e),this.prependListener(n,X(this,n,e)),this};d.prototype.removeListener=function(n,e){var t,s,i,r,a;if(C(e),s=this._events,s===void 0)return this;if(t=s[n],t===void 0)return this;if(t===e||t.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[n],s.removeListener&&this.emit("removeListener",n,t.listener||e));else if(typeof t!="function"){for(i=-1,r=t.length-1;r>=0;r--)if(t[r]===e||t[r].listener===e){a=t[r].listener,i=r;break}if(i<0)return this;i===0?t.shift():ge(t,i),t.length===1&&(s[n]=t[0]),s.removeListener!==void 0&&this.emit("removeListener",n,a||e)}return this};d.prototype.off=d.prototype.removeListener;d.prototype.removeAllListeners=function(n){var e,t,s;if(t=this._events,t===void 0)return this;if(t.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):t[n]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete t[n]),this;if(arguments.length===0){var i=Object.keys(t),r;for(s=0;s<i.length;++s)r=i[s],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=t[n],typeof e=="function")this.removeListener(n,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(n,e[s]);return this};function Y(o,n,e){var t=o._events;if(t===void 0)return[];var s=t[n];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?ve(s):ee(s,s.length)}d.prototype.listeners=function(n){return Y(this,n,!0)};d.prototype.rawListeners=function(n){return Y(this,n,!1)};d.listenerCount=function(o,n){return typeof o.listenerCount=="function"?o.listenerCount(n):Z.call(o,n)};d.prototype.listenerCount=Z;function Z(o){var n=this._events;if(n!==void 0){var e=n[o];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}d.prototype.eventNames=function(){return this._eventsCount>0?E(this._events):[]};function ee(o,n){for(var e=new Array(n),t=0;t<n;++t)e[t]=o[t];return e}function ge(o,n){for(;n+1<o.length;n++)o[n]=o[n+1];o.pop()}function ve(o){for(var n=new Array(o.length),e=0;e<n.length;++e)n[e]=o[e].listener||o[e];return n}function ye(o,n){return new Promise(function(e,t){function s(r){o.removeListener(n,i),t(r)}function i(){typeof o.removeListener=="function"&&o.removeListener("error",s),e([].slice.call(arguments))}te(o,n,i,{once:!0}),n!=="error"&&Se(o,s,{once:!0})})}function Se(o,n,e){typeof o.on=="function"&&te(o,"error",n,e)}function te(o,n,e,t){if(typeof o.on=="function")t.once?o.once(n,e):o.on(n,e);else if(typeof o.addEventListener=="function")o.addEventListener(n,function s(i){t.once&&o.removeEventListener(n,s),e(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof o)}});var oe=V(F());var M=(t=>(t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t))(M||{}),D=(t=>(t.Unsubscribed="unsubscribed",t.Subscribing="subscribing",t.Subscribed="subscribed",t))(D||{});function se(o,n){return o.lastIndexOf(n,0)===0}function O(o){return o==null?!1:typeof o=="function"}function ie(o,n){if(globalThis.console){let e=globalThis.console[o];O(e)&&e.apply(globalThis.console,n)}}function Pe(o,n){return Math.floor(Math.random()*(n-o+1)+o)}function y(o,n,e){o>31&&(o=31);let t=Pe(0,Math.min(e,n*Math.pow(2,o)));return Math.min(e,n+t)}function ne(o){return"error"in o&&o.error!==null}function S(o){return Math.min(o*1e3,2147483647)}function re(o){try{return typeof localStorage>"u"||localStorage===null||!O(localStorage.getItem)?null:localStorage.getItem(o)}catch{return null}}var x=class extends oe.default{constructor(e,t,s){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=t,this.state="unsubscribed",this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValueMap=new Map,this._unsubPromise=Promise.resolve(),this._deltaNumPubs=0,this._deltaNumFull=0,this._deltaNumDelta=0,this._deltaBytesReceived=0,this._deltaBytesDecoded=0,this._setOptions(s),this.type=this._sharedPoll?"shared_poll":this._map?"map":"stream",this._centrifuge._debugEnabled?(this.on("state",i=>{this._debug("subscription state",t,i.oldState,"->",i.newState)}),this.on("error",i=>{this._debug("subscription error",t,i)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state==="unsubscribed"?Promise.reject({code:7,message:this.state}):this.state==="subscribed"?Promise.resolve():new Promise((t,s)=>{let i={resolve:t,reject:s};e&&(i.timeout=setTimeout(function(){s({code:1,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(0,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(0,"unsubscribe called",!0)}_debouncedPublish(e,t,s){let i=this._debouncePending.get(e);if(i)return i.data=t,i.dirty=!0,Promise.resolve({});let r={data:t,dirty:!1,timer:null};return r.timer=setTimeout(()=>{let c=this._debouncePending.get(e);if(!c||!c.dirty){this._debouncePending.delete(e);return}c.dirty=!1;let h=c.data;(s?this._centrifuge.mapPublish(this.channel,e,h):this._centrifuge.publish(this.channel,h)).catch(()=>{}),c.timer=setTimeout(()=>{let u=this._debouncePending.get(e);if(!u||!u.dirty){this._debouncePending.delete(e);return}this._debouncePending.delete(e),this._debouncedPublish(e,u.data,s)},this._debounceMs)},this._debounceMs),this._debouncePending.set(e,r),s?this._centrifuge.mapPublish(this.channel,e,t):this._centrifuge.publish(this.channel,t)}_cancelDebounce(e){let t=this._debouncePending.get(e);t&&(clearTimeout(t.timer),this._debouncePending.delete(e))}_cancelAllDebounce(){for(let[,e]of this._debouncePending)clearTimeout(e.timer);this._debouncePending.clear()}async presence(){return await this._methodCall(),this._centrifuge.presence(this.channel)}async presenceStats(){return await 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(){let 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:7,message:this.state}):new Promise((e,t)=>{let s=this._centrifuge._config.timeout,i=setTimeout(()=>{t({code:1,message:"timeout"})},s);this._promises[this._nextPromiseId()]={timeout:i,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return this._recover===!0}_isUnsubscribed(){return this.state==="unsubscribed"}_isSubscribing(){return this.state==="subscribing"}_isSubscribed(){return this.state==="subscribed"}_setState(e){if(this.state!==e){let t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return this._token!==""||this._getToken!==null}_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):(this._offset=0,this._epoch="_")}_setSubscribed(e){if(!this._isSubscribing())return;if(this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,e.publish_debounce&&(this._debounceMs=e.publish_debounce),this._sharedPoll){let i=e.epoch||"";if(this._sharedPollEpoch!==""&&this._sharedPollEpoch!==i)for(let r of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(r,0);this._sharedPollEpoch=i}this._setState("subscribed");let t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();let s=e.publications;if(s&&s.length>0)for(let i in s)s.hasOwnProperty(i)&&this._handlePublication(s[i]);e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl)))}async _setSubscribing(e,t){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._id=0,this._setState("subscribing")&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&await 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&&this._offset===null?(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(){if(!this._isSubscribing()){this._inflight=!1;return}this._getState().then(e=>{if(!this._isSubscribing()){this._inflight=!1;return}this._offset=e.offset,this._epoch=e.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t))}).catch(e=>{if(!this._isSubscribing()){this._inflight=!1;return}this._inflight=!1,this._subscribeError({code:13,message:e?.toString()||"getState failed",temporary:!0})})}_getDataAndSubscribe(e){if(!this._getData){this._inflight=!1;return}this._getData({channel:this.channel}).then(t=>{if(!this._isSubscribing()){this._inflight=!1;return}this._data=t,this._sendSubscribe(e)}).catch(t=>this._handleGetDataError(t))}_handleGetDataError(e){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof g){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:12,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_handleTokenResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e){this._inflight=!1,this._failUnauthorized();return}this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}_handleTokenError(e){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof g){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:8,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;let t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(s=>{this._inflight=!1;let i=s.reply.subscribe;this._handleSubscribeResponse(i),s.next&&s.next()},s=>{this._inflight=!1,this._handleSubscribeError(s.error),s.next&&s.next()}),t}_buildSubscribeCommand(e){let t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._sharedPoll)return t.type=4,this._delta&&(t.delta=this._delta),{subscribe:t};if(this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=1,this._getState&&(t.flag|=2),this._needRecover()){t.recover=!0;let s=this._getOffset();s&&(t.offset=s);let i=this._getEpoch();i&&(t.epoch=i)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(e){if(this._isSubscribing()){if(e.code===1){this._centrifuge._disconnect(3,"subscribe timeout",!0);return}if(e.code===112&&this._getState){this._offset=null,this._epoch=null,this._recover=!1,this._prevValueMap=new Map,this._scheduleResubscribe();return}this._subscribeError(e)}}_handleSubscribeResponse(e){this._isSubscribing()&&(this._setSubscribed(e),this._sharedPoll&&this._sharedPollReplayTrack())}_setUnsubscribed(e,t,s){if(this._isUnsubscribed())return Promise.resolve();let i=Promise.resolve();return this._isSubscribed()?(s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._id=0,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState("unsubscribed")&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:7,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){let s=(this._map||this._sharedPoll)&&e.key||"",{newData:i,newPrevValue:r,isDelta:a,wireBytes:c,fullBytes:h}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(s));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=c,this._deltaBytesDecoded+=h,a?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(s):this._prevValueMap.set(s,r)}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 this._map?t=this._getMapUpdateContext(e):t=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(typeof e.data=="string"){let t=e.data;e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,new TextEncoder().encode(t));let 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);let t=e.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=t,this._deltaBytesDecoded+=t}}}_handleJoin(e){let t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){let t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(let 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(let 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()){this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);return}let e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||e.code===109||e.temporary===!0){e.code===109&&(this._token="");let t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state==="connected"&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){let e=y(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),e.minResubscribeDelay!==void 0&&(this._minResubscribeDelay=e.minResubscribeDelay),e.maxResubscribeDelay!==void 0&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),e.positioned===!0&&(this._positioned=!0),e.recoverable===!0&&(this._recoverable=!0),e.joinLeave===!0&&(this._joinLeave=!0),e.delta){if(e.delta!=="fossil")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),e.map===!0&&(this._map=!0),e.mapPageSize!==void 0&&(this._mapPageSize=e.mapPageSize),e.mapPresenceType!==void 0&&(this._mapPresenceType=e.mapPresenceType,this._map=!0),e.mapUnrecoverableStrategy&&(this._mapUnrecoverableStrategy=e.mapUnrecoverableStrategy),e.sharedPoll===!0&&(this._sharedPoll=!0),e.sharedPollGetSignature&&(this._sharedPollGetSignature=e.sharedPollGetSignature)}}_getOffset(){let e=this._offset;return e!==null?e:0}_getEpoch(){let e=this._epoch;return e!==null?e:""}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){this._resubscribeTimeout!==null&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);let e={channel:this.channel},t=this._getToken;return t===null?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:12,message:"provide a function to get channel subscription token"}}),Promise.reject(new g(""))):t(e)}_refresh(){this._clearRefreshTimeout();let e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t){e._failUnauthorized();return}e._token=t;let i={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(i).then(r=>{let a=r.reply.sub_refresh;e._refreshResponse(a),r.next&&r.next()},r=>{e._refreshError(r.error),r.next&&r.next()})}).catch(function(t){if(t instanceof g){e._failUnauthorized();return}e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:9,message:t!==void 0?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay())})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||e.temporary===!0?(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 y(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(1,"unauthorized",!0)}_sendTrackRequest(e,t){if(e.length===0)return Promise.resolve();let s=6e4,i=[],r=[],a=100;if(t&&t.length>0)for(let h of t)a+=h.length+4;for(let h of e){let l=100;for(let u of h.items)l+=u.key.length+16;r.length>0&&a+l>s&&(i.push(r),r=[],a=100),r.push(h),a+=l}r.length>0&&i.push(r);let c=(h,l)=>new Promise((u,v)=>{let m={channel:this.channel,type:1,track:h.map(f=>({signature:f.signature,items:f.items.map(_=>_.version>0?_:{key:_.key})}))};l&&l.length>0&&(m.untrack=l);let p={sub_refresh:m};this._centrifuge._call(p).then(f=>{this._handleTrackResponse(f.reply.sub_refresh),f.next&&f.next(),u()},f=>{f.next&&f.next(),v(f.error)})});return i.reduce((h,l,u)=>h.then(()=>c(l,u===0?t:void 0)),Promise.resolve())}_sendUntrackRequest(e){return new Promise((t,s)=>{let r={sub_refresh:{channel:this.channel,type:2,untrack:e}};this._centrifuge._call(r).then(a=>{a.next&&a.next(),t()},a=>{a.next&&a.next(),s(a.error)})})}_handleTrackResponse(e){if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(let t of e.items)this._handlePublication(t);if(e&&e.expires===!0&&e.ttl>0){let t=Date.now()+e.ttl*1e3;this._maybeScheduleSharedPollSignatureRefresh(t)}}_maybeScheduleSharedPollSignatureRefresh(e){if(e===null){this._sharedPollSignatureRefreshTargetMs=null,this._clearSharedPollSignatureRefresh();return}this._isSubscribed()&&(this._sharedPollSignatureRefreshTargetMs!==null&&e>=this._sharedPollSignatureRefreshTargetMs||(this._sharedPollSignatureRefreshTargetMs=e,this._clearSharedPollSignatureRefresh(),this._sharedPollSignatureRefreshTimeout=setTimeout(()=>this._sharedPollRefreshSignature(),Math.max(0,e-Date.now()))))}_clearSharedPollSignatureRefresh(){this._sharedPollSignatureRefreshTimeout!==null&&(clearTimeout(this._sharedPollSignatureRefreshTimeout),this._sharedPollSignatureRefreshTimeout=null),this._sharedPollSignatureRefreshAttempts=0}_clearSharedPollTrackRetry(){this._sharedPollTrackRetryTimeout!==null&&(clearTimeout(this._sharedPollTrackRetryTimeout),this._sharedPollTrackRetryTimeout=null),this._sharedPollTrackRetryAttempts=0}_clearSharedPollReplayRetry(){this._sharedPollReplayRetryTimeout!==null&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_handleTrackError(e){if(this._isSubscribed()){if(this.emit("error",{type:"track",channel:this.channel,error:e}),e.code===109){this._sharedPollRefreshSignature();return}(e.code<100||e.temporary===!0)&&(this._sharedPollTrackRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),y(this._sharedPollTrackRetryAttempts++,1e3,15e3)))}}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed()||!this._sharedPollGetSignature||this._sharedPollTrackedItems.size===0||this._sharedPollSignatureRefreshInFlight)return;this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;let e=Array.from(this._sharedPollTrackedItems.keys()),t=this;this._sharedPollGetSignature({keys:e}).then(s=>{if(t._sharedPollSignatureRefreshInFlight=!1,!t._isSubscribed())return;t._sharedPollSignatureRefreshAttempts=0;let i=new Set(s.keys),r=[];for(let l of e)i.has(l)||(t._sharedPollTrackedItems.delete(l),r.push(l),t.emit("update",{channel:t.channel,key:l,data:null,removed:!0}));r.length>0&&t._sendUntrackRequest(r).catch(l=>{t.emit("error",{type:"untrack",channel:t.channel,error:l})});let a=[];for(let l of s.keys){let u=t._sharedPollTrackedItems.get(l);u!==void 0&&a.push({key:l,version:u})}let c=new Set(s.keys),h=t._sharedPollSignatures.filter(l=>l.keys.some(u=>t._sharedPollTrackedItems.has(u)&&!c.has(u)));t._sharedPollSignatures=a.length>0?[{keys:s.keys,signature:s.signature},...h]:h,a.length!==0&&t._sendTrackRequest([{items:a,signature:s.signature}]).catch(l=>{t._handleTrackError(l)})}).catch(s=>{t._sharedPollSignatureRefreshInFlight=!1,t.emit("error",{type:"signatureRefresh",channel:t.channel,error:{code:14,message:s!==void 0?s.toString():""}}),t._sharedPollSignatureRefreshTimeout=setTimeout(()=>t._sharedPollRefreshSignature(),y(t._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed()||this._sharedPollTrackedItems.size===0&&this._sharedPollSignatures.length===0)return;let e=new Set,t=[],s=[];for(let a of this._sharedPollSignatures){let c=a.keys.map(h=>({key:h,version:this._sharedPollTrackedItems.get(h)??0}));t.push({items:c,signature:a.signature});for(let h of a.keys)this._sharedPollTrackedItems.has(h)?e.add(h):s.push(h)}t.length>0&&this._sendTrackRequest(t,s).catch(a=>{this._handleTrackError(a)});let i=[];for(let a of this._sharedPollTrackedItems.keys())e.has(a)||i.push(a);if(i.length===0)return;if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:"getSignature callback required for tracked keys without an explicit signature"}});return}let r=this;this._sharedPollGetSignature({keys:i}).then(a=>{if(!r._isSubscribed())return;r._clearSharedPollReplayRetry();let c=new Set(a.keys),h=[];for(let u of i)c.has(u)||(r._sharedPollTrackedItems.delete(u),h.push(u),r.emit("update",{channel:r.channel,key:u,data:null,removed:!0}));h.length>0&&r._sendUntrackRequest(h).catch(u=>{r.emit("error",{type:"untrack",channel:r.channel,error:u})});let l=[];for(let u of a.keys){let v=r._sharedPollTrackedItems.get(u);v!==void 0&&l.push({key:u,version:v})}l.length!==0&&(r._sharedPollSignatures.push({keys:a.keys,signature:a.signature}),r._sendTrackRequest([{items:l,signature:a.signature}]).catch(u=>{r._handleTrackError(u)}))}).catch(a=>{r.emit("error",{type:"signatureRefresh",channel:r.channel,error:{code:14,message:a!==void 0?a.toString():""}}),r._sharedPollReplayRetryTimeout=setTimeout(()=>r._sharedPollReplayTrack(),y(r._sharedPollReplayRetryAttempts++,5e3,3e4))})}_mapSubscribe(){if(this._debug("starting map subscribe on",this.channel),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._recover&&this._offset!==null&&this._epoch!==null||(this._prevValueMap=new Map),this._mapPhase=2,this._recover&&this._offset!==null&&this._epoch!==null){this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=1,this._fetchStream();return}this._canSubscribeWithoutGettingToken()?this._fetchSnapshot():this._getSubscriptionToken().then(e=>{if(!this._isSubscribing()){this._inflight=!1;return}if(!e){this._inflight=!1,this._failUnauthorized();return}this._token=e,this._fetchSnapshot()}).catch(e=>this._handleTokenError(e))}_fetchSnapshot(e){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let t=this._buildMapSubscribeCommand(2,e);this._debug("map subscribe: fetching snapshot page",e?`cursor=${e}`:"initial"),this._centrifuge._call(t).then(s=>{let i=s.reply.subscribe;this._handleMapStateResponse(i),s.next&&s.next()},s=>{this._handleMapSubscribeError(s.error),s.next&&s.next()})}_handleMapStateResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e.phase){this._debug("map subscribe: server forced LIVE transition during state pagination"),this._handleMapLiveResponse(e);return}if(!this._epoch&&e.epoch&&(this._epoch=e.epoch,this._offset=e.offset||0),this._epoch&&e.epoch&&this._epoch!==e.epoch){this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._mapStateBuffer=[],this._mapCursor="",this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(let t of e.state)this._seedDeltaTracking(t),this._mapStateBuffer.push(this._getMapUpdateContext(t));if(e.cursor){this._mapCursor=e.cursor,this._fetchSnapshot(this._mapCursor);return}this._transitionFromSnapshot()}_transitionFromSnapshot(){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=1,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let e=this._buildMapSubscribeCommand(1);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(e).then(t=>{let s=t.reply.subscribe;this._handleMapStreamResponse(s),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStreamResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e.phase){this._debug("map subscribe: server forced LIVE transition during stream"),this._handleMapLiveResponse(e);return}if(this._epoch&&e.epoch&&this._epoch!==e.epoch){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=2,this._fetchSnapshot();return}if(e.publications&&e.publications.length>0)for(let t of e.publications)this._seedDeltaTracking(t),this._mapStreamBuffer.push(this._getMapUpdateContext(t));e.offset!==void 0&&(this._offset=e.offset),this._fetchStream()}_handleMapLiveResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(this._inflight=!1,this._epoch&&e.epoch&&this._epoch!==e.epoch){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=2,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(let s of e.state)this._seedDeltaTracking(s),this._mapStateBuffer.push(this._getMapUpdateContext(s));if(e.publications&&e.publications.length>0)for(let s of e.publications){if(this._delta&&e.delta){let i=s.key||"",{newData:r,newPrevValue:a,isDelta:c,wireBytes:h,fullBytes:l}=this._centrifuge._codec.applyDeltaIfNeeded(s,this._prevValueMap.get(i));s.data=r,this._deltaNumPubs++,this._deltaBytesReceived+=h,this._deltaBytesDecoded+=l,c?this._deltaNumDelta++:this._deltaNumFull++,s.removed?this._prevValueMap.delete(i):this._prevValueMap.set(i,a)}else this._delta&&s.key&&(s.removed?this._prevValueMap.delete(s.key):this._prevValueMap.set(s.key,s.data));this._mapStreamBuffer.push(this._getMapUpdateContext(s))}this._offset=e.offset||0,this._epoch=e.epoch||"",this._clearSubscribingState(),e.id&&(this._id=e.id),this._recover=e.recoverable===!0,e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,e.publish_debounce&&(this._debounceMs=e.publish_debounce),this._setState("subscribed");let t=this._centrifuge._getSubscribeContext(this.channel,e);if(t.state=this._mapStateBuffer,this.emit("subscribed",t),this._resolvePromises(),!t.recovered){if(this._mapStreamBuffer.length>0){let s=new Map;for(let i of this._mapStateBuffer)s.set(i.key,i);for(let i of this._mapStreamBuffer)i.removed?s.delete(i.key):s.set(i.key,i);this._mapStateBuffer=Array.from(s.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(let s of this._mapStreamBuffer)this.emit("publication",s),this.emit("update",s);this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl)))}_handleMapSubscribeError(e){if(this._inflight=!1,!!this._isSubscribing()){if(e.code===1){this._centrifuge._disconnect(3,"subscribe timeout",!0);return}if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,this._prevValueMap=new Map,e.code===112&&this._mapUnrecoverableStrategy==="from_scratch"){this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._offset=null,this._epoch=null,this._recover=!1,this._scheduleResubscribe();return}this._subscribeError(e)}}_buildMapSubscribeCommand(e,t){let s={channel:this.channel,type:this._mapPresenceType||1,phase:e};return this._token&&(s.token=this._token),this._tagsFilter&&(s.tf=this._tagsFilter),this._delta&&(s.delta=this._delta),s.flag=1,e===2&&(this._mapPageSize>0&&(s.limit=this._mapPageSize),t&&(s.cursor=t),this._epoch?(s.offset=this._offset,s.epoch=this._epoch):this._data&&(s.data=this._data)),e===1&&(this._mapPageSize>0&&(s.limit=this._mapPageSize),s.offset=this._offset,s.epoch=this._epoch,this._recover&&(s.recover=!0,this._mapStreamBuffer.length===0&&this._data&&(s.data=this._data))),{subscribe:s}}_getMapUpdateContext(e){let t={channel:this.channel,data:e.data,key:e.key||""};return e.removed===!0&&(t.removed=!0),e.offset!==void 0&&(t.offset=e.offset),e.info&&(t.info=this._centrifuge._getJoinLeaveContext(e.info)),e.tags&&(t.tags=e.tags),t}_getSharedPollUpdateContext(e){let t={channel:this.channel,key:e.key||"",data:e.data};return e.removed===!0&&(t.removed=!0),e.version!==void 0&&(t.version=e.version),t}},I=class extends x{async publish(n){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish("",n,!1):this._centrifuge.publish(this.channel,n)}async history(n){return await this._methodCall(),this._centrifuge.history(this.channel,n)}},k=class extends x{async publish(n,e){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish(n,e,!0):this._centrifuge.mapPublish(this.channel,n,e)}async remove(n){return await this._methodCall(),this._cancelDebounce(n),this._centrifuge.mapRemove(this.channel,n)}},L=class extends x{track(n,e){if(n.length===0)return;let t,s=e;typeof n[0]=="string"?t=n.map(a=>({key:a,version:0})):t=n;for(let r of t){let a=this._sharedPollTrackedItems.get(r.key);(a===void 0||r.version>a)&&this._sharedPollTrackedItems.set(r.key,r.version)}if(s!==void 0){this._sharedPollSignatures.push({keys:t.map(r=>r.key),signature:s}),this._isSubscribed()&&this._sendTrackRequest([{items:t,signature:s}]).catch(r=>{this._handleTrackError(r)});return}if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:"getSignature callback required for track(keys)"}});return}if(!this._isSubscribed())return;let i=t.map(r=>r.key);this._sharedPollGetSignature({keys:i}).then(r=>{if(!this._isSubscribed())return;let a=new Set(r.keys),c=[];for(let l of i)a.has(l)||(this._sharedPollTrackedItems.delete(l),c.push(l),this.emit("update",{channel:this.channel,key:l,data:null,removed:!0}));c.length>0&&this._sendUntrackRequest(c).catch(l=>{this.emit("error",{type:"untrack",channel:this.channel,error:l})});let h=[];for(let l of r.keys){let u=this._sharedPollTrackedItems.get(l);u!==void 0&&h.push({key:l,version:u})}h.length!==0&&(this._sharedPollSignatures.push({keys:r.keys,signature:r.signature}),this._sendTrackRequest([{items:h,signature:r.signature}]).catch(l=>{this._handleTrackError(l)}))}).catch(r=>{this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:r!==void 0?r.toString():"getSignature failed"}})})}untrack(n){for(let e of n)this._sharedPollTrackedItems.delete(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(e=>e.keys.some(t=>this._sharedPollTrackedItems.has(t))),this._isSubscribed()&&this._sendUntrackRequest(n).catch(e=>{this.emit("error",{type:"untrack",channel:this.channel,error:e})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}};var U=class{constructor(n,e){this.endpoint=n,this.options=e,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return this.options.sockjs!==null}initialize(n,e){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(n){this._transport.send(n)}};var w=class{constructor(n,e){this.endpoint=n,this.options=e,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return this.options.websocket!==void 0&&this.options.websocket!==null}initialize(n,e){let t="";n==="protobuf"&&(t="centrifuge-protobuf"),t!==""?this._transport=new this.options.websocket(this.endpoint,t):this._transport=new this.options.websocket(this.endpoint),n==="protobuf"&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=s=>{e.onError(s)},this._transport.onclose=s=>{e.onClose(s)},this._transport.onmessage=s=>{e.onMessage(s.data)}}close(){this._transport.close()}send(n){this._transport.send(n)}};var B=class{constructor(n,e){this.endpoint=n,this.options=e,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(n){if(!n.ok)throw new Error(n.status);return n}_fetchEventTarget(n,e,t){let s=new EventTarget,i=n.options.fetch;return i(e,t).then(n._handleErrors).then(r=>{s.dispatchEvent(new Event("open"));let a="",c=0,h=new Uint8Array,l=r.body.getReader();return new n.options.readableStream({start(u){function v(){return l.read().then(({done:m,value:p})=>{if(m){s.dispatchEvent(new Event("close")),u.close();return}try{if(n._protocol==="json")for(a+=n._utf8decoder.decode(p);c<a.length;)if(a[c]===`
`){let f=a.substring(0,c);s.dispatchEvent(new MessageEvent("message",{data:f})),a=a.substring(c+1),c=0}else++c;else{let f=new Uint8Array(h.length+p.length);for(f.set(h),f.set(p,h.length),h=f;;){let _=n.options.decoder.decodeReply(h);if(_.ok){let b=h.slice(0,_.pos);s.dispatchEvent(new MessageEvent("message",{data:b})),h=h.slice(_.pos);continue}break}}}catch(f){s.dispatchEvent(new Event("error",{detail:f})),s.dispatchEvent(new Event("close")),u.close();return}v()}).catch(function(m){s.dispatchEvent(new Event("error",{detail:m})),s.dispatchEvent(new Event("close")),u.close()})}return v()}})}).catch(r=>{s.dispatchEvent(new Event("error",{detail:r})),s.dispatchEvent(new Event("close"))}),s}supported(){return this.options.fetch!==null&&this.options.readableStream!==null&&typeof TextDecoder<"u"&&typeof AbortController<"u"&&typeof EventTarget<"u"&&typeof Event<"u"&&typeof MessageEvent<"u"&&typeof Error<"u"}initialize(n,e,t){this._protocol=n,this._abortController=new AbortController;let s,i;n==="json"?(s={Accept:"application/json","Content-Type":"application/json"},i=t):(s={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},i=t);let r={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},a=this._fetchEventTarget(this,this.endpoint,r);a.addEventListener("open",()=>{e.onOpen()}),a.addEventListener("error",c=>{this._abortController.abort(),e.onError(c)}),a.addEventListener("close",()=>{this._abortController.abort(),e.onClose({code:4,reason:"connection closed"})}),a.addEventListener("message",c=>{e.onMessage(c.data)})}close(){this._abortController.abort()}send(n,e,t){let s,i,r={session:e,node:t,data:n};this._protocol==="json"?(s={"Content-Type":"application/json"},i=JSON.stringify(r)):(s={"Content-Type":"application/octet-stream"},i=this.options.encoder.encodeEmulationRequest(r));let a=this.options.fetch,c={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,c)}};var A=class{constructor(n,e){this.endpoint=n,this.options=e,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return this.options.eventsource!==null&&this.options.fetch!==null}initialize(n,e,t){let s;globalThis&&globalThis.document&&globalThis.document.baseURI?s=new URL(this.endpoint,globalThis.document.baseURI):s=new URL(this.endpoint),s.searchParams.append("cf_connect",t);let i={},r=new this.options.eventsource(s.toString(),i);this._transport=r;let a=this;r.onopen=function(){e.onOpen()},r.onerror=function(c){r.close(),e.onError(c),e.onClose({code:4,reason:"connection closed"})},r.onmessage=function(c){e.onMessage(c.data)},a._onClose=function(){e.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),this._onClose!==null&&this._onClose()}send(n,e,t){let s={session:e,node:t,data:n},i={"Content-Type":"application/json"},r=JSON.stringify(s),a=this.options.fetch,c={method:"POST",headers:i,body:r,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,c)}};var j=class{constructor(n,e){this.endpoint=n,this.options=e,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 this.options.webtransport!==void 0&&this.options.webtransport!==null}async initialize(n,e){let t;globalThis&&globalThis.document&&globalThis.document.baseURI?t=new URL(this.endpoint,globalThis.document.baseURI):t=new URL(this.endpoint),n==="protobuf"&&t.searchParams.append("cf_protocol","protobuf"),this._protocol=n;let s=new EventTarget;this._transport=new this.options.webtransport(t.toString()),this._transport.closed.then(()=>{e.onClose({code:4,reason:"connection closed"})}).catch(()=>{e.onClose({code:4,reason:"connection closed"})});try{await this._transport.ready}catch{this.close();return}let i;try{i=await this._transport.createBidirectionalStream()}catch{this.close();return}this._stream=i,this._writer=this._stream.writable.getWriter(),s.addEventListener("close",()=>{e.onClose({code:4,reason:"connection closed"})}),s.addEventListener("message",r=>{e.onMessage(r.data)}),this._startReading(s),e.onOpen()}async _startReading(n){let e=this._stream.readable.getReader(),t="",s=0,i=new Uint8Array;try{for(;;){let{done:r,value:a}=await e.read();if(a.length>0)if(this._protocol==="json")for(t+=this._utf8decoder.decode(a);s<t.length;)if(t[s]===`
`){let c=t.substring(0,s);n.dispatchEvent(new MessageEvent("message",{data:c})),t=t.substring(s+1),s=0}else++s;else{let c=new Uint8Array(i.length+a.length);for(c.set(i),c.set(a,i.length),i=c;;){let h=this.options.decoder.decodeReply(i);if(h.ok){let l=i.slice(0,h.pos);n.dispatchEvent(new MessageEvent("message",{data:l})),i=i.slice(h.pos);continue}break}}if(r)break}}catch{n.dispatchEvent(new Event("close"))}}async close(){try{this._writer&&await this._writer.close(),this._transport.close()}catch{}}async send(n){let e;this._protocol==="json"?e=new TextEncoder().encode(n+`
`):e=n;try{await this._writer.write(e)}catch{this.close()}}};var Re=[-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],q=class{constructor(n){this.a=n,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){let n=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return n}getChar(){return String.fromCharCode(this.getByte())}getInt(){let n=0,e;for(;this.haveBytes()&&(e=Re[127&this.getByte()])>=0;)n=(n<<6)+e;return this.pos--,n>>>0}},W=class{constructor(){this.a=[]}toByteArray(n){return Array.isArray(n)?this.a:new Uint8Array(this.a)}putArray(n,e,t){for(let s=e;s<t;s++)this.a.push(n[s])}};function Ee(o){let n=0,e=0,t=0,s=0,i=0,r=o.length;for(;r>=16;)n=n+o[i+0]|0,e=e+o[i+1]|0,t=t+o[i+2]|0,s=s+o[i+3]|0,n=n+o[i+4]|0,e=e+o[i+5]|0,t=t+o[i+6]|0,s=s+o[i+7]|0,n=n+o[i+8]|0,e=e+o[i+9]|0,t=t+o[i+10]|0,s=s+o[i+11]|0,n=n+o[i+12]|0,e=e+o[i+13]|0,t=t+o[i+14]|0,s=s+o[i+15]|0,i+=16,r-=16;for(;r>=4;)n=n+o[i+0]|0,e=e+o[i+1]|0,t=t+o[i+2]|0,s=s+o[i+3]|0,i+=4,r-=4;switch(s=((s+(t<<8)|0)+(e<<16)|0)+(n<<24)|0,r){case 3:s=s+(o[i+2]<<8)|0;case 2:s=s+(o[i+1]<<16)|0;case 1:s=s+(o[i+0]<<24)|0}return s>>>0}function ae(o,n){let e=0,t=new q(n),s=o.length,i=n.length,r=t.getInt();if(t.getChar()!==`
`)throw new Error("size integer not terminated by '\\n'");let a=new W;for(;t.haveBytes();){let c=t.getInt(),h;switch(t.getChar()){case"@":if(h=t.getInt(),t.haveBytes()&&t.getChar()!==",")throw new Error("copy command not terminated by ','");if(e+=c,e>r)throw new Error("copy exceeds output file size");if(h+c>s)throw new Error("copy extends past end of input");a.putArray(o,h,h+c);break;case":":if(e+=c,e>r)throw new Error("insert command gives an output larger than predicted");if(c>i)throw new Error("insert count exceeds size of delta");a.putArray(t.a,t.pos,t.pos+c),t.pos+=c;break;case";":{let l=a.toByteArray(o);if(c!==Ee(l))throw new Error("bad checksum");if(e!==r)throw new Error("generated size does not match predicted size");return l}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}var R=class{name(){return"json"}encodeCommands(n){return n.map(e=>JSON.stringify(e)).join(`
`)}decodeReplies(n){return n.trim().split(`
`).map(e=>JSON.parse(e))}applyDeltaIfNeeded(n,e){let t,s,i;if(n.delta){i=!0;let r=new TextEncoder().encode(n.data),a=ae(e,r);t=JSON.parse(new TextDecoder().decode(a)),s=a}else i=!1,t=JSON.parse(n.data),s=new TextEncoder().encode(n.data);return{newData:t,newPrevValue:s,isDelta:i,wireBytes:n.data.length,fullBytes:s.length}}};var ce=V(F()),Ce={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},g=class extends Error{constructor(n){super(n),this.name=this.constructor.name}},P=class extends ce.default{constructor(e,t){super();this._reconnectTimeout=null;this._refreshTimeout=null;this._serverPingTimeout=null;this.state="disconnected",this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new R,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={...Ce,...t},this._configure(),this._debugEnabled?(this.on("state",s=>{this._debug("client state",s.oldState,"->",s.newState)}),this.on("error",s=>{this._debug("client error",s)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");let s=new I(this,e,t);return this._subs[e]=s,s}newMapSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");let s=new k(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newMapClientsSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");let s=new k(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newMapUsersSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");let s=new k(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newSharedPollSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");let s=new L(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,sharedPoll:!0,sharedPollGetSignature: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(e){e&&(e.state!=="unsubscribed"&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){let e={};for(let[t,s]of Object.entries(this._subs))s.type==="map"&&(e[t]=s);return e}sharedPollSubscriptions(){let e={};for(let[t,s]of Object.entries(this._subs))s.type==="shared_poll"&&(e[t]=s);return e}async ready(e){switch(this.state){case"disconnected":throw{code:3,message:"client disconnected"};case"connected":return;default:return new Promise((t,s)=>{let i={resolve:t,reject:s};e&&(i.timeout=setTimeout(()=>{s({code:1,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(0,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}async send(e){let t={send:{data:e}};if(await this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(10,"transport write error")}async rpc(e,t){let s={rpc:{method:e,data:t}};return await this._methodCall(),{data:(await this._callPromise(s,r=>r.rpc)).data}}async publish(e,t){let s={publish:{channel:e,data:t}};return await this._methodCall(),await this._callPromise(s,()=>({})),{}}async mapPublish(e,t,s){let i={publish:{channel:e,type:1,key:t,data:s}};return await this._methodCall(),await this._callPromise(i,()=>({})),{}}async mapRemove(e,t){let s={publish:{channel:e,type:1,key:t,removed:!0}};return await this._methodCall(),await this._callPromise(s,()=>({})),{}}async history(e,t){let s={history:this._getHistoryRequest(e,t)};await this._methodCall();let i=await this._callPromise(s,a=>a.history),r=[];if(i.publications)for(let a=0;a<i.publications.length;a++)r.push(this._getPublicationContext(e,i.publications[a]));return{publications:r,epoch:i.epoch||"",offset:i.offset||0}}async presence(e){let t={presence:{channel:e}};await this._methodCall();let i=(await this._callPromise(t,r=>r.presence)).presence;for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let a=i[r],c=a.conn_info,h=a.chan_info;c&&(a.connInfo=c),h&&(a.chanInfo=h)}return{clients:i}}async presenceStats(e){let t={presence_stats:{channel:e}};await this._methodCall();let s=await this._callPromise(t,i=>i.presence_stats);return{numUsers:s.num_users,numClients:s.num_clients}}startBatching(){this._batching=!0}stopBatching(){let e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&ie("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(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new R,this._formatOverride(),(this._config.debug===!0||re("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(let e in this._transports)if(this._transports.hasOwnProperty(e)){let t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");let s=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(s)<0)throw new Error("unsupported transport name: "+s)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;let t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state==="disconnected"}_isConnecting(){return this.state==="connecting"}_isConnected(){return this.state==="connected"}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state==="connected"||this.state==="connecting")&&(this._disconnect(1,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state==="connecting"&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){let e=y(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(let e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){let t=this._callbacks[e];clearTimeout(t.timeout);let s=t.errback;if(!s)continue;s({error:this._createErrorObject(11,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(let e in this._subs){if(!this._subs.hasOwnProperty(e))continue;let t=this._subs[e];t.state==="subscribed"&&t._setSubscribing(1,"transport closed")}for(let e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(let t of e){let s=t.id;if(!(s in this._callbacks))continue;let i=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s];let r=i.errback;r({error:this._createErrorObject(10,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let t=null;this._config.sockjs!==null?t=this._config.sockjs:typeof globalThis.SockJS<"u"&&(t=globalThis.SockJS);let s=null;this._config.eventsource!==null?s=this._config.eventsource:typeof globalThis.EventSource<"u"&&(s=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let r=null;if(this._config.readableStream!==null?r=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(r=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let p=0;for(;;){if(p>=this._transports.length)throw new Error("no supported transport found");let f=this._transports[this._currentTransportIndex],_=f.transport,b=f.endpoint;if(_==="websocket"){if(this._debug("trying websocket transport"),this._transport=new w(b,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,p++;continue}}else if(_==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new j(b,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,p++;continue}}else if(_==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new B(b,{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++,p++;continue}}else if(_==="sse"){if(this._debug("trying sse transport"),this._transport=new A(b,{eventsource:s,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,p++;continue}}else if(_==="sockjs"){if(this._debug("trying sockjs"),this._transport=new U(b,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,p++;continue}}else throw new Error("unknown transport "+_);break}}else{if(se(this._endpoint,"http"))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 w(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}let a=this,c=this._transport,h=this._nextTransportId();a._debug("id of transport",h);let l=!1,u=[];if(this._transport.emulation()){let p=a._sendConnect(!0);u.push(p)}this._setNetworkEvents();let v=this._codec.encodeCommands(u);this._transportClosed=!1;let m;m=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(m&&(clearTimeout(m),m=null),a._transportId!=h){a._debug("open callback from non-actual transport"),c.close();return}l=!0,a._debug(c.subName(),"transport open"),!c.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(p){if(a._transportId!=h){a._debug("error callback from non-actual transport");return}a._debug("transport level error",p)},onClose:function(p){if(m&&(clearTimeout(m),m=null),a._transportId!=h){a._debug("close callback from non-actual transport");return}a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let f="connection closed",_=!0,b=0;if(p&&"code"in p&&p.code&&(b=p.code),p&&p.reason)try{let z=JSON.parse(p.reason);f=z.reason,_=z.reconnect}catch{f=p.reason,(b>=3500&&b<4e3||b>=4500&&b<5e3)&&(_=!1)}b<3e3?(b===1009?(b=3,f="message size limit exceeded",_=!1):(b=1,f="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!l&&a.emit("error",{type:"transport",error:{code:2,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(b,f,_)},onMessage:function(p){a._dataReceived(p)}},v),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){let t=this._constructConnectCommand(),s=this;return this._call(t,e).then(i=>{let r=i.reply.connect;s._connectResponse(r),i.next&&i.next()},i=>{s._connectError(i.error),i.next&&i.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;let e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}let s=this;this._getToken().then(function(i){if(s._isConnecting()){if(i==null||i==null){s._failUnauthorized();return}s._token=i,s._debug("connection token refreshed"),s._config.getData?s._config.getData().then(function(r){s._isConnecting()&&(s._data=r,s._initializeTransport())}).catch(r=>s._handleGetDataError(r)):s._initializeTransport()}}).catch(function(i){if(!s._isConnecting())return;if(i instanceof g){s._failUnauthorized();return}s.emit("error",{type:"connectToken",error:{code:5,message:i!==void 0?i.toString():""}});let r=s._getReconnectDelay();s._debug("error on getting connection token, reconnect after "+r+" milliseconds",i),s._reconnecting=!1,s._reconnectTimeout=setTimeout(()=>{s._startReconnecting()},r)})}_handleGetDataError(e){if(e instanceof g){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:12,message:e?.toString()||""}});let t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state==="connecting"&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){let 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);let t={},s=!1;for(let i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;let r={recover:!0};this._serverSubs[i].offset&&(r.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(r.epoch=this._serverSubs[i].epoch),t[i]=r}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){let s={channel:e};return t!==void 0&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),t.limit!==void 0&&(s.limit=t.limit),t.reverse===!0&&(s.reverse=!0)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{let s=setTimeout(function(){t({code:1,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((s,i)=>{this._call(e,!1).then(r=>{let a=t(r.reply);s(a),r.next?.()},r=>{i(r.error),r.next?.()})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();let t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let s;this._dispatchPromise=new Promise(i=>{s=i}),this._dispatchSynchronized(t,s)})}_dispatchSynchronized(e,t){let s=Promise.resolve();for(let i in e)e.hasOwnProperty(i)&&(s=s.then(()=>this._dispatchReply(e[i])));s=s.then(()=>{t()})}_dispatchReply(e){let t,s=new Promise(r=>{t=r});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),s;let i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise((s,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState("connecting")&&this.emit("connecting",{code:0,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(e===3014){this._token="",this._refreshRequired=!0;for(let c in this._subs)this._subs.hasOwnProperty(c)&&this._subs[c]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;let i=this.state;this._reconnecting=!1;let r={code:e,reason:t},a=!1;if(s?a=this._setState("connecting"):(a=this._setState("disconnected"),this._rejectPromises({code:3,message:"disconnected"})),this._clearOutgoingRequests(),i==="connecting"&&this._clearReconnectTimeout(),i==="connected"&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",r):this.emit("disconnected",r)),this._transport){this._debug("closing existing transport");let c=this._transport;this._transport=null,c.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(1,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:12,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new g("")))}_refresh(){let e=this._client,t=this;this._getToken().then(function(s){if(e!==t._client)return;if(!s){t._failUnauthorized();return}if(t._token=s,t._debug("connection token refreshed"),!t._isConnected())return;let i={refresh:{token:t._token}};t._call(i,!1).then(r=>{let a=r.reply.refresh;t._refreshResponse(a),r.next&&r.next()},r=>{t._refreshError(r.error),r.next&&r.next()})}).catch(function(s){if(t._isConnected()){if(s instanceof g){t._failUnauthorized();return}t.emit("error",{type:"refreshToken",error:{code:6,message:s!==void 0?s.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return y(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();let s={unsubscribe:{channel:e.channel}},i=this;return new Promise((a,c)=>{this._call(s,!1).then(h=>{a(),h.next&&h.next()},h=>{a(),h.next&&h.next(),i._disconnect(4,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(let i in this._subs)if(this._subs.hasOwnProperty(i)){let r=this._subs[i];if(r._id===t)return r}return null}let s=this._subs[e];return s||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){let e=[];for(let t in this._subs){if(!this._subs.hasOwnProperty(t))continue;let s=this._subs[t];if(s._inflight!==!0&&s.state==="subscribing"){let i=s._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState("connected"),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();let t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(let t in e){if(!e.hasOwnProperty(t))continue;let s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||!1};let i=this._getSubscribeContext(t,s);this.emit("subscribed",i)}for(let t in e){if(!e.hasOwnProperty(t))continue;let s=e[t];if(s.recovered){let i=s.publications;if(i&&i.length>0)for(let r in i)i.hasOwnProperty(r)&&this._handlePublication(t,i[r])}}for(let t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(2,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){let 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 i="";"epoch"in t&&(i=t.epoch);let r=0;return"offset"in t&&(r=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:r,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(s.hasRecoveredPublications=!0),t.data&&(s.data=t.data),s}_handleReply(e,t){let s=e.id;if(!(s in this._callbacks)){t();return}let i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],ne(e)){let r=i.errback;if(!r){t();return}let a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};r({error:a,next:t})}else{let r=i.callback;if(!r)return;r({reply:e,next:t})}}_handleJoin(e,t,s){let i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){let r={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",r)}return}i._handleJoin(t)}_handleLeave(e,t,s){let i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){let r={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",r)}return}i._handleLeave(t)}_handleUnsubscribe(e,t){let s=this._getSub(e,0);if(!s&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):(t.code===2502&&s._invalidateState(),s._setSubscribing(t.code,t.reason))}_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){let t=e.code,s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){let 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){let t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);let i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){let i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){let r=this._getPublicationContext(e,t);this.emit("publication",r),t.offset!==void 0&&(this._serverSubs[e].offset=t.offset)}return}i._handlePublication(t)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){let t={};this._transportSendCommands([t])}e()}_handlePush(e,t){let s=e.channel,i=e.id;e.pub?this._handlePublication(s,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join,i):e.leave?this._handleLeave(s,e.leave,i):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){let e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){let i={code:e,message:t};return s&&(i.temporary=!0),i}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],O(s)&&s({error:this._createErrorObject(1,"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(let 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(let 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])}};P.SubscriptionState=D;P.State=M;P.UnauthorizedError=g;globalThis.Centrifuge=P;})();
//# sourceMappingURL=centrifuge.js.map