var GomsgWidget=function(O){"use strict";var tt=Object.defineProperty;var st=(O,L,w)=>L in O?tt(O,L,{enumerable:!0,configurable:!0,writable:!0,value:w}):O[L]=w;var p=(O,L,w)=>st(O,typeof L!="symbol"?L+"":L,w);class L{constructor(e,t){this.baseUrl=e,this.siteId=t}async getSiteConfig(){const e=await fetch(`${this.baseUrl}/api/widget/${this.siteId}/config`);if(!e.ok)throw new Error(`getSiteConfig failed: ${e.status}`);return e.json()}async startSession(e){const t=e.visitorToken?`?visitor_token=${encodeURIComponent(e.visitorToken)}`:"",s=await fetch(`${this.baseUrl}/api/widget/${this.siteId}/session${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e.displayName,email:e.email,referrer:e.referrer})});if(!s.ok)throw new Error(`startSession failed: ${s.status}`);return s.json()}async listMessages(e,t=50){const s=await fetch(`${this.baseUrl}/api/widget/messages?limit=${t}`,{headers:{Authorization:`Visitor ${e}`}});if(!s.ok)throw new Error(`listMessages failed: ${s.status}`);return s.json()}async sendMessage(e,t,s){const i=await fetch(`${this.baseUrl}/api/widget/messages`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Visitor ${e}`},body:JSON.stringify({chat_id:t,content:s})});if(!i.ok)throw new Error(`sendMessage failed: ${i.status}`);return i.json()}async identify(e,t){const s=await fetch(`${this.baseUrl}/api/widget/identify`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Visitor ${e}`},body:JSON.stringify(t)});if(!s.ok)throw new Error(`identify failed: ${s.status}`)}async ping(e,t){await fetch(`${this.baseUrl}/api/widget/ping`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Visitor ${e}`},body:JSON.stringify({page:t})})}async requestHandoff(e){const t=await fetch(`${this.baseUrl}/api/widget/handoff`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Visitor ${e}`}});if(!t.ok&&t.status!==204)throw new Error(`handoff failed: ${t.status}`)}}function w(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(f){try{d(s.next(f))}catch(E){o(E)}}function h(f){try{d(s.throw(f))}catch(E){o(E)}}function d(f){f.done?n(f.value):i(f.value).then(a,h)}d((s=s.apply(r,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;function ve(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var V={exports:{}},ne;function Se(){if(ne)return V.exports;ne=1;var r=typeof Reflect=="object"?Reflect:null,e=r&&typeof r.apply=="function"?r.apply:function(l,u,_){return Function.prototype.apply.call(l,u,_)},t;r&&typeof r.ownKeys=="function"?t=r.ownKeys:Object.getOwnPropertySymbols?t=function(l){return Object.getOwnPropertyNames(l).concat(Object.getOwnPropertySymbols(l))}:t=function(l){return Object.getOwnPropertyNames(l)};function s(c){console&&console.warn&&console.warn(c)}var i=Number.isNaN||function(l){return l!==l};function n(){n.init.call(this)}V.exports=n,V.exports.once=z,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(c){if(typeof c!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof c)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(c){if(typeof c!="number"||c<0||i(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");o=c}}),n.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},n.prototype.setMaxListeners=function(l){if(typeof l!="number"||l<0||i(l))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+l+".");return this._maxListeners=l,this};function h(c){return c._maxListeners===void 0?n.defaultMaxListeners:c._maxListeners}n.prototype.getMaxListeners=function(){return h(this)},n.prototype.emit=function(l){for(var u=[],_=1;_0&&(m=u[0]),m instanceof Error)throw m;var M=new Error("Unhandled error."+(m?" ("+m.message+")":""));throw M.context=m,M}var G=S[l];if(G===void 0)return!1;if(typeof G=="function")e(G,this,u);else for(var ye=G.length,et=v(G,ye),_=0;_0&&m.length>g&&!m.warned){m.warned=!0;var M=new Error("Possible EventEmitter memory leak detected. "+m.length+" "+String(l)+" listeners added. Use emitter.setMaxListeners() to increase limit");M.name="MaxListenersExceededWarning",M.emitter=c,M.type=l,M.count=m.length,s(M)}return c}n.prototype.addListener=function(l,u){return d(this,l,u,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(l,u){return d(this,l,u,!0)};function f(){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 E(c,l,u){var _={fired:!1,wrapFn:void 0,target:c,type:l,listener:u},g=f.bind(_);return g.listener=u,_.wrapFn=g,g}n.prototype.once=function(l,u){return a(u),this.on(l,E(this,l,u)),this},n.prototype.prependOnceListener=function(l,u){return a(u),this.prependListener(l,E(this,l,u)),this},n.prototype.removeListener=function(l,u){var _,g,S,m,M;if(a(u),g=this._events,g===void 0)return this;if(_=g[l],_===void 0)return this;if(_===u||_.listener===u)--this._eventsCount===0?this._events=Object.create(null):(delete g[l],g.removeListener&&this.emit("removeListener",l,_.listener||u));else if(typeof _!="function"){for(S=-1,m=_.length-1;m>=0;m--)if(_[m]===u||_[m].listener===u){M=_[m].listener,S=m;break}if(S<0)return this;S===0?_.shift():T(_,S),_.length===1&&(g[l]=_[0]),g.removeListener!==void 0&&this.emit("removeListener",l,M||u)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(l){var u,_,g;if(_=this._events,_===void 0)return this;if(_.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_[l]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _[l]),this;if(arguments.length===0){var S=Object.keys(_),m;for(g=0;g=0;g--)this.removeListener(l,u[g]);return this};function I(c,l,u){var _=c._events;if(_===void 0)return[];var g=_[l];return g===void 0?[]:typeof g=="function"?u?[g.listener||g]:[g]:u?P(g):v(g,g.length)}n.prototype.listeners=function(l){return I(this,l,!0)},n.prototype.rawListeners=function(l){return I(this,l,!1)},n.listenerCount=function(c,l){return typeof c.listenerCount=="function"?c.listenerCount(l):y.call(c,l)},n.prototype.listenerCount=y;function y(c){var l=this._events;if(l!==void 0){var u=l[c];if(typeof u=="function")return 1;if(u!==void 0)return u.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function v(c,l){for(var u=new Array(l),_=0;_31&&(r=31);const s=Pe(0,Math.min(t,e*Math.pow(2,r)));return Math.min(t,e+s)}function xe(r){return"error"in r&&r.error!==null}function W(r){return Math.min(r*1e3,2147483647)}var C;(function(r){r[r.Live=0]="Live",r[r.Stream=1]="Stream",r[r.State=2]="State"})(C||(C={}));class X extends re{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=R.Unsubscribed,this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._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===R.Unsubscribed?Promise.reject({code:b.subscriptionUnsubscribed,message:this.state}):this.state===R.Subscribed?Promise.resolve():new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(function(){s({code:b.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(H.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(F.unsubscribeCalled,"unsubscribe called",!0)}_debouncedPublish(e,t,s){const i=this._debouncePending.get(e);if(i)return i.data=t,i.dirty=!0,Promise.resolve({});const n={data:t,dirty:!1,timer:null};return n.timer=setTimeout(()=>{const a=this._debouncePending.get(e);if(!a||!a.dirty){this._debouncePending.delete(e);return}a.dirty=!1;const h=a.data;(s?this._centrifuge.mapPublish(this.channel,e,h):this._centrifuge.publish(this.channel,h)).catch(()=>{}),a.timer=setTimeout(()=>{const f=this._debouncePending.get(e);if(!f||!f.dirty){this._debouncePending.delete(e);return}this._debouncePending.delete(e),this._debouncedPublish(e,f.data,s)},this._debounceMs)},this._debounceMs),this._debouncePending.set(e,n),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 w(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return w(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:b.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const s=this._centrifuge._config.timeout,i=setTimeout(()=>{t({code:b.timeout,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===R.Unsubscribed}_isSubscribing(){return this.state===R.Subscribing}_isSubscribed(){return this.state===R.Subscribed}_setState(e){if(this.state!==e){const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return this._token!==""||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){const i=e.epoch||"";if(this._sharedPollEpoch!==""&&this._sharedPollEpoch!==i)for(const n of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(n,0);this._sharedPollEpoch=i}this._setState(R.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const s=e.publications;if(s&&s.length>0)for(const i in s)s.hasOwnProperty(i)&&this._handlePublication(s[i]);e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),W(e.ttl)))}_setSubscribing(e,t){return w(this,void 0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._id=0,this._setState(R.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._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:b.subscriptionGetState,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 U){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:b.badConfiguration,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 U){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:b.subscriptionSubscribeToken,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(s=>{this._inflight=!1;const 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){const 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=$.channelCompaction,this._getState&&(t.flag|=$.rejectUnrecovered),this._needRecover()){t.recover=!0;const s=this._getOffset();s&&(t.offset=s);const 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===b.timeout){this._centrifuge._disconnect(D.subscribeTimeout,"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(R.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:b.subscriptionUnsubscribed,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){const s=(this._map||this._sharedPoll)&&e.key||"",{newData:i,newPrevValue:n,isDelta:o,wireBytes:a,fullBytes:h}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(s));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=a,this._deltaBytesDecoded+=h,o?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(s):this._prevValueMap.set(s,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 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"){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()){this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);return}const e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||e.code===109||e.temporary===!0){e.code===109&&(this._token="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===x.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=B(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(){const e=this._offset;return e!==null?e:0}_getEpoch(){const 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);const e={channel:this.channel},t=this._getToken;return t===null?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:b.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new U(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t){e._failUnauthorized();return}e._token=t;const i={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(i).then(n=>{const o=n.reply.sub_refresh;e._refreshResponse(o),n.next&&n.next()},n=>{e._refreshError(n.error),n.next&&n.next()})}).catch(function(t){if(t instanceof U){e._failUnauthorized();return}e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:b.subscriptionRefreshToken,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(),W(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 B(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(F.unauthorized,"unauthorized",!0)}_sendTrackRequest(e,t){if(e.length===0)return Promise.resolve();const s=6e4,i=[];let n=[],o=100;if(t&&t.length>0)for(const h of t)o+=h.length+4;for(const h of e){let d=100;for(const f of h.items)d+=f.key.length+16;n.length>0&&o+d>s&&(i.push(n),n=[],o=100),n.push(h),o+=d}n.length>0&&i.push(n);const a=(h,d)=>new Promise((f,E)=>{const I={channel:this.channel,type:1,track:h.map(v=>({signature:v.signature,items:v.items.map(T=>T.version>0?T:{key:T.key})}))};d&&d.length>0&&(I.untrack=d);const y={sub_refresh:I};this._centrifuge._call(y).then(v=>{this._handleTrackResponse(v.reply.sub_refresh),v.next&&v.next(),f()},v=>{v.next&&v.next(),E(v.error)})});return i.reduce((h,d,f)=>h.then(()=>a(d,f===0?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(o=>{o.next&&o.next(),t()},o=>{o.next&&o.next(),s(o.error)})})}_handleTrackResponse(e){if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(const t of e.items)this._handlePublication(t);if(e&&e.expires===!0&&e.ttl>0){const 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(),B(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;const e=Array.from(this._sharedPollTrackedItems.keys()),t=this;this._sharedPollGetSignature({keys:e}).then(s=>{if(t._sharedPollSignatureRefreshInFlight=!1,!t._isSubscribed())return;t._sharedPollSignatureRefreshAttempts=0;const i=new Set(s.keys),n=[];for(const d of e)i.has(d)||(t._sharedPollTrackedItems.delete(d),n.push(d),t.emit("update",{channel:t.channel,key:d,data:null,removed:!0}));n.length>0&&t._sendUntrackRequest(n).catch(d=>{t.emit("error",{type:"untrack",channel:t.channel,error:d})});const o=[];for(const d of s.keys){const f=t._sharedPollTrackedItems.get(d);f!==void 0&&o.push({key:d,version:f})}const a=new Set(s.keys),h=t._sharedPollSignatures.filter(d=>d.keys.some(f=>t._sharedPollTrackedItems.has(f)&&!a.has(f)));t._sharedPollSignatures=o.length>0?[{keys:s.keys,signature:s.signature},...h]:h,o.length!==0&&t._sendTrackRequest([{items:o,signature:s.signature}]).catch(d=>{t._handleTrackError(d)})}).catch(s=>{t._sharedPollSignatureRefreshInFlight=!1,t.emit("error",{type:"signatureRefresh",channel:t.channel,error:{code:b.sharedPollGetSignature,message:s!==void 0?s.toString():""}}),t._sharedPollSignatureRefreshTimeout=setTimeout(()=>t._sharedPollRefreshSignature(),B(t._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed()||this._sharedPollTrackedItems.size===0&&this._sharedPollSignatures.length===0)return;const e=new Set,t=[],s=[];for(const o of this._sharedPollSignatures){const a=o.keys.map(h=>{var d;return{key:h,version:(d=this._sharedPollTrackedItems.get(h))!==null&&d!==void 0?d:0}});t.push({items:a,signature:o.signature});for(const h of o.keys)this._sharedPollTrackedItems.has(h)?e.add(h):s.push(h)}t.length>0&&this._sendTrackRequest(t,s).catch(o=>{this._handleTrackError(o)});const i=[];for(const o of this._sharedPollTrackedItems.keys())e.has(o)||i.push(o);if(i.length===0)return;if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:"getSignature callback required for tracked keys without an explicit signature"}});return}const n=this;this._sharedPollGetSignature({keys:i}).then(o=>{if(!n._isSubscribed())return;n._clearSharedPollReplayRetry();const a=new Set(o.keys),h=[];for(const f of i)a.has(f)||(n._sharedPollTrackedItems.delete(f),h.push(f),n.emit("update",{channel:n.channel,key:f,data:null,removed:!0}));h.length>0&&n._sendUntrackRequest(h).catch(f=>{n.emit("error",{type:"untrack",channel:n.channel,error:f})});const d=[];for(const f of o.keys){const E=n._sharedPollTrackedItems.get(f);E!==void 0&&d.push({key:f,version:E})}d.length!==0&&(n._sharedPollSignatures.push({keys:o.keys,signature:o.signature}),n._sendTrackRequest([{items:d,signature:o.signature}]).catch(f=>{n._handleTrackError(f)}))}).catch(o=>{n.emit("error",{type:"signatureRefresh",channel:n.channel,error:{code:b.sharedPollGetSignature,message:o!==void 0?o.toString():""}}),n._sharedPollReplayRetryTimeout=setTimeout(()=>n._sharedPollReplayTrack(),B(n._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=C.State,this._recover&&this._offset!==null&&this._epoch!==null){this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=C.Stream,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}const t=this._buildMapSubscribeCommand(C.State,e);this._debug("map subscribe: fetching snapshot page",e?`cursor=${e}`:"initial"),this._centrifuge._call(t).then(s=>{const 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(const 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=C.Stream,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}const e=this._buildMapSubscribeCommand(C.Stream);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(e).then(t=>{const 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=C.State,this._fetchSnapshot();return}if(e.publications&&e.publications.length>0)for(const 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=C.State,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(const s of e.state)this._seedDeltaTracking(s),this._mapStateBuffer.push(this._getMapUpdateContext(s));if(e.publications&&e.publications.length>0)for(const s of e.publications){if(this._delta&&e.delta){const i=s.key||"",{newData:n,newPrevValue:o,isDelta:a,wireBytes:h,fullBytes:d}=this._centrifuge._codec.applyDeltaIfNeeded(s,this._prevValueMap.get(i));s.data=n,this._deltaNumPubs++,this._deltaBytesReceived+=h,this._deltaBytesDecoded+=d,a?this._deltaNumDelta++:this._deltaNumFull++,s.removed?this._prevValueMap.delete(i):this._prevValueMap.set(i,o)}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(R.Subscribed);const 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){const s=new Map;for(const i of this._mapStateBuffer)s.set(i.key,i);for(const 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(const 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(),W(e.ttl)))}_handleMapSubscribeError(e){if(this._inflight=!1,!!this._isSubscribing()){if(e.code===b.timeout){this._centrifuge._disconnect(D.subscribeTimeout,"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){const 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=$.channelCompaction,e===C.State&&(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===C.Stream&&(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){const 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){const 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}}class Ee extends X{publish(e){return w(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 w(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}}class Z extends X{publish(e,t){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish(e,t,!0):this._centrifuge.mapPublish(this.channel,e,t)})}remove(e){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._cancelDebounce(e),this._centrifuge.mapRemove(this.channel,e)})}}class Re extends X{track(e,t){if(e.length===0)return;let s;const i=t;typeof e[0]=="string"?s=e.map(a=>({key:a,version:0})):s=e;for(const o of s){const a=this._sharedPollTrackedItems.get(o.key);(a===void 0||o.version>a)&&this._sharedPollTrackedItems.set(o.key,o.version)}if(i!==void 0){this._sharedPollSignatures.push({keys:s.map(o=>o.key),signature:i}),this._isSubscribed()&&this._sendTrackRequest([{items:s,signature:i}]).catch(o=>{this._handleTrackError(o)});return}if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:"getSignature callback required for track(keys)"}});return}if(!this._isSubscribed())return;const n=s.map(o=>o.key);this._sharedPollGetSignature({keys:n}).then(o=>{if(!this._isSubscribed())return;const a=new Set(o.keys),h=[];for(const f of n)a.has(f)||(this._sharedPollTrackedItems.delete(f),h.push(f),this.emit("update",{channel:this.channel,key:f,data:null,removed:!0}));h.length>0&&this._sendUntrackRequest(h).catch(f=>{this.emit("error",{type:"untrack",channel:this.channel,error:f})});const d=[];for(const f of o.keys){const E=this._sharedPollTrackedItems.get(f);E!==void 0&&d.push({key:f,version:E})}d.length!==0&&(this._sharedPollSignatures.push({keys:o.keys,signature:o.signature}),this._sendTrackRequest([{items:d,signature:o.signature}]).catch(f=>{this._handleTrackError(f)}))}).catch(o=>{this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:o!==void 0?o.toString():"getSignature failed"}})})}untrack(e){for(const t of e)this._sharedPollTrackedItems.delete(t);this._sharedPollSignatures=this._sharedPollSignatures.filter(t=>t.keys.some(s=>this._sharedPollTrackedItems.has(s))),this._isSubscribed()&&this._sendUntrackRequest(e).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}}class Ie{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 this.options.sockjs!==null}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=s=>{t.onError(s)},this._transport.onclose=s=>{t.onClose(s)},this._transport.onmessage=s=>{t.onMessage(s.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class ae{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return this.options.websocket!==void 0&&this.options.websocket!==null}initialize(e,t){let s="";e==="protobuf"&&(s="centrifuge-protobuf"),s!==""?this._transport=new this.options.websocket(this.endpoint,s):this._transport=new this.options.websocket(this.endpoint),e==="protobuf"&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=i=>{t.onError(i)},this._transport.onclose=i=>{t.onClose(i)},this._transport.onmessage=i=>{t.onMessage(i.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class Ce{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 i=new EventTarget,n=e.options.fetch;return n(t,s).then(e._handleErrors).then(o=>{i.dispatchEvent(new Event("open"));let a="",h=0,d=new Uint8Array;const f=o.body.getReader();return new e.options.readableStream({start(E){function I(){return f.read().then(({done:y,value:v})=>{if(y){i.dispatchEvent(new Event("close")),E.close();return}try{if(e._protocol==="json")for(a+=e._utf8decoder.decode(v);h{i.dispatchEvent(new Event("error",{detail:o})),i.dispatchEvent(new Event("close"))}),i}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(e,t,s){this._protocol=e,this._abortController=new AbortController;let i,n;e==="json"?(i={Accept:"application/json","Content-Type":"application/json"},n=s):(i={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=s);const o={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},a=this._fetchEventTarget(this,this.endpoint,o);a.addEventListener("open",()=>{t.onOpen()}),a.addEventListener("error",h=>{this._abortController.abort(),t.onError(h)}),a.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),a.addEventListener("message",h=>{t.onMessage(h.data)})}close(){this._abortController.abort()}send(e,t,s){let i,n;const o={session:t,node:s,data:e};this._protocol==="json"?(i={"Content-Type":"application/json"},n=JSON.stringify(o)):(i={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(o));const a=this.options.fetch,h={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,h)}}class Me{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 this.options.eventsource!==null&&this.options.fetch!==null}initialize(e,t,s){let i;globalThis&&globalThis.document&&globalThis.document.baseURI?i=new URL(this.endpoint,globalThis.document.baseURI):i=new URL(this.endpoint),i.searchParams.append("cf_connect",s);const n={},o=new this.options.eventsource(i.toString(),n);this._transport=o;const a=this;o.onopen=function(){t.onOpen()},o.onerror=function(h){o.close(),t.onError(h),t.onClose({code:4,reason:"connection closed"})},o.onmessage=function(h){t.onMessage(h.data)},a._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),this._onClose!==null&&this._onClose()}send(e,t,s){const i={session:t,node:s,data:e},n={"Content-Type":"application/json"},o=JSON.stringify(i),a=this.options.fetch,h={method:"POST",headers:n,body:o,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,h)}}class Oe{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 this.options.webtransport!==void 0&&this.options.webtransport!==null}initialize(e,t){return w(this,void 0,void 0,function*(){let s;globalThis&&globalThis.document&&globalThis.document.baseURI?s=new URL(this.endpoint,globalThis.document.baseURI):s=new URL(this.endpoint),e==="protobuf"&&s.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const i=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch{this.close();return}let n;try{n=yield this._transport.createBidirectionalStream()}catch{this.close();return}this._stream=n,this._writer=this._stream.writable.getWriter(),i.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),i.addEventListener("message",o=>{t.onMessage(o.data)}),this._startReading(i),t.onOpen()})}_startReading(e){return w(this,void 0,void 0,function*(){const t=this._stream.readable.getReader();let s="",i=0,n=new Uint8Array;try{for(;;){const{done:o,value:a}=yield t.read();if(a.length>0)if(this._protocol==="json")for(s+=this._utf8decoder.decode(a);ithis.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e=0,t;for(;this.haveBytes()&&(t=Le[127&this.getByte()])>=0;)e=(e<<6)+t;return this.pos--,e>>>0}}class Ue{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,s){for(let i=t;i=16;)e=e+r[n+0]|0,t=t+r[n+1]|0,s=s+r[n+2]|0,i=i+r[n+3]|0,e=e+r[n+4]|0,t=t+r[n+5]|0,s=s+r[n+6]|0,i=i+r[n+7]|0,e=e+r[n+8]|0,t=t+r[n+9]|0,s=s+r[n+10]|0,i=i+r[n+11]|0,e=e+r[n+12]|0,t=t+r[n+13]|0,s=s+r[n+14]|0,i=i+r[n+15]|0,n+=16,o-=16;for(;o>=4;)e=e+r[n+0]|0,t=t+r[n+1]|0,s=s+r[n+2]|0,i=i+r[n+3]|0,n+=4,o-=4;switch(i=((i+(s<<8)|0)+(t<<16)|0)+(e<<24)|0,o){case 3:i=i+(r[n+2]<<8)|0;case 2:i=i+(r[n+1]<<16)|0;case 1:i=i+(r[n+0]<<24)|0}return i>>>0}function Be(r,e){let t=0;const s=new De(e),i=r.length,n=e.length,o=s.getInt();if(s.getChar()!==` `)throw new Error("size integer not terminated by '\\n'");const a=new Ue;for(;s.haveBytes();){const h=s.getInt();let d;switch(s.getChar()){case"@":if(d=s.getInt(),s.haveBytes()&&s.getChar()!==",")throw new Error("copy command not terminated by ','");if(t+=h,t>o)throw new Error("copy exceeds output file size");if(d+h>i)throw new Error("copy extends past end of input");a.putArray(r,d,d+h);break;case":":if(t+=h,t>o)throw new Error("insert command gives an output larger than predicted");if(h>n)throw new Error("insert count exceeds size of delta");a.putArray(s.a,s.pos,s.pos+h),s.pos+=h;break;case";":{const f=a.toByteArray(r);if(h!==Ae(f))throw new Error("bad checksum");if(t!==o)throw new Error("generated size does not match predicted size");return f}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class he{name(){return"json"}encodeCommands(e){return e.map(t=>JSON.stringify(t)).join(` `)}decodeReplies(e){return e.trim().split(` `).map(t=>JSON.parse(t))}applyDeltaIfNeeded(e,t){let s,i,n;if(e.delta){n=!0;const o=new TextEncoder().encode(e.data),a=Be(t,o);s=JSON.parse(new TextDecoder().decode(a)),i=a}else n=!1,s=JSON.parse(e.data),i=new TextEncoder().encode(e.data);return{newData:s,newPrevValue:i,isDelta:n,wireBytes:e.data.length,fullBytes:i.length}}}const ze={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 U extends Error{constructor(e){super(e),this.name=this.constructor.name}}class J extends re{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=x.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 he,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({},ze),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");const s=new Ee(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");const s=new Z(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");const s=new Z(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");const s=new Z(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");const s=new Re(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!==R.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}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))s.type==="map"&&(e[t]=s);return e}sharedPollSubscriptions(){const e={};for(const[t,s]of Object.entries(this._subs))s.type==="shared_poll"&&(e[t]=s);return e}ready(e){return w(this,void 0,void 0,function*(){switch(this.state){case x.Disconnected:throw{code:b.clientDisconnected,message:"client disconnected"};case x.Connected:return;default:return new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(()=>{s({code:b.timeout,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(j.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return w(this,void 0,void 0,function*(){const t={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(b.transportWriteError,"transport write error")})}rpc(e,t){return w(this,void 0,void 0,function*(){const s={rpc:{method:e,data:t}};return yield this._methodCall(),{data:(yield this._callPromise(s,n=>n.rpc)).data}})}publish(e,t){return w(this,void 0,void 0,function*(){const s={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}mapPublish(e,t,s){return w(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:t,data:s}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,t){return w(this,void 0,void 0,function*(){const s={publish:{channel:e,type:1,key:t,removed:!0}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}history(e,t){return w(this,void 0,void 0,function*(){const s={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(s,o=>o.history),n=[];if(i.publications)for(let o=0;on.presence)).presence;for(const n in i)if(Object.prototype.hasOwnProperty.call(i,n)){const o=i[n],a=o.conn_info,h=o.chan_info;a&&(o.connInfo=a),h&&(o.chanInfo=h)}return{clients:i}})}presenceStats(e){return w(this,void 0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const s=yield this._callPromise(t,i=>i.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&&ke("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 he,this._formatOverride(),(this._config.debug===!0||typeof localStorage<"u"&&typeof localStorage.getItem=="function"&&localStorage.getItem("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(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)}}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;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===x.Disconnected}_isConnecting(){return this.state===x.Connecting}_isConnected(){return this.state===x.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===x.Connected||this.state===x.Connecting)&&(this._disconnect(D.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===x.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=B(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const s=t.errback;if(!s)continue;s({error:this._createErrorObject(b.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===R.Subscribed&&t._setSubscribing(H.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const s=t.id;if(!(s in this._callbacks))continue;const i=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s];const n=i.errback;n({error:this._createErrorObject(b.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;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 n=null;if(this._config.readableStream!==null?n=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let y=0;for(;;){if(y>=this._transports.length)throw new Error("no supported transport found");const v=this._transports[this._currentTransportIndex],T=v.transport,P=v.endpoint;if(T==="websocket"){if(this._debug("trying websocket transport"),this._transport=new ae(P,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,y++;continue}}else if(T==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new Oe(P,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,y++;continue}}else if(T==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new Ce(P,{fetch:i,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,y++;continue}}else if(T==="sse"){if(this._debug("trying sse transport"),this._transport=new Me(P,{eventsource:s,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,y++;continue}}else if(T==="sockjs"){if(this._debug("trying sockjs"),this._transport=new Ie(P,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,y++;continue}}else throw new Error("unknown transport "+T);break}}else{if(Te(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 ae(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")}const o=this,a=this._transport,h=this._nextTransportId();o._debug("id of transport",h);let d=!1;const f=[];if(this._transport.emulation()){const y=o._sendConnect(!0);f.push(y)}this._setNetworkEvents();const E=this._codec.encodeCommands(f);this._transportClosed=!1;let I;I=setTimeout(function(){a.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(I&&(clearTimeout(I),I=null),o._transportId!=h){o._debug("open callback from non-actual transport"),a.close();return}d=!0,o._debug(a.subName(),"transport open"),!a.emulation()&&(o._transportIsOpen=!0,o._transportWasOpen=!0,o.startBatching(),o._sendConnect(!1),o._sendSubscribeCommands(),o.stopBatching(),o.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(y){if(o._transportId!=h){o._debug("error callback from non-actual transport");return}o._debug("transport level error",y)},onClose:function(y){if(I&&(clearTimeout(I),I=null),o._transportId!=h){o._debug("close callback from non-actual transport");return}o._debug(a.subName(),"transport closed"),o._transportClosed=!0,o._transportIsOpen=!1;let v="connection closed",T=!0,P=0;if(y&&"code"in y&&y.code&&(P=y.code),y&&y.reason)try{const z=JSON.parse(y.reason);v=z.reason,T=z.reconnect}catch{v=y.reason,(P>=3500&&P<4e3||P>=4500&&P<5e3)&&(T=!1)}P<3e3?(P===1009?(P=j.messageSizeLimit,v="message size limit exceeded",T=!1):(P=D.transportClosed,v="transport closed"),o._emulation&&!o._transportWasOpen&&(o._currentTransportIndex++,o._currentTransportIndex>=o._transports.length&&(o._triedAllTransports=!0,o._currentTransportIndex=0))):o._transportWasOpen=!0,o._isConnecting()&&!d&&o.emit("error",{type:"transport",error:{code:b.transportClosed,message:"transport closed"},transport:a.name()}),o._reconnecting=!1,o._disconnect(P,v,T)},onMessage:function(y){o._dataReceived(y)}},E),o.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),s=this;return this._call(t,e).then(i=>{const n=i.reply.connect;s._connectResponse(n),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;const 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}const 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(n){s._isConnecting()&&(s._data=n,s._initializeTransport())}).catch(n=>s._handleGetDataError(n)):s._initializeTransport()}}).catch(function(i){if(!s._isConnecting())return;if(i instanceof U){s._failUnauthorized();return}s.emit("error",{type:"connectToken",error:{code:b.clientConnectToken,message:i!==void 0?i.toString():""}});const n=s._getReconnectDelay();s._debug("error on getting connection token, reconnect after "+n+" milliseconds",i),s._reconnecting=!1,s._reconnectTimeout=setTimeout(()=>{s._startReconnecting()},n)})}_handleGetDataError(e){if(e instanceof U){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:b.badConfiguration,message:e?.toString()||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===x.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(){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 i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;const n={recover:!0};this._serverSubs[i].offset&&(n.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(n.epoch=this._serverSubs[i].epoch),t[i]=n}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const 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)=>{const s=setTimeout(function(){t({code:b.timeout,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(n=>{var o;const a=t(n.reply);s(a),(o=n.next)===null||o===void 0||o.call(n)},n=>{var o;i(n.error),(o=n.next)===null||o===void 0||o.call(n)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const 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(const i in e)e.hasOwnProperty(i)&&(s=s.then(()=>this._dispatchReply(e[i])));s=s.then(()=>{t()})}_dispatchReply(e){let t;const s=new Promise(n=>{t=n});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),s;const 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(x.Connecting)&&this.emit("connecting",{code:D.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(e===j.stateInvalidated){this._token="",this._refreshRequired=!0;for(const a in this._subs)this._subs.hasOwnProperty(a)&&this._subs[a]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const n={code:e,reason:t};let o=!1;if(s?o=this._setState(x.Connecting):(o=this._setState(x.Disconnected),this._rejectPromises({code:b.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===x.Connecting&&this._clearReconnectTimeout(),i===x.Connected&&this._clearConnectedState(),o&&(this._isConnecting()?this.emit("connecting",n):this.emit("disconnected",n)),this._transport){this._debug("closing existing transport");const a=this._transport;this._transport=null,a.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(j.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:b.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new U("")))}_refresh(){const 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;const i={refresh:{token:t._token}};t._call(i,!1).then(n=>{const o=n.reply.refresh;t._refreshResponse(o),n.next&&n.next()},n=>{t._refreshError(n.error),n.next&&n.next()})}).catch(function(s){if(t._isConnected()){if(s instanceof U){t._failUnauthorized();return}t.emit("error",{type:"refreshToken",error:{code:b.clientRefreshToken,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 B(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),W(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const s={unsubscribe:{channel:e.channel}},i=this;return new Promise((o,a)=>{this._call(s,!1).then(h=>{o(),h.next&&h.next()},h=>{o(),h.next&&h.next(),i._disconnect(D.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const n=this._subs[i];if(n._id===t)return n}return null}const s=this._subs[e];return s||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const s=this._subs[t];if(s._inflight!==!0&&s.state===R.Subscribing){const 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(x.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),W(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,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 i=this._getSubscribeContext(t,s);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];if(s.recovered){const i=s.publications;if(i&&i.length>0)for(const n in i)i.hasOwnProperty(n)&&this._handlePublication(t,i[n])}}for(const 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(D.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 i="";"epoch"in t&&(i=t.epoch);let n=0;return"offset"in t&&(n=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:n,epoch:i}),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)){t();return}const i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],xe(e)){const n=i.errback;if(!n){t();return}const o={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};n({error:o,next:t})}else{const n=i.callback;if(!n)return;n({reply:e,next:t})}}_handleJoin(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",n)}return}i._handleJoin(t)}_handleLeave(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",n)}return}i._handleLeave(t)}_handleUnsubscribe(e,t){const 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===F.stateInvalidated&&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){const t=e.code;let s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),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 i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n=this._getPublicationContext(e,t);this.emit("publication",n),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){const t={};this._transportSendCommands([t])}e()}_handlePush(e,t){const 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(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){const 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],oe(s)&&s({error:this._createErrorObject(b.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])}}J.SubscriptionState=R,J.State=x,J.UnauthorizedError=U;const je=5e3,Ne=3e4,Fe=2500;class $e{constructor(e,t,s=""){p(this,"listeners",new Map);p(this,"centrifuge",null);p(this,"subscription",null);p(this,"pollTimer",null);p(this,"lastSeenId",null);p(this,"wsState","idle");p(this,"wsTimeoutTimer",null);p(this,"wsRetryTimer",null);p(this,"destroyed",!1);this.centrifugoUrl=e,this.chatId=t,this.centrifugoToken=s}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}emit(e,t){this.listeners.get(e)?.forEach(s=>{try{s(t)}catch(i){console.error("[gomsg-widget] listener error",i)}})}start(){this.tryWebSocket()}tryWebSocket(){this.destroyed||this.wsState==="connecting"||this.wsState==="connected"||(this.wsState="connecting",this.wsRetryTimer&&(clearTimeout(this.wsRetryTimer),this.wsRetryTimer=null),this.wsTimeoutTimer=setTimeout(()=>{this.wsState!=="connected"&&(console.warn("[gomsg-widget] WS connect timeout — falling back to polling"),this.teardownWebSocket(),this.wsState="failed",this.startPolling(Q),this.scheduleWsRetry())},je),this.centrifuge=new J(this.centrifugoUrl,{token:this.centrifugoToken}),this.centrifuge.on("connected",()=>{this.destroyed||(console.info("[gomsg-widget] WS connected to Centrifugo"),this.wsState="connected",this.wsTimeoutTimer&&(clearTimeout(this.wsTimeoutTimer),this.wsTimeoutTimer=null),this.stopPolling(),this.emit("connected",null))}),this.centrifuge.on("disconnected",()=>{this.destroyed||(console.warn("[gomsg-widget] WS disconnected"),this.wsState="failed",this.emit("closed",null),this.startPolling(Q),this.scheduleWsRetry())}),this.centrifuge.on("error",e=>{console.warn("[gomsg-widget] WS error",e)}),this.subscription=this.centrifuge.newSubscription(`chat:${this.chatId}`,{}),this.subscription.on("publication",e=>{const t=e?.data;t&&this.emit("message",t)}),this.subscription.on("subscribed",()=>{console.info("[gomsg-widget] subscribed to chat:"+this.chatId)}),this.subscription.on("error",e=>{console.warn("[gomsg-widget] subscription error",e)}),this.subscription.subscribe(),this.centrifuge.connect())}teardownWebSocket(){try{this.subscription?.unsubscribe(),this.subscription=null}catch{}try{this.centrifuge?.disconnect(),this.centrifuge=null}catch{}}scheduleWsRetry(){this.destroyed||this.wsRetryTimer||(this.wsRetryTimer=setTimeout(()=>{this.wsRetryTimer=null,!this.destroyed&&this.wsState!=="connected"&&this.tryWebSocket()},Ne))}startPolling(e){if(this.pollTimer)return;const t=async()=>{try{const s=await e();if(s.length===0)return;if(this.lastSeenId===null){this.lastSeenId=s[0].id;return}const i=s.findIndex(o=>o.id===this.lastSeenId),n=i===-1?s:s.slice(0,i);if(n.length===0)return;this.lastSeenId=n[0].id;for(let o=n.length-1;o>=0;o--)this.emit("message",n[o])}catch{}};t(),this.pollTimer=setInterval(t,Fe)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}disconnect(){this.destroyed=!0,this.stopPolling(),this.wsTimeoutTimer&&clearTimeout(this.wsTimeoutTimer),this.wsRetryTimer&&clearTimeout(this.wsRetryTimer),this.wsTimeoutTimer=null,this.wsRetryTimer=null,this.teardownWebSocket(),this.listeners.clear()}}let Q=async()=>[];function We(r){Q=r}const ee=r=>`gomsg:${r}:visitor_token`,te=r=>`gomsg:${r}:open`,le=r=>`gomsg:${r}:launcher_pos`,ce=r=>`gomsg:${r}:panel_pos`,A={getVisitorToken(r){try{return localStorage.getItem(ee(r))}catch{return null}},setVisitorToken(r,e){try{localStorage.setItem(ee(r),e)}catch{}},clearVisitorToken(r){try{localStorage.removeItem(ee(r))}catch{}},getIsOpen(r){try{return localStorage.getItem(te(r))==="1"}catch{return!1}},setIsOpen(r,e){try{e?localStorage.setItem(te(r),"1"):localStorage.removeItem(te(r))}catch{}},getLauncherPos(r){try{const e=localStorage.getItem(le(r));if(!e)return null;const t=JSON.parse(e);return typeof t.x=="number"&&typeof t.y=="number"?t:null}catch{return null}},setLauncherPos(r,e){try{localStorage.setItem(le(r),JSON.stringify(e))}catch{}},getPanelPos(r){try{const e=localStorage.getItem(ce(r));if(!e)return null;const t=JSON.parse(e);return typeof t.x=="number"&&typeof t.y=="number"?t:null}catch{return null}},setPanelPos(r,e){try{localStorage.setItem(ce(r),JSON.stringify(e))}catch{}}},K=60,N=6,qe=4;class Ge{constructor(e,t,s,i){p(this,"el");p(this,"pulseTimer",null);p(this,"pos");p(this,"pointerStart",null);p(this,"hasDragged",!1);this.color=e,this.onClick=s,this.onPositionChange=i,this.pos={...t},this.el=document.createElement("button"),this.el.type="button",this.el.setAttribute("aria-label","Open chat"),this.el.className="gomsg-launcher",this.el.innerHTML=de(),this.el.style.touchAction="none",this.applyStyles(),this.applyPos(),this.setupDrag()}mount(e){e.appendChild(this.el)}getPosition(){return{...this.pos}}setPosition(e){this.pos=ue(e),this.applyPos()}setUnread(e){const t=this.el.querySelector(".gomsg-badge");if(e>0){if(t)t.textContent=String(e>99?"99+":e);else{const s=document.createElement("span");s.className="gomsg-badge",s.textContent=String(e>99?"99+":e),this.el.appendChild(s)}this.pulseTimer||(this.pulseTimer=setInterval(()=>{this.el.classList.toggle("gomsg-pulse")},1200))}else t?.remove(),this.pulseTimer&&(clearInterval(this.pulseTimer),this.pulseTimer=null),this.el.classList.remove("gomsg-pulse")}setActive(e){this.el.innerHTML=e?Ve():de(),e&&this.setUnread(0)}applyStyles(){if(this.el.setAttribute("style",` position: fixed; width: ${K}px; height: ${K}px; border-radius: 50%; background: ${this.color}; color: #fff; border: none; cursor: grab; box-shadow: 0 6px 20px rgba(0,0,0,0.25); display: flex; align-items: center; justify-content: center; z-index: 2147483000; transition: transform 0.15s ease, box-shadow 0.15s ease; padding: 0; user-select: none; -webkit-user-select: none; touch-action: none; `),this.el.addEventListener("mouseenter",()=>{this.hasDragged||(this.el.style.transform="scale(1.06)")}),this.el.addEventListener("mouseleave",()=>{this.el.style.transform="scale(1)"}),!document.getElementById("gomsg-launcher-styles")){const e=document.createElement("style");e.id="gomsg-launcher-styles",e.textContent=` .gomsg-launcher.gomsg-pulse { box-shadow: 0 0 0 0 ${this.color}aa, 0 6px 20px rgba(0,0,0,0.25); animation: gomsg-keyframe-pulse 1.2s infinite; } @keyframes gomsg-keyframe-pulse { 0% { box-shadow: 0 0 0 0 ${this.color}aa, 0 6px 20px rgba(0,0,0,0.25); } 70% { box-shadow: 0 0 0 14px ${this.color}00, 0 6px 20px rgba(0,0,0,0.25); } 100% { box-shadow: 0 0 0 0 ${this.color}00, 0 6px 20px rgba(0,0,0,0.25); } } .gomsg-launcher.gomsg-dragging { cursor: grabbing !important; transform: scale(1.08) !important; transition: none !important; } .gomsg-badge { position: absolute; top: -4px; right: -4px; min-width: 22px; height: 22px; padding: 0 6px; border-radius: 11px; background: #ff3b30; color: #fff; font-size: 11px; font-weight: 700; line-height: 22px; text-align: center; box-shadow: 0 2px 6px rgba(0,0,0,0.25); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; } `,document.head.appendChild(e)}}applyPos(){this.el.style.left=`${this.pos.x}px`,this.el.style.top=`${this.pos.y}px`}setupDrag(){const e=i=>{if(i.button===0){this.pointerStart={x:i.clientX,y:i.clientY,elX:this.pos.x,elY:this.pos.y},this.hasDragged=!1;try{this.el.setPointerCapture(i.pointerId)}catch{}i.preventDefault()}},t=i=>{if(!this.pointerStart)return;const n=i.clientX-this.pointerStart.x,o=i.clientY-this.pointerStart.y;!this.hasDragged&&Math.abs(n)+Math.abs(o)>qe&&(this.hasDragged=!0,this.el.classList.add("gomsg-dragging")),this.hasDragged&&(this.pos=ue({x:this.pointerStart.elX+n,y:this.pointerStart.elY+o}),this.applyPos(),this.onPositionChange?.(this.pos))},s=i=>{if(this.pointerStart){try{this.el.releasePointerCapture(i.pointerId)}catch{}this.hasDragged?this.onPositionChange?.(this.pos):this.onClick(),this.pointerStart=null,this.hasDragged=!1,this.el.classList.remove("gomsg-dragging")}};this.el.addEventListener("pointerdown",e),this.el.addEventListener("pointermove",t),this.el.addEventListener("pointerup",s),this.el.addEventListener("pointercancel",s)}}function ue(r){const e=Math.max(N,window.innerWidth-K-N),t=Math.max(N,window.innerHeight-K-N);return{x:Math.min(Math.max(r.x,N),e),y:Math.min(Math.max(r.y,N),t)}}function de(){return''}function Ve(){return''}const se=360,ie=540,k=8,q=60;class He{constructor(e,t){p(this,"host");p(this,"shadow");p(this,"root");p(this,"headerEl");p(this,"messagesEl");p(this,"inputEl");p(this,"sendBtn");p(this,"headerTitleEl");p(this,"typingEl");p(this,"identifyFormEl");p(this,"aiFooterEl");p(this,"panelPos",null);p(this,"dragInfo",null);this.site=e,this.handlers=t}mount(e){this.host=document.createElement("div"),this.host.className="gomsg-panel-host",e.appendChild(this.host),this.shadow=this.host.attachShadow({mode:"open"}),this.shadow.innerHTML=Ke(this.site.color),this.root=this.shadow.querySelector(".gomsg-root"),this.headerEl=this.shadow.querySelector(".gomsg-header"),this.messagesEl=this.shadow.querySelector(".gomsg-messages"),this.inputEl=this.shadow.querySelector(".gomsg-input"),this.sendBtn=this.shadow.querySelector(".gomsg-send"),this.headerTitleEl=this.shadow.querySelector(".gomsg-title"),this.typingEl=this.shadow.querySelector(".gomsg-typing"),this.identifyFormEl=this.shadow.querySelector(".gomsg-identify"),this.aiFooterEl=this.shadow.querySelector(".gomsg-ai-footer");const t=this.shadow.querySelector(".gomsg-handoff-btn");t&&t.addEventListener("click",()=>this.handlers.onHandoff?.()),this.headerTitleEl.textContent=this.site.name,(this.site.entry_mode==="anonymous"||this.site.identification_mode==="js_only")&&(this.identifyFormEl.style.display="none"),this.applyAiFooter(),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.inputEl.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSend())}),this.shadow.querySelector(".gomsg-close").addEventListener("click",()=>this.handlers.onClose()),this.shadow.querySelector(".gomsg-identify-submit").addEventListener("click",()=>this.handleIdentify()),this.inputEl.addEventListener("input",()=>{this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`}),this.setupHeaderDrag()}applyAiFooter(){if(!this.aiFooterEl)return;const e=this.site.ai_enabled&&this.site.ai_show_handoff_btn;this.aiFooterEl.style.display=e?"flex":"none"}show(){this.host.style.display="block",requestAnimationFrame(()=>{this.root.classList.add("gomsg-open"),this.scrollMessagesToBottom(),setTimeout(()=>this.inputEl.focus(),200)})}hide(){this.root.classList.remove("gomsg-open"),setTimeout(()=>{this.host.style.display="none"},220)}anchorToLauncher(e){const t=this.panelPos??fe(e);this.applyPanelPos(t)}resetToLauncher(e){this.panelPos=null;const t=fe(e);this.applyPanelPos(t)}setMessages(e){this.messagesEl.innerHTML="";for(const t of[...e].reverse())this.appendMessage(t,!1);this.scrollMessagesToBottom()}pushMessage(e){this.appendMessage(e,!0),this.scrollMessagesToBottom()}setTyping(e){this.typingEl.style.display=e?"block":"none"}setOperatorOnline(e){e?this.headerTitleEl.textContent=`${this.site.name} · ${e}`:this.headerTitleEl.textContent=this.site.name}appendGreeting(){this.site.welcome_message&&this.appendMessage({id:"greeting-"+Date.now(),chat_id:"",sender_id:"system",sender_kind:"user",sender_display_name:this.site.name,sender_avatar_url:null,content:this.site.welcome_message,message_type:"text",attachment_url:null,created_at:new Date().toISOString()},!0)}applyPanelPos(e){this.root.style.left=`${e.x}px`,this.root.style.top=`${e.y}px`,this.root.style.bottom="auto",this.root.style.right="auto"}setupHeaderDrag(){this.headerEl.style.cursor="grab",this.headerEl.style.touchAction="none";const e=i=>{if(i.button!==0||i.target.closest(".gomsg-close"))return;const o=this.root.getBoundingClientRect();this.dragInfo={pointerStart:{x:i.clientX,y:i.clientY},panelStart:{x:o.left,y:o.top}},this.headerEl.style.cursor="grabbing";try{this.headerEl.setPointerCapture(i.pointerId)}catch{}i.preventDefault()},t=i=>{if(!this.dragInfo)return;const n=i.clientX-this.dragInfo.pointerStart.x,o=i.clientY-this.dragInfo.pointerStart.y,a=_e({x:this.dragInfo.panelStart.x+n,y:this.dragInfo.panelStart.y+o});this.panelPos=a,this.applyPanelPos(a),this.handlers.onPanelMove?.(a)},s=i=>{if(this.dragInfo){try{this.headerEl.releasePointerCapture(i.pointerId)}catch{}this.dragInfo=null,this.headerEl.style.cursor="grab"}};this.headerEl.addEventListener("pointerdown",e),this.headerEl.addEventListener("pointermove",t),this.headerEl.addEventListener("pointerup",s),this.headerEl.addEventListener("pointercancel",s)}appendMessage(e,t){const s=document.createElement("div"),i=e.sender_kind==="visitor",n=e.sender_kind==="bot",o=n?this.site.ai_persona_name||"Assistant":e.sender_display_name||"";s.className=`gomsg-row${i?" gomsg-row-mine":""}${n?" gomsg-row-bot":""}${t?" gomsg-row-new":""}`;const a=n&&this.site.ai_show_badge;s.innerHTML=`
${a?'AI':""} ${ge(e.content)}
${Je(e.created_at)}${!i&&o?" · "+ge(o):""}
`,this.messagesEl.appendChild(s)}showSystemMessage(e){const t=document.createElement("div");t.className="gomsg-system-msg",t.textContent=e,this.messagesEl.appendChild(t),this.scrollMessagesToBottom()}scrollMessagesToBottom(){requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight})}handleSend(){const e=this.inputEl.value.trim();e&&(this.inputEl.value="",this.inputEl.style.height="auto",this.handlers.onSend(e))}handleIdentify(){const e=this.shadow.querySelector("#gomsg-identify-name"),t=this.shadow.querySelector("#gomsg-identify-email"),s={};e?.value.trim()&&(s.display_name=e.value.trim()),t?.value.trim()&&(s.email=t.value.trim()),Object.keys(s).length!==0&&(this.handlers.onIdentify?.(s),this.identifyFormEl.style.display="none")}}function fe(r){const e=window.innerWidth,t=window.innerHeight,s=r.x+q/2;r.y+q/2;const i=Math.min(se,e-2*k),n=Math.min(ie,t-2*k);let o;se-k&&(o=Math.max(k,r.x-i-k))):(o=r.x-i-k,o=k?a=h:(a=r.y+q+k,a+n>t-k&&(a=Math.max(k,t-n-k))),_e({x:o,y:a})}function _e(r){const e=window.innerWidth,t=window.innerHeight,s=Math.min(se,e-2*k),i=Math.min(ie,t-2*k);return{x:Math.min(Math.max(r.x,k),Math.max(k,e-s-k)),y:Math.min(Math.max(r.y,k),Math.max(k,t-i-k))}}function ge(r){return r.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function Je(r){try{return new Date(r).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Ke(r){return`
GoMsg
Оператор печатает…
`}const Ye="0.1.0";class pe{constructor(){p(this,"version",Ye);p(this,"cfg");p(this,"api");p(this,"site");p(this,"session");p(this,"launcher");p(this,"panel");p(this,"rt");p(this,"isOpen",!1);p(this,"unread",0);p(this,"pendingListeners",[])}async init(e){if(this.cfg){console.warn("[gomsg-widget] already initialised");return}this.cfg=e;const t=(e.server||me()).replace(/\/+$/,"");this.api=new L(t,e.siteId);try{this.site=await this.api.getSiteConfig()}catch(i){console.error("[gomsg-widget] failed to load site config",i);return}if(!this.site.is_active){console.info("[gomsg-widget] site is disabled; widget will not render");return}this.mount(),(e.visitorToken||A.getVisitorToken(e.siteId))&&this.ensureSession().catch(i=>console.error("[gomsg-widget] session restore failed",i)),e.onMessage&&this.on("message",i=>e.onMessage(i))}async ensureSession(){if(this.session)return!0;const e=this.cfg.visitorToken||A.getVisitorToken(this.cfg.siteId);try{this.session=await this.api.startSession({visitorToken:e??void 0,referrer:document.referrer||void 0}),A.setVisitorToken(this.cfg.siteId,this.session.visitor_token)}catch(t){return console.error("[gomsg-widget] failed to start visitor session",t),!1}return this.panel.setMessages(this.session.messages),this.session.messages.length===0&&this.panel.appendGreeting(),this.connectRealtime(),this.startPingLoop(),!0}open(){this.setOpen(!0)}close(){this.setOpen(!1)}toggle(){this.setOpen(!this.isOpen)}async identify(e){await this.ensureSession()&&await this.api.identify(this.session.visitor_token,e)}on(e,t){return this.rt?this.rt.on(e,t):(this.pendingListeners.push({event:e,listener:t}),()=>{this.pendingListeners=this.pendingListeners.filter(s=>s.listener!==t)})}mount(){const e=document.body,t=A.getLauncherPos(this.cfg.siteId)??Xe(this.site.position);this.panel=new He(this.site,{onSend:s=>this.handleSend(s),onIdentify:s=>{this.ensureSession().then(()=>this.api.identify(this.session.visitor_token,s)).catch(()=>{})},onClose:()=>this.close(),onPanelMove:s=>A.setPanelPos(this.cfg.siteId,s),onHandoff:()=>this.handleHandoff()}),this.panel.mount(e),this.panel.setMessages([]),this.panel.appendGreeting(),this.launcher=new Ge(this.site.color,t,()=>this.toggle(),s=>{A.setLauncherPos(this.cfg.siteId,s),this.isOpen&&this.panel.resetToLauncher(s)}),this.launcher.mount(e),window.addEventListener("resize",()=>{const s=this.launcher.getPosition();this.launcher.setPosition(s),this.isOpen&&this.panel.resetToLauncher(this.launcher.getPosition())}),A.getIsOpen(this.cfg.siteId)&&this.open()}connectRealtime(){const e=this.session.centrifugo_url||Ze(this.cfg.server||me());We(()=>this.api.listMessages(this.session.visitor_token,20)),this.rt=new $e(e,this.session.chat_id,this.session.centrifugo_token??""),this.rt.on("message",t=>this.handleIncoming(t)),this.rt.on("operator",t=>{const s=t;s?.name&&this.panel.setOperatorOnline(s.name),this.cfg.onOperatorJoined?.(s)}),this.rt.on("typing",t=>{this.panel.setTyping(!!t)}),this.rt.on("connected",()=>{console.info("[gomsg-widget] realtime connected")}),this.rt.on("closed",()=>{console.info("[gomsg-widget] realtime disconnected (will retry)")});for(const{event:t,listener:s}of this.pendingListeners)this.rt.on(t,s);this.pendingListeners=[],this.rt.start()}startPingLoop(){let e=location.pathname;this.api.ping(this.session.visitor_token,e).catch(()=>{}),setInterval(()=>{const t=location.pathname;t!==e&&(e=t,this.api.ping(this.session.visitor_token,t).catch(()=>{}))},15e3)}async handleSend(e){if(!await this.ensureSession())return;const t={id:"tmp-"+Date.now(),chat_id:this.session.chat_id,sender_id:this.session.visitor.id,sender_kind:"visitor",sender_display_name:this.session.visitor.display_name,sender_avatar_url:null,content:e,message_type:"text",attachment_url:null,created_at:new Date().toISOString()};this.panel.pushMessage(t);try{const s=await this.api.sendMessage(this.session.visitor_token,this.session.chat_id,e)}catch(s){console.error("[gomsg-widget] send failed",s)}}async handleHandoff(){if(await this.ensureSession())try{await this.api.requestHandoff(this.session.visitor_token),this.panel.showSystemMessage("Подключаем оператора, подождите…")}catch(e){console.error("[gomsg-widget] handoff failed",e)}}handleIncoming(e){const t=e;!t||!t.id||t.sender_kind!=="visitor"&&(this.panel.pushMessage(t),this.isOpen||(this.unread++,this.launcher.setUnread(this.unread)))}setOpen(e){this.isOpen=e,A.setIsOpen(this.cfg.siteId,e),e?(this.panel.anchorToLauncher(this.launcher.getPosition()),this.panel.show(),this.unread=0,this.launcher.setUnread(0)):this.panel.hide(),this.launcher.setActive(e),this.cfg.onOpenChange?.(e)}}function Xe(r){const s=typeof window<"u"?window.innerWidth:1280,i=typeof window<"u"?window.innerHeight:720;switch(r){case"bottom_left":return{x:18,y:i-60-18};case"top_right":return{x:s-60-18,y:18};case"top_left":return{x:18,y:18};case"bottom_right":default:return{x:s-60-18,y:i-60-18}}}function me(){if(typeof document<"u"&&document.currentScript){const r=document.currentScript.src;if(r)try{const e=new URL(r);return`${e.protocol}//${e.host}`}catch{}}return"http://localhost:8081"}function Ze(r){try{const e=new URL(r),t=e.protocol==="https:"?"wss:":"ws:";return e.hostname==="localhost"||e.hostname==="127.0.0.1"?`${t}//${e.hostname}:8000/connection/websocket`:`${t}//${e.host}/connection/websocket`}catch{return"ws://localhost:8000/connection/websocket"}}const Y=new pe;return typeof window<"u"&&(window.GomsgWidget=Y,window.GOMSG_CONFIG&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Y.init(window.GOMSG_CONFIG).catch(r=>console.error("[gomsg-widget] init failed",r))}):Y.init(window.GOMSG_CONFIG).catch(r=>console.error("[gomsg-widget] init failed",r)))),O.GomsgWidgetController=pe,O.default=Y,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),O}({}); //# sourceMappingURL=gomsg-widget.iife.js.map