topgun-socket
Advanced tools
Comparing version 1.2.2 to 1.2.3
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk6CUHH3QPjs = require('./chunk-6CUHH3QP.js');require('./chunk-L63Q7CFL.js');exports.TGChannel = _chunk6CUHH3QPjs.a; | ||
var u=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var C=(n,e,t)=>e in n?u(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var S=(n,e)=>{for(var t in e)u(n,t,{get:e[t],enumerable:!0})},b=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of h(e))!c.call(n,s)&&s!==t&&u(n,s,{get:()=>e[s],enumerable:!(r=o(e,s))||r.enumerable});return n};var p=n=>b(u({},"__esModule",{value:!0}),n);var l=(n,e,t)=>(C(n,typeof e!="symbol"?e+"":e,t),t);var d={};S(d,{TGChannel:()=>i});module.exports=p(d);var m=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var a=class extends m{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,r,s){super(),this.PENDING=a.PENDING,this.SUBSCRIBED=a.SUBSCRIBED,this.UNSUBSCRIBED=a.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=r,this._dataStream=s.stream(this.name)}get state(){return this.client.getChannelState(this.name)}set state(e){throw new Error("Cannot directly set channel state")}get options(){return this.client.getChannelOptions(this.name)}set options(e){throw new Error("Cannot directly set channel options")}createConsumer(e){return this._dataStream.createConsumer(e)}listener(e){return this._eventDemux.stream(`${this.name}/${e}`)}close(){this.client.closeChannel(this.name)}kill(){this.client.killChannel(this.name)}killOutputConsumer(e){this.hasOutputConsumer(e)&&this.client.killChannelOutputConsumer(e)}killListenerConsumer(e){this.hasAnyListenerConsumer(e)&&this.client.killChannelListenerConsumer(e)}getOutputConsumerStats(e){if(this.hasOutputConsumer(e))return this.client.getChannelOutputConsumerStats(e)}getListenerConsumerStats(e){if(this.hasAnyListenerConsumer(e))return this.client.getChannelListenerConsumerStats(e)}getBackpressure(){return this.client.getChannelBackpressure(this.name)}getListenerConsumerBackpressure(e){return this.hasAnyListenerConsumer(e)?this.client.getChannelListenerConsumerBackpressure(e):0}getOutputConsumerBackpressure(e){return this.hasOutputConsumer(e)?this.client.getChannelOutputConsumerBackpressure(e):0}closeOutput(){this.client.channelCloseOutput(this.name)}closeListener(e){this.client.channelCloseListener(this.name,e)}closeAllListeners(){this.client.channelCloseAllListeners(this.name)}killOutput(){this.client.channelKillOutput(this.name)}killListener(e){this.client.channelKillListener(this.name,e)}killAllListeners(){this.client.channelKillAllListeners(this.name)}getOutputConsumerStatsList(){return this.client.channelGetOutputConsumerStatsList(this.name)}getListenerConsumerStatsList(e){return this.client.channelGetListenerConsumerStatsList(this.name,e)}getAllListenersConsumerStatsList(){return this.client.channelGetAllListenersConsumerStatsList(this.name)}getOutputBackpressure(){return this.client.channelGetOutputBackpressure(this.name)}getListenerBackpressure(e){return this.client.channelGetListenerBackpressure(this.name,e)}getAllListenersBackpressure(){return this.client.channelGetAllListenersBackpressure(this.name)}hasOutputConsumer(e){return this.client.channelHasOutputConsumer(this.name,e)}hasListenerConsumer(e,t){return this.client.channelHasListenerConsumer(this.name,e,t)}hasAnyListenerConsumer(e){return this.client.channelHasAnyListenerConsumer(this.name,e)}subscribe(e){this.client.subscribe(this.name,e)}unsubscribe(){this.client.unsubscribe(this.name)}isSubscribed(e){return this.client.isSubscribed(this.name,e)}transmitPublish(e){return this.client.transmitPublish(this.name,e)}invokePublish(e){return this.client.invokePublish(this.name,e)}},i=a;l(i,"PENDING","pending"),l(i,"SUBSCRIBED","subscribed"),l(i,"UNSUBSCRIBED","unsubscribed");0&&(module.exports={TGChannel}); |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _class; var _class2;var _chunkHK2T5JM4js = require('./chunk-HK2T5JM4.js');var _chunk6CUHH3QPjs = require('./chunk-6CUHH3QP.js');require('./chunk-ZNIU5T3X.js');var _chunkL63Q7CFLjs = require('./chunk-L63Q7CFL.js');function V(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let t=Math.random()*16|0;return(o==="x"?t:t&3|8).toString(16)})}var _topgunbuffer = require('topgun-buffer'); var _topgunbuffer2 = _interopRequireDefault(_topgunbuffer);function E(o,t){if(!t)return o;if(t[Symbol.iterator]){let e=t[Symbol.iterator](),n;for(;(n=e.next())&&!n.done;)o.append(n.value)}else{let e=-1;for(;++e<t.length;){let n=t[e];o.append(n)}}return o}var A=class{constructor(){this.next=null,this.prev=null,this.list=null}append(t){let e=this.list;if(!t||!t.append||!t.prepend||!t.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!e||this===t?!1:(t.detach(),this.next&&(t.next=this.next,this.next.prev=t),t.prev=this,t.list=e,this.next=t,(this===e.tail||!e.tail)&&(e.tail=t),e.size++,t)}prepend(t){let e=this.list;if(!t||!t.append||!t.prepend||!t.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!e||this===t?!1:(t.detach(),this.prev&&(t.prev=this.prev,this.prev.next=t),t.next=this,t.list=e,this.prev=t,this===e.head&&(e.head=t),e.tail||(e.tail=this),e.size++,t)}detach(){let t=this.list;return t?(t.tail===this&&(t.tail=this.prev),t.head===this&&(t.head=this.next),t.tail===t.head&&(t.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,t.size--,this):this}};var x= (_class =class{__init() {this.item=null}constructor(t){;_class.prototype.__init.call(this);this.item=t}next(){let t=this.item;return t?(this.item=t.next,{value:t,done:!1}):{value:null,done:!0}}}, _class);var D=class{static from(t){let e=new this;return E(e,t)}static of(...t){let e=new this;return E(e,t)}constructor(...t){this.size=0,this.tail=null,this.head=null,E(this,t)}append(t){if(!t)return!1;if(!t.append||!t.prepend||!t.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(t):this.head?this.head.append(t):(t.detach(),t.list=this,this.head=t,this.size++,t)}prepend(t){if(!t)return!1;if(!t.append||!t.prepend||!t.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(t):(t.detach(),t.list=this,this.head=t,this.size++,t)}toArray(){let t=this.head,e=[];for(;t;)e.push(t),t=t.next;return e}[Symbol.iterator](){return new x(this.head)}};function O(o=0){return new Promise(t=>{setTimeout(()=>t(),o)})}var g=_chunkHK2T5JM4js.t.call(void 0, ),B= exports.AuthEngine =class{constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(t,e,n){return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.setItem(t,e):this._internalStorage[t]=e,Promise.resolve(e)}removeToken(t){let e=this.loadToken(t);return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.removeItem(t):delete this._internalStorage[t],e}loadToken(t){let e;return this.isLocalStorageEnabled&&g.localStorage?e=g.localStorage.getItem(t):e=this._internalStorage[t]||null,Promise.resolve(e)}_checkLocalStorageEnabled(){let t;try{g.localStorage,g.localStorage.setItem("__scLocalStorageTest",1),g.localStorage.removeItem("__scLocalStorageTest")}catch(e){t=e}return!t}};function $(o){return typeof o=="function"}function j(o,t){let e=_chunkHK2T5JM4js.t.call(void 0, );if(e&&$(e.WebSocket))return new e.WebSocket(o);throw Error("WebSocket instance not found")}var c=class{constructor(t,e,n,i,s){this.state=c.CLOSED,this.auth=t,this.codec=e,this.options=n,this.wsOptions=i,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],s||(s={}),this._onOpenHandler=s.onOpen||function(){},this._onOpenAbortHandler=s.onOpenAbort||function(){},this._onCloseHandler=s.onClose||function(){},this._onEventHandler=s.onEvent||function(){},this._onErrorHandler=s.onError||function(){},this._onInboundInvokeHandler=s.onInboundInvoke||function(){},this._onInboundTransmitHandler=s.onInboundTransmit||function(){},this.state=c.CONNECTING;let r=this.uri(),h=j(r,i);h.binaryType=this.options.binaryType,this.socket=h,h.onopen=()=>{this._onOpen()},h.onclose=async l=>{let p;l.code==null?p=1005:p=l.code,this._destroy(p,l.reason)},h.onmessage=(l,p)=>{this._onMessage(l.data)},h.onerror=()=>{this.state===c.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=l=>l==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=l=>l===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let t=this.options.query||{},e;this.options.protocolScheme==null?e=this.options.secure?"wss":"ws":e=this.options.protocolScheme,this.options.timestampRequests&&(t[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[r,h]of Object.entries(t))if(Array.isArray(h))for(let l of h)n.append(r,l);else n.set(r,`${h}`);t=n.toString(),t.length&&(t="?"+t);let i,s;if(this.options.socketPath==null){if(this.options.host)i=this.options.host;else{let r="";this.options.port&&(e==="wss"&&this.options.port!==443||e==="ws"&&this.options.port!==80)&&(r=":"+this.options.port),i=this.options.hostname+r}s=this.options.path}else i=this.options.socketPath,s=`:${this.options.path}`;return e+"://"+i+s+t}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let t=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(t)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(t,e){(this.state===c.OPEN||this.state===c.CONNECTING)&&(t=t||1e3,this._destroy(t,e),this.socket.close(t,e))}transmitObject(t){let e={event:t.event,data:t.data};return t.callback&&(e.cid=t.cid=this.callIdGenerator(),this._callbackMap[t.cid]=t),this.sendObject(e),t.cid||null}transmit(t,e,n){let i={event:t,data:e};return(this.state===c.OPEN||n.force)&&this.transmitObject(i),Promise.resolve()}invokeRaw(t,e,n,i){let s={event:t,data:e,callback:i};n.noTimeout||(s.timeout=setTimeout(()=>{this._handleEventAckTimeout(s)},this.options.ackTimeout));let r=null;return(this.state===c.OPEN||n.force)&&(r=this.transmitObject(s)),r}invoke(t,e,n){return new Promise((i,s)=>{this.invokeRaw(t,e,n,(r,h)=>{if(r){s(r);return}i(h)})})}cancelPendingResponse(t){delete this._callbackMap[t]}decode(t){return this.codec.decode(t)}encode(t){return this.codec.encode(t)}send(t){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(t)}serializeObject(t){let e;try{e=this.encode(t)}catch(n){return this._onError(n),null}return e}sendObject(t){if(this.isBufferingBatch){this._batchBuffer.push(t);return}let e=this.serializeObject(t);e!=null&&this.send(e)}_handleEventAckTimeout(t){t.cid&&delete this._callbackMap[t.cid],delete t.timeout;let e=t.callback;if(e){delete t.callback;let n=new (0, _chunkHK2T5JM4js.m)(`Event response for "${t.event}" timed out`);e.call(t,n,t)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let t;try{t=await this._handshake()}catch(e){e.statusCode==null&&(e.statusCode=4003),this._onError(e),this._destroy(e.statusCode,e.toString()),this.socket.close(e.statusCode);return}this.state=c.OPEN,t&&(this.pingTimeout=t.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(t)}async _handshake(){let t=await this.auth.loadToken(this.authTokenName),e={force:!0},n=await this.invoke("#handshake",{authToken:t},e);return n&&(n.authToken=t,n.authError&&(n.authError=_chunkHK2T5JM4js.s.call(void 0, n.authError))),n}_abortAllPendingEventsDueToBadConnection(t){Object.keys(this._callbackMap||{}).forEach(e=>{let n=this._callbackMap[e];delete this._callbackMap[e],clearTimeout(n.timeout),delete n.timeout;let i=`Event "${n.event}" was aborted due to a bad connection`,s=new (0, _chunkHK2T5JM4js.n)(i,t),r=n.callback;r&&(delete n.callback,r.call(n,s,n))})}_destroy(t,e){!e&&_chunkHK2T5JM4js.p[t]&&(e=_chunkHK2T5JM4js.p[t]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===c.OPEN?(this.state=c.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:t,reason:e})):this.state===c.CONNECTING?(this.state=c.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:t,reason:e})):this.state===c.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(t,e){if(t&&t.event!=null)if(t.cid==null)this._onInboundTransmitHandler({...t});else{let n=new (0, _chunkHK2T5JM4js.y)(this,t.cid,t.event,t.data);this._onInboundInvokeHandler(n)}else if(t&&t.rid!=null){let n=this._callbackMap[t.rid];if(n&&(clearTimeout(n.timeout),delete n.timeout,delete this._callbackMap[t.rid],n.callback)){let i=_chunkHK2T5JM4js.s.call(void 0, t.error);n.callback(i,t.data)}}else this._onEventHandler({event:"raw",data:{message:e}})}_onMessage(t){if(this._onEventHandler({event:"message",data:{message:t}}),this._handlePing(t))return;let e=this.decode(t);if(Array.isArray(e)){let n=e.length;for(let i=0;i<n;i++)this._processInboundPacket(e[i],t)}else this._processInboundPacket(e,t)}_onError(t){this._onErrorHandler({error:t})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},v= exports.TGTransport =c;_chunkL63Q7CFLjs.a.call(void 0, v,"CONNECTING","connecting"),_chunkL63Q7CFLjs.a.call(void 0, v,"OPEN","open"),_chunkL63Q7CFLjs.a.call(void 0, v,"CLOSED","closed");var K=typeof window<"u",I=_chunkHK2T5JM4js.t.call(void 0, ),a= (_class2 =class extends _chunkHK2T5JM4js.v{__init2() {this._privateDataHandlerMap={"#publish":t=>{let e=this._undecorateChannelName(t.channel);this.isSubscribed(e,!0)&&this._channelDataDemux.write(e,t.data)},"#kickOut":t=>{let e=this._undecorateChannelName(t.channel),n=this._channelMap[e];n&&(this.emit("kickOut",{channel:e,message:t.message}),this._channelEventDemux.write(`${e}/kickOut`,{message:t.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":t=>{t&&this._setAuthToken(t)},"#removeAuthToken":t=>{this._removeAuthToken()}}}__init3() {this._privateRPCHandlerMap={"#setAuthToken":(t,e)=>{t?(this._setAuthToken(t),e.end()):e.error(new (0, _chunkHK2T5JM4js.j)("No token data provided by #setAuthToken event"))},"#removeAuthToken":(t,e)=>{this._removeAuthToken(),e.end()}}}constructor(t){super();_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);;let n=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},t);this.id=null,this.version=n.version||null,this.protocolVersion=n.protocolVersion,this.state=a.CLOSED,this.authState=a.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let i=Math.pow(2,31)-1,s=r=>{if(this[r]>i)throw new (0, _chunkHK2T5JM4js.h)(`The ${r} value provided exceeded the maximum amount allowed`)};if(s("connectTimeout"),s("ackTimeout"),s("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new D,this._channelMap={},this._channelEventDemux=new _chunkHK2T5JM4js.u,this._channelDataDemux=new _chunkHK2T5JM4js.u,this._receiverDemux=new _chunkHK2T5JM4js.u,this._procedureDemux=new _chunkHK2T5JM4js.u,this.options=n,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let r=this.options.autoReconnectOptions;r.initialDelay==null&&(r.initialDelay=1e4),r.randomness==null&&(r.randomness=1e4),r.multiplier==null&&(r.multiplier=1.5),r.maxDelay==null&&(r.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new B,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunkHK2T5JM4js.w,this.options.protocol){let r=new (0, _chunkHK2T5JM4js.h)('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(r)}if(this.options.query=n.query||{},typeof this.options.query=="string"){let r=new URLSearchParams(this.options.query),h={};r.forEach((l,p)=>{let k=h[p];k==null?h[p]=l:(Array.isArray(k)||(h[p]=[k]),h[p].push(l))}),this.options.query=h}K&&this.disconnectOnUnload&&I.addEventListener&&I.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let t;try{t=await this.auth.removeToken(this.authTokenName)}catch(e){this._onError(e);return}this.emit("removeAuthToken",{oldAuthToken:t})})(),this.state!==a.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await O(0)}connect(){if(this.state===a.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=a.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let t={onOpen:e=>{this.state=a.OPEN,this._onOpen(e)},onOpenAbort:e=>{this.state!==a.CLOSED&&(this.state=a.CLOSED,this._destroy(e.code,e.reason,!0))},onClose:e=>{this.state!==a.CLOSED&&(this.state=a.CLOSED,this._destroy(e.code,e.reason))},onEvent:e=>{this.emit(e.event,e.data)},onError:e=>{this._onError(e.error)},onInboundInvoke:e=>{this._onInboundInvoke(e)},onInboundTransmit:e=>{this._onInboundTransmit(e.event,e.data)}};this.transport=new v(this.auth,this.codec,this.options,this.wsOptions,t)}}reconnect(t,e){this.disconnect(t,e),this.connect()}disconnect(t,e){if(t=t||1e3,typeof t!="number")throw new (0, _chunkHK2T5JM4js.h)("If specified, the code argument must be a number");let n=this.state===a.CONNECTING;n||this.state===a.OPEN?(this.state=a.CLOSED,this._destroy(t,e,n),this.transport.close(t,e)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(t){return _topgunbuffer2.default.from(t,"base64").toString("utf8")}encodeBase64(t){return _topgunbuffer2.default.from(t,"utf8").toString("base64")}getAuthToken(){return this.authToken}getSignedAuthToken(){return this.signedAuthToken}async authenticate(t){let e;try{e=await this.invoke("#authenticate",t)}catch(n){throw n.name!=="BadConnectionError"&&n.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await O(0),n}return e&&e.isAuthenticated!=null?e.authError&&(e.authError=_chunkHK2T5JM4js.s.call(void 0, e.authError)):e={isAuthenticated:this.authState,authError:null},e.isAuthenticated?this._changeToAuthenticatedState(t):this._changeToUnauthenticatedStateAndClearTokens(),(async()=>{try{await this.auth.saveToken(this.authTokenName,t,{})}catch(n){this._onError(n)}})(),await O(0),e}decode(t){return this.transport.decode(t)}encode(t){return this.transport.encode(t)}send(t){this.transport.send(t)}transmit(t,e,n){return this._processOutboundEvent(t,e,n)}invoke(t,e,n){return this._processOutboundEvent(t,e,n,!0)}transmitPublish(t,e){let n={channel:this._decorateChannelName(t),data:e};return this.transmit("#publish",n)}invokePublish(t,e){let n={channel:this._decorateChannelName(t),data:e};return this.invoke("#publish",n)}startBatch(){this.transport.startBatch()}flushBatch(){this.transport.flushBatch()}cancelBatch(){this.transport.cancelBatch()}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}subscribe(t,e){e=e||{};let n=this._channelMap[t],i={waitForAuth:!!e.waitForAuth};return e.priority!=null&&(i.priority=e.priority),e.data!==void 0&&(i.data=e.data),n?e&&(n.options=i):(n={name:t,state:_chunk6CUHH3QPjs.a.PENDING,options:i},this._channelMap[t]=n,this._trySubscribe(n)),new (0, _chunk6CUHH3QPjs.a)(t,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(t){let e=this._channelMap[t];e&&(this._triggerChannelUnsubscribe(e),this._tryUnsubscribe(e))}receiver(t){return this._receiverDemux.stream(t)}closeReceiver(t){this._receiverDemux.close(t)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(t){this._receiverDemux.kill(t)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(t){this._receiverDemux.killConsumer(t)}getReceiverConsumerStats(t){return this._receiverDemux.getConsumerStats(t)}getReceiverConsumerStatsList(t){return this._receiverDemux.getConsumerStatsList(t)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(t){return this._receiverDemux.getBackpressure(t)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(t){return this._receiverDemux.getConsumerBackpressure(t)}hasReceiverConsumer(t,e){return this._receiverDemux.hasConsumer(t,e)}hasAnyReceiverConsumer(t){return this._receiverDemux.hasConsumerAll(t)}procedure(t){return this._procedureDemux.stream(t)}closeProcedure(t){this._procedureDemux.close(t)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(t){this._procedureDemux.kill(t)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(t){this._procedureDemux.killConsumer(t)}getProcedureConsumerStats(t){return this._procedureDemux.getConsumerStats(t)}getProcedureConsumerStatsList(t){return this._procedureDemux.getConsumerStatsList(t)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(t){return this._procedureDemux.getBackpressure(t)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(t){return this._procedureDemux.getConsumerBackpressure(t)}hasProcedureConsumer(t,e){return this._procedureDemux.hasConsumer(t,e)}hasAnyProcedureConsumer(t){return this._procedureDemux.hasConsumerAll(t)}channel(t){return new (0, _chunk6CUHH3QPjs.a)(t,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(t){this.channelCloseOutput(t),this.channelCloseAllListeners(t)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(t){this.channelKillOutput(t),this.channelKillAllListeners(t)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(t){this._channelDataDemux.killConsumer(t)}killChannelListenerConsumer(t){this._channelEventDemux.killConsumer(t)}getChannelOutputConsumerStats(t){return this._channelDataDemux.getConsumerStats(t)}getChannelListenerConsumerStats(t){return this._channelEventDemux.getConsumerStats(t)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(t){return Math.max(this.channelGetOutputBackpressure(t),this.channelGetAllListenersBackpressure(t))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(t){return this._channelEventDemux.getConsumerBackpressure(t)}getChannelOutputConsumerBackpressure(t){return this._channelDataDemux.getConsumerBackpressure(t)}hasAnyChannelOutputConsumer(t){return this._channelDataDemux.hasConsumerAll(t)}hasAnyChannelListenerConsumer(t){return this._channelEventDemux.hasConsumerAll(t)}getChannelState(t){let e=this._channelMap[t];return e?e.state:_chunk6CUHH3QPjs.a.UNSUBSCRIBED}getChannelOptions(t){let e=this._channelMap[t];return e?{...e.options}:{}}channelCloseOutput(t){this._channelDataDemux.close(t)}channelCloseListener(t,e){this._channelEventDemux.close(`${t}/${e}`)}channelCloseAllListeners(t){this._getAllChannelStreamNames(t).forEach(e=>{this._channelEventDemux.close(e)})}channelKillOutput(t){this._channelDataDemux.kill(t)}channelKillListener(t,e){this._channelEventDemux.kill(`${t}/${e}`)}channelKillAllListeners(t){this._getAllChannelStreamNames(t).forEach(e=>{this._channelEventDemux.kill(e)})}channelGetOutputConsumerStatsList(t){return this._channelDataDemux.getConsumerStatsList(t)}channelGetListenerConsumerStatsList(t,e){return this._channelEventDemux.getConsumerStatsList(`${t}/${e}`)}channelGetAllListenersConsumerStatsList(t){return this._getAllChannelStreamNames(t).map(e=>this._channelEventDemux.getConsumerStatsList(e)).reduce((e,n)=>(n.forEach(i=>{e.push(i)}),e),[])}channelGetOutputBackpressure(t){return this._channelDataDemux.getBackpressure(t)}channelGetListenerBackpressure(t,e){return this._channelEventDemux.getBackpressure(`${t}/${e}`)}channelGetAllListenersBackpressure(t){let e=this._getAllChannelStreamNames(t).map(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...e.concat(0))}channelHasOutputConsumer(t,e){return this._channelDataDemux.hasConsumer(t,e)}channelHasListenerConsumer(t,e,n){return this._channelEventDemux.hasConsumer(`${t}/${e}`,n)}channelHasAnyListenerConsumer(t,e){return this._getAllChannelStreamNames(t).some(n=>this._channelEventDemux.hasConsumer(n,e))}subscriptions(t){let e=[];return Object.keys(this._channelMap).forEach(n=>{(t||this._channelMap[n].state===_chunk6CUHH3QPjs.a.SUBSCRIBED)&&e.push(n)}),e}isSubscribed(t,e){let n=this._channelMap[t];return e?!!n:!!n&&n.state===_chunk6CUHH3QPjs.a.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let t=[];Object.keys(this._channelMap).forEach(e=>{let n=this._channelMap[e];n.state===_chunk6CUHH3QPjs.a.PENDING&&t.push(n)}),t.sort((e,n)=>{let i=e.options.priority||0,s=n.options.priority||0;return i>s?-1:i<s?1:0}),t.forEach(e=>{this._trySubscribe(e)})}_getAllChannelStreamNames(t){let e=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${t}/`)===0).reduce((n,i)=>(n[i.stream]=!0,n),{});return Object.keys(e)}_tryUnsubscribe(t){if(this.state===a.OPEN){let e={noTimeout:!0};this._cancelPendingSubscribeCallback(t);let n=this._decorateChannelName(t.name);this.transport.transmit("#unsubscribe",n,e)}}_triggerChannelUnsubscribe(t,e){let n=t.name;if(this._cancelPendingSubscribeCallback(t),t.state===_chunk6CUHH3QPjs.a.SUBSCRIBED){let i={oldChannelState:t.state,newChannelState:e?_chunk6CUHH3QPjs.a.PENDING:_chunk6CUHH3QPjs.a.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("unsubscribe",{channel:n})}e?t.state=_chunk6CUHH3QPjs.a.PENDING:delete this._channelMap[n]}_trySubscribe(t){let e=!t.options.waitForAuth||this.authState===a.AUTHENTICATED;if(this.state===a.OPEN&&!this.preparingPendingSubscriptions&&t._pendingSubscriptionCid==null&&e){let n={noTimeout:!0},i={};t.options.waitForAuth&&(n.waitForAuth=!0,i.waitForAuth=n.waitForAuth),t.options.data&&(i.data=t.options.data),t._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(t.name),...i},n,s=>{if(s){if(s.name==="BadConnectionError")return;delete t._pendingSubscriptionCid,this._triggerChannelSubscribeFail(s,t,i)}else delete t._pendingSubscriptionCid,this._triggerChannelSubscribe(t,i)}),this.emit("subscribeRequest",{channel:t.name,subscriptionOptions:i})}}_cancelBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.cancelBatch()}_stopBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.flushBatch()}_startBatching(){this._batchingIntervalId==null&&(this.startBatch(),this._batchingIntervalId=setInterval(()=>{this.flushBatch(),this.startBatch()},this.options.batchInterval))}_undecorateChannelName(t){return this.channelPrefix&&t.indexOf(this.channelPrefix)===0?t.replace(this.channelPrefix,""):t}_decorateChannelName(t){return this.channelPrefix&&(t=this.channelPrefix+t),t}_cancelPendingSubscribeCallback(t){t._pendingSubscriptionCid!=null&&(this.transport.cancelPendingResponse(t._pendingSubscriptionCid),delete t._pendingSubscriptionCid)}_triggerChannelSubscribeFail(t,e,n){let i=e.name,s=!e.options.waitForAuth||this.authState===a.AUTHENTICATED;!!this._channelMap[i]&&s&&(delete this._channelMap[i],this._channelEventDemux.write(`${i}/subscribeFail`,{error:t,subscriptionOptions:n}),this.emit("subscribeFail",{error:t,channel:i,subscriptionOptions:n}))}_triggerChannelSubscribe(t,e){let n=t.name;if(t.state!==_chunk6CUHH3QPjs.a.SUBSCRIBED){let i=t.state;t.state=_chunk6CUHH3QPjs.a.SUBSCRIBED;let s={oldChannelState:i,newChannelState:t.state,subscriptionOptions:e};this._channelEventDemux.write(`${n}/subscribeStateChange`,s),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:e}),this.emit("subscribeStateChange",{channel:n,...s}),this.emit("subscribe",{channel:n,subscriptionOptions:e})}}_processOutboundEvent(t,e,n,i){n=n||{},this.state===a.CLOSED&&this.connect();let s={event:t,data:null},r;i?r=new Promise((p,k)=>{s.callback=(w,z)=>{if(w){k(w);return}p(z)}}):r=Promise.resolve();let h=new A;this.options.cloneData?s.data=_chunkHK2T5JM4js.x.call(void 0, e):s.data=e,h.data=s;let l=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return s.timeout=setTimeout(()=>{this._handleEventAckTimeout(s,h)},l),this._outboundBuffer.append(h),this.state===a.OPEN&&this._flushOutboundBuffer(),r}_handleEventAckTimeout(t,e){e&&e.detach(),delete t.timeout;let n=t.callback;if(n){delete t.callback;let i=new (0, _chunkHK2T5JM4js.m)(`Event response for "${t.event}" timed out`);n.call(t,i,t)}t.cid&&this.transport.cancelPendingResponse(t.cid)}_flushOutboundBuffer(){let t=this._outboundBuffer.head,e;for(;t;){e=t.next;let n=t.data;t.detach(),this.transport.transmitObject(n),t=e}}_onInboundInvoke(t){let{procedure:e,data:n}=t,i=this._privateRPCHandlerMap[e];i?i.call(this,n,t):this._procedureDemux.write(e,t)}_onInboundTransmit(t,e){let n=this._privateDataHandlerMap[t];n?n.call(this,e):this._receiverDemux.write(t,e)}_destroy(t,e,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:t,reason:e}):this.emit("disconnect",{code:t,reason:e}),this.emit("close",{code:t,reason:e}),!a.ignoreStatuses[t]){let i;e?i="Socket connection closed with status code "+t+" and reason: "+e:i="Socket connection closed with status code "+t;let s=new (0, _chunkHK2T5JM4js.k)(a.errorStatuses[t]||i,t);this._onError(s)}this._abortAllPendingEventsDueToBadConnection(n?"connectAbort":"disconnect"),this.options.autoReconnect&&(t===4e3||t===4001||t===1005?this._tryReconnect(0):t!==1e3&&t<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(t){let e=this._outboundBuffer.head,n;for(;e;){n=e.next;let i=e.data;clearTimeout(i.timeout),delete i.timeout,e.detach(),e=n;let s=i.callback;if(s){delete i.callback;let r=`Event "${i.event}" was aborted due to a bad connection`,h=new (0, _chunkHK2T5JM4js.n)(r,t);s.call(i,h,i)}i.cid&&this.transport.cancelPendingResponse(i.cid)}}_suspendSubscriptions(){Object.keys(this._channelMap).forEach(t=>{let e=this._channelMap[t];this._triggerChannelUnsubscribe(e,!0)})}_onError(t){this.emit("error",{error:t})}_tryReconnect(t){let e=this.connectAttempts++,n=this.options.autoReconnectOptions,i;if(t==null||e>0){let s=Math.round(n.initialDelay+(n.randomness||0)*Math.random());i=Math.round(s*Math.pow(n.multiplier,e))}else i=t;i>n.maxDelay&&(i=n.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=i,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},i)}_onOpen(t){this.isBatching?this._startBatching():this.batchOnHandshake&&(this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)),this.preparingPendingSubscriptions=!0,t?(this.id=t.id,this.pingTimeout=t.pingTimeout,t.isAuthenticated?this._changeToAuthenticatedState(t.authToken):this._changeToUnauthenticatedStateAndClearTokens()):this._changeToUnauthenticatedStateAndClearTokens(),this.connectAttempts=0,this.options.autoSubscribeOnConnect&&this.processPendingSubscriptions(),this.emit("connect",{...t,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===a.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(t){let n=(t||"").split(".")[1];if(n!=null){let i=n;try{return i=this.decodeBase64(i),JSON.parse(i)}catch (e2){return i}}return null}_changeToAuthenticatedState(t){if(this.signedAuthToken=t,this.authToken=this._extractAuthTokenData(t),this.authState!==a.AUTHENTICATED){let e=this.authState;this.authState=a.AUTHENTICATED;let n={oldAuthState:e,newAuthState:this.authState,signedAuthToken:t,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:t,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==a.UNAUTHENTICATED){let t=this.authState,e=this.authToken,n=this.signedAuthToken;this.authState=a.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let i={oldAuthState:t,newAuthState:this.authState};this.emit("authStateChange",i),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:e})}}async _handleBrowserUnload(){let t=()=>{this.disconnect()},e=!1,n=()=>{e||(e=!0,I.addEventListener("beforeunload",t,!1))},i=()=>{e&&(e=!1,I.removeEventListener("beforeunload",t,!1))};(async()=>{let s=this.listener("connecting").createConsumer();for(;!(await s.next()).done;)n()})(),(async()=>{let s=this.listener("close").createConsumer();for(;!(await s.next()).done;)i()})()}_setAuthToken(t){this._changeToAuthenticatedState(t.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,t.token,{})}catch(e){this._onError(e)}})()}_removeAuthToken(){(async()=>{let t;try{t=await this.auth.removeToken(this.authTokenName)}catch(e){this._onError(e);return}this.emit("removeAuthToken",{oldAuthToken:t})})(),this._changeToUnauthenticatedStateAndClearTokens()}}, _class2),m= exports.TGClientSocket =a;_chunkL63Q7CFLjs.a.call(void 0, m,"CONNECTING","connecting"),_chunkL63Q7CFLjs.a.call(void 0, m,"OPEN","open"),_chunkL63Q7CFLjs.a.call(void 0, m,"CLOSED","closed"),_chunkL63Q7CFLjs.a.call(void 0, m,"AUTHENTICATED","authenticated"),_chunkL63Q7CFLjs.a.call(void 0, m,"UNAUTHENTICATED","unauthenticated"),_chunkL63Q7CFLjs.a.call(void 0, m,"SUBSCRIBED","subscribed"),_chunkL63Q7CFLjs.a.call(void 0, m,"PENDING","pending"),_chunkL63Q7CFLjs.a.call(void 0, m,"UNSUBSCRIBED","unsubscribed"),_chunkL63Q7CFLjs.a.call(void 0, m,"ignoreStatuses",_chunkHK2T5JM4js.q),_chunkL63Q7CFLjs.a.call(void 0, m,"errorStatuses",_chunkHK2T5JM4js.p);var P=_chunkHK2T5JM4js.t.call(void 0, );function W(){return P.location&&location.protocol==="https:"}function J(o,t){let e=o.secure==null?t:o.secure;return o.port||(P.location&&location.port?parseFloat(location.port):e?443:80)}function q(o){if(o=o||{},o.host&&!o.host.match(/[^:]+:\d{2,5}/))throw new (0, _chunkHK2T5JM4js.h)('The host option should include both the hostname and the port number in the format "hostname:port"');if(o.host&&o.hostname)throw new (0, _chunkHK2T5JM4js.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and hostname options together');if(o.host&&o.port)throw new (0, _chunkHK2T5JM4js.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and port options together');let t=W(),e={clientId:V(),port:J(o,t),hostname:P.location&&location.hostname||"localhost",secure:t};return Object.assign(e,o),new m(e)}var Q="1.0.0";function qt(o){return q({...o,version:Q})}exports.AuthEngine = B; exports.TGClientSocket = m; exports.TGTransport = v; exports.create = qt; exports.version = Q; | ||
var ce=Object.create;var D=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var pe=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var fe=(s,e)=>{for(var t in e)D(s,t,{get:e[t],enumerable:!0})},Q=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of he(e))!de.call(s,r)&&r!==t&&D(s,r,{get:()=>e[r],enumerable:!(n=le(e,r))||n.enumerable});return s};var ge=(s,e,t)=>(t=s!=null?ce(me(s)):{},Q(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s)),be=s=>Q(D({},"__esModule",{value:!0}),s);var h=(s,e,t)=>(pe(s,typeof e!="symbol"?e+"":e,t),t);var De={};fe(De,{AuthEngine:()=>I,TGClientSocket:()=>p,TGTransport:()=>v,create:()=>Oe,version:()=>ae});module.exports=be(De);function X(s){let e=[],t=[];return function n(r,i){let o,u,a;if(typeof r=="object"&&r!==null&&!(r instanceof Boolean)&&!(r instanceof Date)&&!(r instanceof Number)&&!(r instanceof RegExp)&&!(r instanceof String)){for(o=0;o<e.length;o+=1)if(e[o]===r)return{$ref:t[o]};if(e.push(r),t.push(i),Object.prototype.toString.apply(r)==="[object Array]")for(a=[],o=0;o<r.length;o+=1)a[o]=n(r[o],i+"["+o+"]");else{a={};for(u in r)Object.prototype.hasOwnProperty.call(r,u)&&(a[u]=n(r[u],i+"["+JSON.stringify(u)+"]"))}return a}return r}(s,"$")}function A(){"use strict";return typeof function(){return this}()>"u"}var _=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_.prototype),this.name="InvalidActionError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},f=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,f.prototype),this.name="InvalidArgumentsError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var x=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,x.prototype),this.name="InvalidMessageError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},E=class extends Error{code;constructor(e,t){super(e),Object.setPrototypeOf(this,E.prototype),this.name="SocketProtocolError",this.message=e,this.code=t,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var C=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,C.prototype),this.name="TimeoutError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},S=class extends Error{type;constructor(e,t){super(e),Object.setPrototypeOf(this,S.prototype),this.name="BadConnectionError",this.message=e,this.type=t,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var B={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token",4005:"Did not receive #handshake from client before timeout",4006:"Failed to bind socket to message broker",4007:"Client connection establishment timed out",4008:"Server rejected handshake from client",4009:"Server received a message before the client handshake"},Y={1e3:"Socket closed normally",1001:"Socket hung up"},ke={domain:1,domainEmitter:1,domainThrown:1};function Z(s,e){let t;if(s&&typeof s=="object"){t={message:s.message},e&&(t.stack=s.stack);for(let n in s)ke[n]||(t[n]=s[n])}else typeof s=="function"?t="[function "+(s.name||"anonymous")+"]":t=s;return X(t)}function w(s){let e=null;if(s!=null)if(typeof s=="object"){e=new Error(s.message);for(let t in s)s.hasOwnProperty(t)&&(e[t]=s[t])}else e=s;return e}function g(){return typeof WorkerGlobalScope<"u"?self:typeof window<"u"&&window||function(){return this}()}function ee(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}var W=ge(require("topgun-buffer"));var y=class{async next(e){let t=this.createConsumer(e),n=await t.next();return t.return(),n}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var L=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,n,r=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=n,this.timeout=r,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,n)=>{this._resolve=t;let r;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let o=Ce(e);r=o.timeoutId,await o.promise,i.name="TimeoutError",delete this._resolve,n(i)})()}this._timeoutId=r})}[Symbol.asyncIterator](){return this}};function Ce(s){let e,t=new Promise(n=>{e=setTimeout(n,s)});return{timeoutId:e,promise:t}}var N=class extends y{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let n=this._consumers.get(e);!n||n.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let n=t.getBackpressure();n>e&&(e=n)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new L(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,n){let r={data:{value:e,done:t},next:null};n&&(r.consumerId=n),this._tailNode.next=r,this._tailNode=r;for(let i of this._consumers.values())i.write(r.data)}};var R=class extends y{name;_streamDemux;constructor(e,t){super(),this.name=t,this._streamDemux=e}createConsumer(e){return this._streamDemux.createConsumer(this.name,e)}};var b=class{_mainStream;constructor(){this._mainStream=new N}write(e,t){this._mainStream.write({stream:e,data:{value:t,done:!1}})}close(e,t){this._mainStream.write({stream:e,data:{value:t,done:!0}})}closeAll(e){this._mainStream.close(e)}writeToConsumer(e,t){this._mainStream.writeToConsumer(e,{consumerId:e,data:{value:t,done:!1}})}closeConsumer(e,t){this._mainStream.closeConsumer(e,{consumerId:e,data:{value:t,done:!0}})}getConsumerStats(e){return this._mainStream.getConsumerStats(e)}getConsumerStatsList(e){return this._mainStream.getConsumerStatsList().filter(n=>n.stream===e)}getConsumerStatsListAll(){return this._mainStream.getConsumerStatsList()}kill(e,t){let n=this.getConsumerStatsList(e),r=n.length;for(let i=0;i<r;i++)this.killConsumer(n[i].id,t)}killAll(e){this._mainStream.kill(e)}killConsumer(e,t){this._mainStream.killConsumer(e,t)}getBackpressure(e){let t=this.getConsumerStatsList(e),n=t.length,r=0;for(let i=0;i<n;i++){let o=t[i];o.backpressure>r&&(r=o.backpressure)}return r}getBackpressureAll(){return this._mainStream.getBackpressure()}getConsumerBackpressure(e){return this._mainStream.getConsumerBackpressure(e)}hasConsumer(e,t){let n=this._mainStream.getConsumerStats(t);return!!n&&n.stream===e}hasConsumerAll(e){return this._mainStream.hasConsumer(e)}getConsumerCount(e){return this.getConsumerStatsList(e).length}getConsumerCountAll(){return this.getConsumerStatsListAll().length}createConsumer(e,t){let n=this._mainStream.createConsumer(t),r=n.next;n.next=async function(){for(;;){let a=arguments,c=await r.apply(this,a);if(c.value&&(c.value.stream===e||c.value.consumerId===this.id))return c.value.data.done&&this.return(),c.value.data;if(c.done)return c}};let i=n.getStats;n.getStats=function(){let a=arguments,c=i.apply(this,a);return c.stream=e,c};let o=n.applyBackpressure;n.applyBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){o.apply(this,c);return}a.done&&o.apply(this,c)};let u=n.releaseBackpressure;return n.releaseBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){u.apply(this,c);return}a.done&&u.apply(this,c)},n}stream(e){return new R(this,e)}};var U=class{_listenerDemux;constructor(){this._listenerDemux=new b}emit(e,t){this._listenerDemux.write(e,t)}listener(e){return this._listenerDemux.stream(e)}closeListener(e){this._listenerDemux.close(e)}closeAllListeners(){this._listenerDemux.closeAll()}getListenerConsumerStats(e){return this._listenerDemux.getConsumerStats(e)}getListenerConsumerStatsList(e){return this._listenerDemux.getConsumerStatsList(e)}getAllListenersConsumerStatsList(){return this._listenerDemux.getConsumerStatsListAll()}getListenerConsumerCount(e){return this._listenerDemux.getConsumerCount(e)}getAllListenersConsumerCount(){return this._listenerDemux.getConsumerCountAll()}killListener(e){this._listenerDemux.kill(e)}killAllListeners(){this._listenerDemux.killAll()}killListenerConsumer(e){this._listenerDemux.killConsumer(e)}getListenerBackpressure(e){return this._listenerDemux.getBackpressure(e)}getAllListenersBackpressure(){return this._listenerDemux.getBackpressureAll()}getListenerConsumerBackpressure(e){return this._listenerDemux.getConsumerBackpressure(e)}hasListenerConsumer(e,t){return this._listenerDemux.hasConsumer(e,t)}hasAnyListenerConsumer(e){return this._listenerDemux.hasConsumerAll(e)}};var P=class extends y{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,n,r){super(),this.PENDING=P.PENDING,this.SUBSCRIBED=P.SUBSCRIBED,this.UNSUBSCRIBED=P.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=n,this._dataStream=r.stream(this.name)}get state(){return this.client.getChannelState(this.name)}set state(e){throw new Error("Cannot directly set channel state")}get options(){return this.client.getChannelOptions(this.name)}set options(e){throw new Error("Cannot directly set channel options")}createConsumer(e){return this._dataStream.createConsumer(e)}listener(e){return this._eventDemux.stream(`${this.name}/${e}`)}close(){this.client.closeChannel(this.name)}kill(){this.client.killChannel(this.name)}killOutputConsumer(e){this.hasOutputConsumer(e)&&this.client.killChannelOutputConsumer(e)}killListenerConsumer(e){this.hasAnyListenerConsumer(e)&&this.client.killChannelListenerConsumer(e)}getOutputConsumerStats(e){if(this.hasOutputConsumer(e))return this.client.getChannelOutputConsumerStats(e)}getListenerConsumerStats(e){if(this.hasAnyListenerConsumer(e))return this.client.getChannelListenerConsumerStats(e)}getBackpressure(){return this.client.getChannelBackpressure(this.name)}getListenerConsumerBackpressure(e){return this.hasAnyListenerConsumer(e)?this.client.getChannelListenerConsumerBackpressure(e):0}getOutputConsumerBackpressure(e){return this.hasOutputConsumer(e)?this.client.getChannelOutputConsumerBackpressure(e):0}closeOutput(){this.client.channelCloseOutput(this.name)}closeListener(e){this.client.channelCloseListener(this.name,e)}closeAllListeners(){this.client.channelCloseAllListeners(this.name)}killOutput(){this.client.channelKillOutput(this.name)}killListener(e){this.client.channelKillListener(this.name,e)}killAllListeners(){this.client.channelKillAllListeners(this.name)}getOutputConsumerStatsList(){return this.client.channelGetOutputConsumerStatsList(this.name)}getListenerConsumerStatsList(e){return this.client.channelGetListenerConsumerStatsList(this.name,e)}getAllListenersConsumerStatsList(){return this.client.channelGetAllListenersConsumerStatsList(this.name)}getOutputBackpressure(){return this.client.channelGetOutputBackpressure(this.name)}getListenerBackpressure(e){return this.client.channelGetListenerBackpressure(this.name,e)}getAllListenersBackpressure(){return this.client.channelGetAllListenersBackpressure(this.name)}hasOutputConsumer(e){return this.client.channelHasOutputConsumer(this.name,e)}hasListenerConsumer(e,t){return this.client.channelHasListenerConsumer(this.name,e,t)}hasAnyListenerConsumer(e){return this.client.channelHasAnyListenerConsumer(this.name,e)}subscribe(e){this.client.subscribe(this.name,e)}unsubscribe(){this.client.unsubscribe(this.name)}isSubscribed(e){return this.client.isSubscribed(this.name,e)}transmitPublish(e){return this.client.transmitPublish(this.name,e)}invokePublish(e){return this.client.invokePublish(this.name,e)}},m=P;h(m,"PENDING","pending"),h(m,"SUBSCRIBED","subscribed"),h(m,"UNSUBSCRIBED","unsubscribed");var H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Se=/^[ \n\r\t]*[{\[]/,T=g(),ye=function(s){let e=new Uint8Array(s),t=e.length,n="";for(let r=0;r<t;r+=3)n+=H[e[r]>>2],n+=H[(e[r]&3)<<4|e[r+1]>>4],n+=H[(e[r+1]&15)<<2|e[r+2]>>6],n+=H[e[r+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},ve=function(s,e){if(T.ArrayBuffer&&e instanceof T.ArrayBuffer)return{base64:!0,data:ye(e)};if(T.Buffer){if(e instanceof T.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&e.type==="Buffer"&&Array.isArray(e.data)){let t;return T.Buffer.from?t=T.Buffer.from(e.data):t=new T.Buffer(e.data),{base64:!0,data:t.toString("base64")}}}return e};function Te(s){if(s==null)return null;if(s==="#1"||s==="#2")return s;let e=s.toString();if(!Se.test(e))return e;try{return JSON.parse(e)}catch{}return e}function _e(s){return s==="#1"||s==="#2"?s:JSON.stringify(s,ve)}var te={encode:_e,decode:Te};function G(s,e){if(!e)return s;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)s.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];s.append(n)}}return s}var j=class{next;prev;list;constructor(){this.next=null,this.prev=null,this.list=null}append(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!t||this===e?!1:(e.detach(),this.next&&(e.next=this.next,this.next.prev=e),e.prev=this,e.list=t,this.next=e,(this===t.tail||!t.tail)&&(t.tail=e),t.size++,e)}prepend(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!t||this===e?!1:(e.detach(),this.prev&&(e.prev=this.prev,this.prev.next=e),e.next=this,e.list=t,this.prev=e,this===t.head&&(t.head=e),t.tail||(t.tail=this),t.size++,e)}detach(){let e=this.list;return e?(e.tail===this&&(e.tail=this.prev),e.head===this&&(e.head=this.next),e.tail===e.head&&(e.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,e.size--,this):this}};var M=class{item=null;constructor(e){this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}};var V=class{size;head;tail;static from(e){let t=new this;return G(t,e)}static of(...e){let t=new this;return G(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,G(this,e)}append(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(e):this.head?this.head.append(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}prepend(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}toArray(){let e=this.head,t=[];for(;e;)t.push(e),e=e.next;return t}[Symbol.iterator](){return new M(this.head)}};function ne(s){return Object.prototype.toString.call(s)==="[object Date]"}function re(s){return!!s&&typeof s=="object"&&Object.prototype.toString.call(s)!=="[object Array]"}function $(s){if(ne(s))return new Date(s.getTime());if(Array.isArray(s))return[...s].map(e=>$(e));if(s instanceof Map||s instanceof Set)return s;if(re(s)){let e={};for(let t of Object.keys(s))e[t]=$(s[t]);return e}return s}function F(s=0){return new Promise(e=>{setTimeout(()=>e(),s)})}var k=g(),I=class{_internalStorage;isLocalStorageEnabled;constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&k.localStorage?k.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&k.localStorage?k.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&k.localStorage?t=k.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{k.localStorage,k.localStorage.setItem("__scLocalStorageTest",1),k.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var z=class{id;socket;procedure;data;sent;constructor(e,t,n,r){this.socket=e,this.id=t,this.procedure=n,this.data=r,this.sent=!1}end(e,t){let n={rid:this.id};e!==void 0&&(n.data=e),this._respond(n,t)}error(e,t){let n={rid:this.id,error:Z(e)};this._respond(n,t)}_respond(e,t){if(this.sent)throw new _(`Response to request ${this.id} has already been sent`);this.sent=!0,this.socket.sendObject(e,t)}};function se(s){return typeof s=="function"}function ie(s,e){let t=g();if(t&&se(t.WebSocket))return new t.WebSocket(s);throw Error("WebSocket instance not found")}var d=class{state;auth;codec;options;wsOptions;protocolVersion;connectTimeout;pingTimeout;pingTimeoutDisabled;callIdGenerator;authTokenName;isBufferingBatch;socket;_pingTimeoutTicker;_callbackMap;_batchBuffer;_onOpenHandler;_onOpenAbortHandler;_onCloseHandler;_onEventHandler;_onErrorHandler;_onInboundInvokeHandler;_onInboundTransmitHandler;_connectTimeoutRef;_handlePing;constructor(e,t,n,r,i){this.state=d.CLOSED,this.auth=e,this.codec=t,this.options=n,this.wsOptions=r,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],i||(i={}),this._onOpenHandler=i.onOpen||function(){},this._onOpenAbortHandler=i.onOpenAbort||function(){},this._onCloseHandler=i.onClose||function(){},this._onEventHandler=i.onEvent||function(){},this._onErrorHandler=i.onError||function(){},this._onInboundInvokeHandler=i.onInboundInvoke||function(){},this._onInboundTransmitHandler=i.onInboundTransmit||function(){},this.state=d.CONNECTING;let o=this.uri(),u=ie(o,r);u.binaryType=this.options.binaryType,this.socket=u,u.onopen=()=>{this._onOpen()},u.onclose=async a=>{let c;a.code==null?c=1005:c=a.code,this._destroy(c,a.reason)},u.onmessage=(a,c)=>{this._onMessage(a.data)},u.onerror=()=>{this.state===d.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=a=>a==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=a=>a===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let e=this.options.query||{},t;this.options.protocolScheme==null?t=this.options.secure?"wss":"ws":t=this.options.protocolScheme,this.options.timestampRequests&&(e[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[o,u]of Object.entries(e))if(Array.isArray(u))for(let a of u)n.append(o,a);else n.set(o,`${u}`);e=n.toString(),e.length&&(e="?"+e);let r,i;if(this.options.socketPath==null){if(this.options.host)r=this.options.host;else{let o="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="ws"&&this.options.port!==80)&&(o=":"+this.options.port),r=this.options.hostname+o}i=this.options.path}else r=this.options.socketPath,i=`:${this.options.path}`;return t+"://"+r+i+e}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let e=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(e)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(e,t){(this.state===d.OPEN||this.state===d.CONNECTING)&&(e=e||1e3,this._destroy(e,t),this.socket.close(e,t))}transmitObject(e){let t={event:e.event,data:e.data};return e.callback&&(t.cid=e.cid=this.callIdGenerator(),this._callbackMap[e.cid]=e),this.sendObject(t),e.cid||null}transmit(e,t,n){let r={event:e,data:t};return(this.state===d.OPEN||n.force)&&this.transmitObject(r),Promise.resolve()}invokeRaw(e,t,n,r){let i={event:e,data:t,callback:r};n.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let o=null;return(this.state===d.OPEN||n.force)&&(o=this.transmitObject(i)),o}invoke(e,t,n){return new Promise((r,i)=>{this.invokeRaw(e,t,n,(o,u)=>{if(o){i(o);return}r(u)})})}cancelPendingResponse(e){delete this._callbackMap[e]}decode(e){return this.codec.decode(e)}encode(e){return this.codec.encode(e)}send(e){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(e)}serializeObject(e){let t;try{t=this.encode(e)}catch(n){return this._onError(n),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}_handleEventAckTimeout(e){e.cid&&delete this._callbackMap[e.cid],delete e.timeout;let t=e.callback;if(t){delete e.callback;let n=new C(`Event response for "${e.event}" timed out`);t.call(e,n,e)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let e;try{e=await this._handshake()}catch(t){t.statusCode==null&&(t.statusCode=4003),this._onError(t),this._destroy(t.statusCode,t.toString()),this.socket.close(t.statusCode);return}this.state=d.OPEN,e&&(this.pingTimeout=e.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(e)}async _handshake(){let e=await this.auth.loadToken(this.authTokenName),t={force:!0},n=await this.invoke("#handshake",{authToken:e},t);return n&&(n.authToken=e,n.authError&&(n.authError=w(n.authError))),n}_abortAllPendingEventsDueToBadConnection(e){Object.keys(this._callbackMap||{}).forEach(t=>{let n=this._callbackMap[t];delete this._callbackMap[t],clearTimeout(n.timeout),delete n.timeout;let r=`Event "${n.event}" was aborted due to a bad connection`,i=new S(r,e),o=n.callback;o&&(delete n.callback,o.call(n,i,n))})}_destroy(e,t){!t&&B[e]&&(t=B[e]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===d.OPEN?(this.state=d.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===d.CONNECTING?(this.state=d.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===d.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new z(this,e.cid,e.event,e.data);this._onInboundInvokeHandler(n)}else if(e&&e.rid!=null){let n=this._callbackMap[e.rid];if(n&&(clearTimeout(n.timeout),delete n.timeout,delete this._callbackMap[e.rid],n.callback)){let r=w(e.error);n.callback(r,e.data)}}else this._onEventHandler({event:"raw",data:{message:t}})}_onMessage(e){if(this._onEventHandler({event:"message",data:{message:e}}),this._handlePing(e))return;let t=this.decode(e);if(Array.isArray(t)){let n=t.length;for(let r=0;r<n;r++)this._processInboundPacket(t[r],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},v=d;h(v,"CONNECTING","connecting"),h(v,"OPEN","open"),h(v,"CLOSED","closed");var xe=typeof window<"u",q=g(),l=class extends U{options;id;clientId;version;protocolVersion;state;authState;signedAuthToken;authToken;authTokenName;wsOptions;pendingReconnect;pendingReconnectTimeout;preparingPendingSubscriptions;ackTimeout;connectTimeout;pingTimeout;pingTimeoutDisabled;channelPrefix;disconnectOnUnload;connectAttempts;isBatching;batchOnHandshake;batchOnHandshakeDuration;auth;codec;transport;poolIndex;_batchingIntervalId;_outboundBuffer;_channelMap;_channelEventDemux;_channelDataDemux;_receiverDemux;_procedureDemux;_cid;_reconnectTimeoutRef;_privateDataHandlerMap={"#publish":e=>{let t=this._undecorateChannelName(e.channel);this.isSubscribed(t,!0)&&this._channelDataDemux.write(t,e.data)},"#kickOut":e=>{let t=this._undecorateChannelName(e.channel),n=this._channelMap[t];n&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};_privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new x("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};constructor(e){super();let n=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},e);this.id=null,this.version=n.version||null,this.protocolVersion=n.protocolVersion,this.state=l.CLOSED,this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let r=Math.pow(2,31)-1,i=o=>{if(this[o]>r)throw new f(`The ${o} value provided exceeded the maximum amount allowed`)};if(i("connectTimeout"),i("ackTimeout"),i("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new V,this._channelMap={},this._channelEventDemux=new b,this._channelDataDemux=new b,this._receiverDemux=new b,this._procedureDemux=new b,this.options=n,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let o=this.options.autoReconnectOptions;o.initialDelay==null&&(o.initialDelay=1e4),o.randomness==null&&(o.randomness=1e4),o.multiplier==null&&(o.multiplier=1.5),o.maxDelay==null&&(o.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new I,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=te,this.options.protocol){let o=new f('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=n.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),u={};o.forEach((a,c)=>{let O=u[c];O==null?u[c]=a:(Array.isArray(O)||(u[c]=[O]),u[c].push(a))}),this.options.query=u}xe&&this.disconnectOnUnload&&q.addEventListener&&q.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this.state!==l.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await F(0)}connect(){if(this.state===l.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=l.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=l.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==l.CLOSED&&(this.state=l.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==l.CLOSED&&(this.state=l.CLOSED,this._destroy(t.code,t.reason))},onEvent:t=>{this.emit(t.event,t.data)},onError:t=>{this._onError(t.error)},onInboundInvoke:t=>{this._onInboundInvoke(t)},onInboundTransmit:t=>{this._onInboundTransmit(t.event,t.data)}};this.transport=new v(this.auth,this.codec,this.options,this.wsOptions,e)}}reconnect(e,t){this.disconnect(e,t),this.connect()}disconnect(e,t){if(e=e||1e3,typeof e!="number")throw new f("If specified, the code argument must be a number");let n=this.state===l.CONNECTING;n||this.state===l.OPEN?(this.state=l.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return W.default.from(e,"base64").toString("utf8")}encodeBase64(e){return W.default.from(e,"utf8").toString("base64")}getAuthToken(){return this.authToken}getSignedAuthToken(){return this.signedAuthToken}async authenticate(e){let t;try{t=await this.invoke("#authenticate",e)}catch(n){throw n.name!=="BadConnectionError"&&n.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await F(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=w(t.authError)):t={isAuthenticated:this.authState,authError:null},t.isAuthenticated?this._changeToAuthenticatedState(e):this._changeToUnauthenticatedStateAndClearTokens(),(async()=>{try{await this.auth.saveToken(this.authTokenName,e,{})}catch(n){this._onError(n)}})(),await F(0),t}decode(e){return this.transport.decode(e)}encode(e){return this.transport.encode(e)}send(e){this.transport.send(e)}transmit(e,t,n){return this._processOutboundEvent(e,t,n)}invoke(e,t,n){return this._processOutboundEvent(e,t,n,!0)}transmitPublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",n)}invokePublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",n)}startBatch(){this.transport.startBatch()}flushBatch(){this.transport.flushBatch()}cancelBatch(){this.transport.cancelBatch()}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}subscribe(e,t){t=t||{};let n=this._channelMap[e],r={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(r.priority=t.priority),t.data!==void 0&&(r.data=t.data),n?t&&(n.options=r):(n={name:e,state:m.PENDING,options:r},this._channelMap[e]=n,this._trySubscribe(n)),new m(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&(this._triggerChannelUnsubscribe(t),this._tryUnsubscribe(t))}receiver(e){return this._receiverDemux.stream(e)}closeReceiver(e){this._receiverDemux.close(e)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(e){this._receiverDemux.kill(e)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(e){this._receiverDemux.killConsumer(e)}getReceiverConsumerStats(e){return this._receiverDemux.getConsumerStats(e)}getReceiverConsumerStatsList(e){return this._receiverDemux.getConsumerStatsList(e)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(e){return this._receiverDemux.getBackpressure(e)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(e){return this._receiverDemux.getConsumerBackpressure(e)}hasReceiverConsumer(e,t){return this._receiverDemux.hasConsumer(e,t)}hasAnyReceiverConsumer(e){return this._receiverDemux.hasConsumerAll(e)}procedure(e){return this._procedureDemux.stream(e)}closeProcedure(e){this._procedureDemux.close(e)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(e){this._procedureDemux.kill(e)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(e){this._procedureDemux.killConsumer(e)}getProcedureConsumerStats(e){return this._procedureDemux.getConsumerStats(e)}getProcedureConsumerStatsList(e){return this._procedureDemux.getConsumerStatsList(e)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(e){return this._procedureDemux.getBackpressure(e)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(e){return this._procedureDemux.getConsumerBackpressure(e)}hasProcedureConsumer(e,t){return this._procedureDemux.hasConsumer(e,t)}hasAnyProcedureConsumer(e){return this._procedureDemux.hasConsumerAll(e)}channel(e){return new m(e,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(e){this.channelCloseOutput(e),this.channelCloseAllListeners(e)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(e){this.channelKillOutput(e),this.channelKillAllListeners(e)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(e){this._channelDataDemux.killConsumer(e)}killChannelListenerConsumer(e){this._channelEventDemux.killConsumer(e)}getChannelOutputConsumerStats(e){return this._channelDataDemux.getConsumerStats(e)}getChannelListenerConsumerStats(e){return this._channelEventDemux.getConsumerStats(e)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(e){return Math.max(this.channelGetOutputBackpressure(e),this.channelGetAllListenersBackpressure(e))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(e){return this._channelEventDemux.getConsumerBackpressure(e)}getChannelOutputConsumerBackpressure(e){return this._channelDataDemux.getConsumerBackpressure(e)}hasAnyChannelOutputConsumer(e){return this._channelDataDemux.hasConsumerAll(e)}hasAnyChannelListenerConsumer(e){return this._channelEventDemux.hasConsumerAll(e)}getChannelState(e){let t=this._channelMap[e];return t?t.state:m.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?{...t.options}:{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.close(t)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.kill(t)})}channelGetOutputConsumerStatsList(e){return this._channelDataDemux.getConsumerStatsList(e)}channelGetListenerConsumerStatsList(e,t){return this._channelEventDemux.getConsumerStatsList(`${e}/${t}`)}channelGetAllListenersConsumerStatsList(e){return this._getAllChannelStreamNames(e).map(t=>this._channelEventDemux.getConsumerStatsList(t)).reduce((t,n)=>(n.forEach(r=>{t.push(r)}),t),[])}channelGetOutputBackpressure(e){return this._channelDataDemux.getBackpressure(e)}channelGetListenerBackpressure(e,t){return this._channelEventDemux.getBackpressure(`${e}/${t}`)}channelGetAllListenersBackpressure(e){let t=this._getAllChannelStreamNames(e).map(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,n){return this._channelEventDemux.hasConsumer(`${e}/${t}`,n)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(n=>this._channelEventDemux.hasConsumer(n,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(n=>{(e||this._channelMap[n].state===m.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===m.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===m.PENDING&&e.push(n)}),e.sort((t,n)=>{let r=t.options.priority||0,i=n.options.priority||0;return r>i?-1:r<i?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,r)=>(n[r.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===l.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let n=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",n,t)}}_triggerChannelUnsubscribe(e,t){let n=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===m.SUBSCRIBED){let r={oldChannelState:e.state,newChannelState:t?m.PENDING:m.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,r),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...r}),this.emit("unsubscribe",{channel:n})}t?e.state=m.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===l.AUTHENTICATED;if(this.state===l.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},r={};e.options.waitForAuth&&(n.waitForAuth=!0,r.waitForAuth=n.waitForAuth),e.options.data&&(r.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...r},n,i=>{if(i){if(i.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(i,e,r)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,r)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:r})}}_cancelBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.cancelBatch()}_stopBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.flushBatch()}_startBatching(){this._batchingIntervalId==null&&(this.startBatch(),this._batchingIntervalId=setInterval(()=>{this.flushBatch(),this.startBatch()},this.options.batchInterval))}_undecorateChannelName(e){return this.channelPrefix&&e.indexOf(this.channelPrefix)===0?e.replace(this.channelPrefix,""):e}_decorateChannelName(e){return this.channelPrefix&&(e=this.channelPrefix+e),e}_cancelPendingSubscribeCallback(e){e._pendingSubscriptionCid!=null&&(this.transport.cancelPendingResponse(e._pendingSubscriptionCid),delete e._pendingSubscriptionCid)}_triggerChannelSubscribeFail(e,t,n){let r=t.name,i=!t.options.waitForAuth||this.authState===l.AUTHENTICATED;!!this._channelMap[r]&&i&&(delete this._channelMap[r],this._channelEventDemux.write(`${r}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:r,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==m.SUBSCRIBED){let r=e.state;e.state=m.SUBSCRIBED;let i={oldChannelState:r,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,r){n=n||{},this.state===l.CLOSED&&this.connect();let i={event:e,data:null},o;r?o=new Promise((c,O)=>{i.callback=(J,ue)=>{if(J){O(J);return}c(ue)}}):o=Promise.resolve();let u=new j;this.options.cloneData?i.data=$(t):i.data=t,u.data=i;let a=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i,u)},a),this._outboundBuffer.append(u),this.state===l.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let r=new C(`Event response for "${e.event}" timed out`);n.call(e,r,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let n=e.data;e.detach(),this.transport.transmitObject(n),e=t}}_onInboundInvoke(e){let{procedure:t,data:n}=e,r=this._privateRPCHandlerMap[t];r?r.call(this,n,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let n=this._privateDataHandlerMap[e];n?n.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!l.ignoreStatuses[e]){let r;t?r="Socket connection closed with status code "+e+" and reason: "+t:r="Socket connection closed with status code "+e;let i=new E(l.errorStatuses[e]||r,e);this._onError(i)}this._abortAllPendingEventsDueToBadConnection(n?"connectAbort":"disconnect"),this.options.autoReconnect&&(e===4e3||e===4001||e===1005?this._tryReconnect(0):e!==1e3&&e<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(e){let t=this._outboundBuffer.head,n;for(;t;){n=t.next;let r=t.data;clearTimeout(r.timeout),delete r.timeout,t.detach(),t=n;let i=r.callback;if(i){delete r.callback;let o=`Event "${r.event}" was aborted due to a bad connection`,u=new S(o,e);i.call(r,u,r)}r.cid&&this.transport.cancelPendingResponse(r.cid)}}_suspendSubscriptions(){Object.keys(this._channelMap).forEach(e=>{let t=this._channelMap[e];this._triggerChannelUnsubscribe(t,!0)})}_onError(e){this.emit("error",{error:e})}_tryReconnect(e){let t=this.connectAttempts++,n=this.options.autoReconnectOptions,r;if(e==null||t>0){let i=Math.round(n.initialDelay+(n.randomness||0)*Math.random());r=Math.round(i*Math.pow(n.multiplier,t))}else r=e;r>n.maxDelay&&(r=n.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=r,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},r)}_onOpen(e){this.isBatching?this._startBatching():this.batchOnHandshake&&(this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)),this.preparingPendingSubscriptions=!0,e?(this.id=e.id,this.pingTimeout=e.pingTimeout,e.isAuthenticated?this._changeToAuthenticatedState(e.authToken):this._changeToUnauthenticatedStateAndClearTokens()):this._changeToUnauthenticatedStateAndClearTokens(),this.connectAttempts=0,this.options.autoSubscribeOnConnect&&this.processPendingSubscriptions(),this.emit("connect",{...e,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===l.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let r=n;try{return r=this.decodeBase64(r),JSON.parse(r)}catch{return r}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==l.AUTHENTICATED){let t=this.authState;this.authState=l.AUTHENTICATED;let n={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==l.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let r={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",r),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,q.addEventListener("beforeunload",e,!1))},r=()=>{t&&(t=!1,q.removeEventListener("beforeunload",e,!1))};(async()=>{let i=this.listener("connecting").createConsumer();for(;!(await i.next()).done;)n()})(),(async()=>{let i=this.listener("close").createConsumer();for(;!(await i.next()).done;)r()})()}_setAuthToken(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this._changeToUnauthenticatedStateAndClearTokens()}},p=l;h(p,"CONNECTING","connecting"),h(p,"OPEN","open"),h(p,"CLOSED","closed"),h(p,"AUTHENTICATED","authenticated"),h(p,"UNAUTHENTICATED","unauthenticated"),h(p,"SUBSCRIBED","subscribed"),h(p,"PENDING","pending"),h(p,"UNSUBSCRIBED","unsubscribed"),h(p,"ignoreStatuses",Y),h(p,"errorStatuses",B);var K=g();function Ee(){return K.location&&location.protocol==="https:"}function Ae(s,e){let t=s.secure==null?e:s.secure;return s.port||(K.location&&location.port?parseFloat(location.port):t?443:80)}function oe(s){if(s=s||{},s.host&&!s.host.match(/[^:]+:\d{2,5}/))throw new f('The host option should include both the hostname and the port number in the format "hostname:port"');if(s.host&&s.hostname)throw new f('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and hostname options together');if(s.host&&s.port)throw new f('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and port options together');let e=Ee(),t={clientId:ee(),port:Ae(s,e),hostname:K.location&&location.hostname||"localhost",secure:e};return Object.assign(t,s),new p(t)}var ae="1.0.0";function Oe(s){return oe({...s,version:ae})}0&&(module.exports={AuthEngine,TGClientSocket,TGTransport,create,version}); |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkZNIU5T3Xjs = require('./chunk-ZNIU5T3X.js');require('./chunk-L63Q7CFL.js');exports.WritableConsumableStream = _chunkZNIU5T3Xjs.a; | ||
var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});module.exports=b(v);var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};0&&(module.exports={WritableConsumableStream}); |
{ | ||
"name": "topgun-socket", | ||
"version": "1.2.2", | ||
"version": "1.2.3", | ||
"description": "Scalable realtime pub/sub and RPC serverless framework", | ||
@@ -5,0 +5,0 @@ "publishConfig": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
451671
2896
2
0
24