topgun-socket
Advanced tools
Comparing version 1.0.5 to 1.1.0
@@ -1,1 +0,1 @@ | ||
var topGunSocket=(()=>{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 b=(n,e)=>{for(var t in e)u(n,t,{get:e[t],enumerable:!0})},S=(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=>S(u({},"__esModule",{value:!0}),n);var l=(n,e,t)=>(C(n,typeof e!="symbol"?e+"":e,t),t);var d={};b(d,{TGChannel:()=>i});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");return p(d);})(); | ||
var topGunSocket=(()=>{var c=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var L=(n,t)=>{for(var e in t)c(n,e,{get:t[e],enumerable:!0})},g=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of p(t))!d.call(n,r)&&r!==e&&c(n,r,{get:()=>t[r],enumerable:!(s=S(t,r))||s.enumerable});return n};var B=n=>g(c({},"__esModule",{value:!0}),n);var C=(n,t,e)=>new Promise((s,r)=>{var m=i=>{try{o(e.next(i))}catch(h){r(h)}},b=i=>{try{o(e.throw(i))}catch(h){r(h)}},o=i=>i.done?s(i.value):Promise.resolve(i.value).then(m,b);o((e=e.apply(n,t)).next())});var y={};L(y,{TGChannel:()=>a});var l=class{next(t){return C(this,null,function*(){let e=this.createConsumer(t),s=yield e.next();return e.return(),s})}once(t){return C(this,null,function*(){let e=yield this.next(t);return e.done&&(yield new Promise(()=>{})),e.value})}createConsumer(t){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class extends l{constructor(e,s,r,m){super();this.PENDING=u.PENDING,this.SUBSCRIBED=u.SUBSCRIBED,this.UNSUBSCRIBED=u.UNSUBSCRIBED,this.name=e,this.client=s,this._eventDemux=r,this._dataStream=m.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,s){return this.client.channelHasListenerConsumer(this.name,e,s)}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)}},a=u;a.PENDING="pending",a.SUBSCRIBED="subscribed",a.UNSUBSCRIBED="unsubscribed";return B(y);})(); |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkFOM74K3Hjs = require('./chunk-FOM74K3H.js');require('./chunk-EQT5ZTTX.js');exports.TGChannel = _chunkFOM74K3Hjs.a; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk26YZNXPKjs = require('./chunk-26YZNXPK.js');require('./chunk-MY4YFY5T.js');exports.TGChannel = _chunk26YZNXPKjs.a; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;var _chunk2MN4DLM7js = require('./chunk-2MN4DLM7.js');var _chunkFOM74K3Hjs = require('./chunk-FOM74K3H.js');require('./chunk-WSYY47HQ.js');var _chunkEQT5ZTTXjs = require('./chunk-EQT5ZTTX.js');function F(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}var _2 = require('buffer/');function A(a,e){if(!e)return a;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)a.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];a.append(n)}}return a}var x=class{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 D= (_class =class{__init() {this.item=null}constructor(e){;_class.prototype.__init.call(this);this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}}, _class);var y=class{static from(e){let t=new this;return A(t,e)}static of(...e){let t=new this;return A(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,A(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 D(this.head)}};function O(a=0){return new Promise(e=>{setTimeout(()=>e(),a)})}var g=_chunk2MN4DLM7js.t.call(void 0, ),B= exports.AuthEngine =class{constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&g.localStorage?t=g.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{g.localStorage,g.localStorage.setItem("__scLocalStorageTest",1),g.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var _ws = require('ws'); var _ws2 = _interopRequireDefault(_ws);var z=_chunk2MN4DLM7js.t.call(void 0, ),I,L;_optionalChain([z, 'optionalAccess', _4 => _4.WebSocket])?(I=z.WebSocket,L=function(a,e){return new I(a)}):(I=_ws2.default,L=function(a,e){return new I(a,[],e)});var c=class{constructor(e,t,n,i,s){this.state=c.CLOSED,this.auth=e,this.codec=t,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(),l=L(r,i);l.binaryType=this.options.binaryType,this.socket=l,l.onopen=()=>{this._onOpen()},l.onclose=async h=>{let p;h.code==null?p=1005:p=h.code,this._destroy(p,h.reason)},l.onmessage=(h,p)=>{this._onMessage(h.data)},l.onerror=h=>{this.state===c.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=h=>h==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=h=>h===""?(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[r,l]of Object.entries(e))if(Array.isArray(l))for(let h of l)n.append(r,h);else n.set(r,l);e=n.toString(),e.length&&(e="?"+e);let i,s;if(this.options.socketPath==null){if(this.options.host)i=this.options.host;else{let r="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="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 t+"://"+i+s+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===c.OPEN||this.state===c.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 i={event:e,data:t};return(this.state===c.OPEN||n.force)&&this.transmitObject(i),Promise.resolve()}invokeRaw(e,t,n,i){let s={event:e,data:t,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(e,t,n){return new Promise((i,s)=>{this.invokeRaw(e,t,n,(r,l)=>{if(r){s(r);return}i(l)})})}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 (0, _chunk2MN4DLM7js.m)(`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=c.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=_chunk2MN4DLM7js.s.call(void 0, 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 i=`Event "${n.event}" was aborted due to a bad connection`,s=new (0, _chunk2MN4DLM7js.n)(i,e),r=n.callback;r&&(delete n.callback,r.call(n,s,n))})}_destroy(e,t){let n=_chunk2MN4DLM7js.p[e];!t&&_chunk2MN4DLM7js.p[e]&&(t=_chunk2MN4DLM7js.p[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===c.OPEN?(this.state=c.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===c.CONNECTING?(this.state=c.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===c.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new (0, _chunk2MN4DLM7js.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 i=_chunk2MN4DLM7js.s.call(void 0, e.error);n.callback(i,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 i=0;i<n;i++)this._processInboundPacket(t[i],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}_resetPingTimeout(){if(this.pingTimeoutDisabled)return;let e=new Date().getTime();clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout)}},v= exports.TGTransport =c;_chunkEQT5ZTTXjs.a.call(void 0, v,"CONNECTING","connecting"),_chunkEQT5ZTTXjs.a.call(void 0, v,"OPEN","open"),_chunkEQT5ZTTXjs.a.call(void 0, v,"CLOSED","closed");var X=typeof window<"u",w=_chunk2MN4DLM7js.t.call(void 0, ),o= (_class2 =class extends _chunk2MN4DLM7js.v{__init2() {this._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(e)}}}__init3() {this._privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new (0, _chunk2MN4DLM7js.j)("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(e),t.end()}}}constructor(e){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},e);this.id=null,this.version=n.version||null,this.protocolVersion=n.protocolVersion,this.state=o.CLOSED,this.authState=o.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, _chunk2MN4DLM7js.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 y,this._channelMap={},this._channelEventDemux=new _chunk2MN4DLM7js.u,this._channelDataDemux=new _chunk2MN4DLM7js.u,this._receiverDemux=new _chunk2MN4DLM7js.u,this._procedureDemux=new _chunk2MN4DLM7js.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=_chunk2MN4DLM7js.w,this.options.protocol){let r=new (0, _chunk2MN4DLM7js.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),l={};r.forEach((h,p)=>{let k=l[p];k==null?l[p]=h:(Array.isArray(k)||(l[p]=[k]),l[p].push(h))}),this.options.query=l}X&&this.disconnectOnUnload&&w.addEventListener&&w.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!==o.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await O(0)}connect(){if(this.state===o.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=o.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=o.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==o.CLOSED&&(this.state=o.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==o.CLOSED&&(this.state=o.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 (0, _chunk2MN4DLM7js.h)("If specified, the code argument must be a number");let n=this.state===o.CONNECTING;n||this.state===o.OPEN?(this.state=o.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return _2.Buffer.from(e,"base64").toString("utf8")}encodeBase64(e){return _2.Buffer.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 O(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=_chunk2MN4DLM7js.s.call(void 0, 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 O(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],i={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(i.priority=t.priority),t.data!==void 0&&(i.data=t.data),n?t&&(n.options=i):(n={name:e,state:_chunkFOM74K3Hjs.a.PENDING,options:i},this._channelMap[e]=n,this._trySubscribe(n)),new (0, _chunkFOM74K3Hjs.a)(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){let t=this._channelMap[e];return new (0, _chunkFOM74K3Hjs.a)(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:_chunkFOM74K3Hjs.a.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){let t=this._getAllChannelStreamNames(e).forEach(n=>{this._channelEventDemux.close(n)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(n=>{this._channelEventDemux.kill(n)})}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(i=>{t.push(i)}),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===_chunkFOM74K3Hjs.a.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===_chunkFOM74K3Hjs.a.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===_chunkFOM74K3Hjs.a.PENDING&&e.push(n)}),e.sort((t,n)=>{let i=t.options.priority||0,s=n.options.priority||0;return i>s?-1:i<s?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,i)=>(n[i.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===o.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===_chunkFOM74K3Hjs.a.SUBSCRIBED){let i={oldChannelState:e.state,newChannelState:t?_chunkFOM74K3Hjs.a.PENDING:_chunkFOM74K3Hjs.a.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("unsubscribe",{channel:n})}t?e.state=_chunkFOM74K3Hjs.a.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===o.AUTHENTICATED;if(this.state===o.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},i={};e.options.waitForAuth&&(n.waitForAuth=!0,i.waitForAuth=n.waitForAuth),e.options.data&&(i.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...i},n,s=>{if(s){if(s.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(s,e,i)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,i)}),this.emit("subscribeRequest",{channel:e.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(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 i=t.name,s=!t.options.waitForAuth||this.authState===o.AUTHENTICATED;!!this._channelMap[i]&&s&&(delete this._channelMap[i],this._channelEventDemux.write(`${i}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:i,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==_chunkFOM74K3Hjs.a.SUBSCRIBED){let i=e.state;e.state=_chunkFOM74K3Hjs.a.SUBSCRIBED;let s={oldChannelState:i,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,s),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...s}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,i){n=n||{},this.state===o.CLOSED&&this.connect();let s={event:e,data:null},r;i?r=new Promise((p,k)=>{s.callback=(R,J)=>{if(R){k(R);return}p(J)}}):r=Promise.resolve();let l=new x;this.options.cloneData?s.data=_chunk2MN4DLM7js.y.call(void 0, t):s.data=t,l.data=s;let h=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return s.timeout=setTimeout(()=>{this._handleEventAckTimeout(s,l)},h),this._outboundBuffer.append(l),this.state===o.OPEN&&this._flushOutboundBuffer(),r}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let i=new (0, _chunk2MN4DLM7js.m)(`Event response for "${e.event}" timed out`);n.call(e,i,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,i=this._privateRPCHandlerMap[t];i?i.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}),!o.ignoreStatuses[e]){let i;t?i="Socket connection closed with status code "+e+" and reason: "+t:i="Socket connection closed with status code "+e;let s=new (0, _chunk2MN4DLM7js.k)(o.errorStatuses[e]||i,e);this._onError(s)}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 i=t.data;clearTimeout(i.timeout),delete i.timeout,t.detach(),t=n;let s=i.callback;if(s){delete i.callback;let r=`Event "${i.event}" was aborted due to a bad connection`,l=new (0, _chunk2MN4DLM7js.n)(r,e);s.call(i,l,i)}i.cid&&this.transport.cancelPendingResponse(i.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,i;if(e==null||t>0){let s=Math.round(n.initialDelay+(n.randomness||0)*Math.random());i=Math.round(s*Math.pow(n.multiplier,t))}else i=e;i>n.maxDelay&&(i=n.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=i,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},i)}_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===o.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let i=n;try{return i=this.decodeBase64(i),JSON.parse(i)}catch (e2){return i}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==o.AUTHENTICATED){let t=this.authState;this.authState=o.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!==o.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=o.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let i={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",i),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,w.addEventListener("beforeunload",e,!1))},i=()=>{t&&(t=!1,w.removeEventListener("beforeunload",e,!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(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(e){(async()=>{let t;try{t=await this.auth.removeToken(this.authTokenName)}catch(n){this._onError(n);return}this.emit("removeAuthToken",{oldAuthToken:t})})(),this._changeToUnauthenticatedStateAndClearTokens()}}, _class2),m= exports.TGClientSocket =o;_chunkEQT5ZTTXjs.a.call(void 0, m,"CONNECTING","connecting"),_chunkEQT5ZTTXjs.a.call(void 0, m,"OPEN","open"),_chunkEQT5ZTTXjs.a.call(void 0, m,"CLOSED","closed"),_chunkEQT5ZTTXjs.a.call(void 0, m,"AUTHENTICATED","authenticated"),_chunkEQT5ZTTXjs.a.call(void 0, m,"UNAUTHENTICATED","unauthenticated"),_chunkEQT5ZTTXjs.a.call(void 0, m,"SUBSCRIBED","subscribed"),_chunkEQT5ZTTXjs.a.call(void 0, m,"PENDING","pending"),_chunkEQT5ZTTXjs.a.call(void 0, m,"UNSUBSCRIBED","unsubscribed"),_chunkEQT5ZTTXjs.a.call(void 0, m,"ignoreStatuses",_chunk2MN4DLM7js.q),_chunkEQT5ZTTXjs.a.call(void 0, m,"errorStatuses",_chunk2MN4DLM7js.p);var N=_chunk2MN4DLM7js.t.call(void 0, );function Y(){return N.location&&location.protocol==="https:"}function Z(a,e){let t=a.secure==null?e:a.secure;return a.port||(N.location&&location.port?parseFloat(location.port):t?443:80)}function W(a){if(a=a||{},a.host&&!a.host.match(/[^:]+:\d{2,5}/))throw new (0, _chunk2MN4DLM7js.h)('The host option should include both the hostname and the port number in the format "hostname:port"');if(a.host&&a.hostname)throw new (0, _chunk2MN4DLM7js.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(a.host&&a.port)throw new (0, _chunk2MN4DLM7js.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 e=Y(),t={clientId:F(),port:Z(a,e),hostname:N.location&&location.hostname||"localhost",secure:e};return Object.assign(t,a),new m(t)}var K=_chunk2MN4DLM7js.t.call(void 0, ),P=_optionalChain([K, 'optionalAccess', _5 => _5.WebSocket])||_optionalChain([K, 'optionalAccess', _6 => _6.MozWebSocket]);function ee(a,e,t){let n;return e?n=new P(a,e):n=new P(a),n}P&&(ee.prototype=P.prototype);var te="1.0.0";function Je(a){return W({...a,version:te})}exports.AuthEngine = B; exports.TGClientSocket = m; exports.TGTransport = v; exports.create = Je; exports.version = te; exports.ws = ee; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkKMDXU75Pjs = require('./chunk-KMDXU75P.js');var _chunk26YZNXPKjs = require('./chunk-26YZNXPK.js');require('./chunk-4FLQOCQE.js');var _chunkMY4YFY5Tjs = require('./chunk-MY4YFY5T.js');function J(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let n=Math.random()*16|0;return(o==="x"?n:n&3|8).toString(16)})}var _2 = require('buffer/');function O(o,n){if(!n)return o;if(n[Symbol.iterator]){let e=n[Symbol.iterator](),t;for(;(t=e.next())&&!t.done;)o.append(t.value)}else{let e=-1;for(;++e<n.length;){let t=n[e];o.append(t)}}return o}var B=class{constructor(){this.next=null,this.prev=null,this.list=null}append(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!e||this===n?!1:(n.detach(),this.next&&(n.next=this.next,this.next.prev=n),n.prev=this,n.list=e,this.next=n,(this===e.tail||!e.tail)&&(e.tail=n),e.size++,n)}prepend(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!e||this===n?!1:(n.detach(),this.prev&&(n.prev=this.prev,this.prev.next=n),n.next=this,n.list=e,this.prev=n,this===e.head&&(e.head=n),e.tail||(e.tail=this),e.size++,n)}detach(){let n=this.list;return n?(n.tail===this&&(n.tail=this.prev),n.head===this&&(n.head=this.next),n.tail===n.head&&(n.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,n.size--,this):this}};var I=class{constructor(n){this.item=null;this.item=n}next(){let n=this.item;return n?(this.item=n.next,{value:n,done:!1}):{value:null,done:!0}}};var w=class{static from(n){let e=new this;return O(e,n)}static of(...n){let e=new this;return O(e,n)}constructor(...n){this.size=0,this.tail=null,this.head=null,O(this,n)}append(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(n):this.head?this.head.append(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}prepend(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}toArray(){let n=this.head,e=[];for(;n;)e.push(n),n=n.next;return e}[Symbol.iterator](){return new I(this.head)}};function P(o=0){return new Promise(n=>{setTimeout(()=>n(),o)})}var b=_chunkKMDXU75Pjs.t.call(void 0, ),L= exports.AuthEngine =class{constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(n,e,t){return this.isLocalStorageEnabled&&b.localStorage?b.localStorage.setItem(n,e):this._internalStorage[n]=e,Promise.resolve(e)}removeToken(n){let e=this.loadToken(n);return this.isLocalStorageEnabled&&b.localStorage?b.localStorage.removeItem(n):delete this._internalStorage[n],e}loadToken(n){let e;return this.isLocalStorageEnabled&&b.localStorage?e=b.localStorage.getItem(n):e=this._internalStorage[n]||null,Promise.resolve(e)}_checkLocalStorageEnabled(){let n;try{b.localStorage,b.localStorage.setItem("__scLocalStorageTest",1),b.localStorage.removeItem("__scLocalStorageTest")}catch(e){n=e}return!n}};var _ws = require('ws'); var _ws2 = _interopRequireDefault(_ws);var N=_chunkKMDXU75Pjs.t.call(void 0, ),R,M;N!=null&&N.WebSocket?(R=N.WebSocket,M=function(o,n){return new R(o)}):(R=_ws2.default,M=function(o,n){return new R(o,[],n)});var c=class{constructor(n,e,t,i,s){this.state=c.CLOSED,this.auth=n,this.codec=e,this.options=t,this.wsOptions=i,this.protocolVersion=t.protocolVersion,this.connectTimeout=t.connectTimeout,this.pingTimeout=t.pingTimeout,this.pingTimeoutDisabled=!!t.pingTimeoutDisabled,this.callIdGenerator=t.callIdGenerator,this.authTokenName=t.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(),a=M(r,i);a.binaryType=this.options.binaryType,this.socket=a,a.onopen=()=>{this._onOpen()},a.onclose=h=>_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let g;h.code==null?g=1005:g=h.code,this._destroy(g,h.reason)}),a.onmessage=(h,g)=>{this._onMessage(h.data)},a.onerror=h=>{this.state===c.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=h=>h==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=h=>h===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let n=this.options.query||{},e;this.options.protocolScheme==null?e=this.options.secure?"wss":"ws":e=this.options.protocolScheme,this.options.timestampRequests&&(n[this.options.timestampParam]=new Date().getTime());let t=new URLSearchParams;for(let[r,a]of Object.entries(n))if(Array.isArray(a))for(let h of a)t.append(r,h);else t.set(r,a);n=t.toString(),n.length&&(n="?"+n);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+n}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 n=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(n)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(n,e){(this.state===c.OPEN||this.state===c.CONNECTING)&&(n=n||1e3,this._destroy(n,e),this.socket.close(n,e))}transmitObject(n){let e={event:n.event,data:n.data};return n.callback&&(e.cid=n.cid=this.callIdGenerator(),this._callbackMap[n.cid]=n),this.sendObject(e),n.cid||null}transmit(n,e,t){let i={event:n,data:e};return(this.state===c.OPEN||t.force)&&this.transmitObject(i),Promise.resolve()}invokeRaw(n,e,t,i){let s={event:n,data:e,callback:i};t.noTimeout||(s.timeout=setTimeout(()=>{this._handleEventAckTimeout(s)},this.options.ackTimeout));let r=null;return(this.state===c.OPEN||t.force)&&(r=this.transmitObject(s)),r}invoke(n,e,t){return new Promise((i,s)=>{this.invokeRaw(n,e,t,(r,a)=>{if(r){s(r);return}i(a)})})}cancelPendingResponse(n){delete this._callbackMap[n]}decode(n){return this.codec.decode(n)}encode(n){return this.codec.encode(n)}send(n){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(n)}serializeObject(n){let e;try{e=this.encode(n)}catch(t){return this._onError(t),null}return e}sendObject(n){if(this.isBufferingBatch){this._batchBuffer.push(n);return}let e=this.serializeObject(n);e!=null&&this.send(e)}_handleEventAckTimeout(n){n.cid&&delete this._callbackMap[n.cid],delete n.timeout;let e=n.callback;if(e){delete n.callback;let t=new (0, _chunkKMDXU75Pjs.m)(`Event response for "${n.event}" timed out`);e.call(n,t,n)}}_onOpen(){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let n;try{n=yield 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,n&&(this.pingTimeout=n.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(n)})}_handshake(){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let n=yield this.auth.loadToken(this.authTokenName),e={force:!0},t=yield this.invoke("#handshake",{authToken:n},e);return t&&(t.authToken=n,t.authError&&(t.authError=_chunkKMDXU75Pjs.s.call(void 0, t.authError))),t})}_abortAllPendingEventsDueToBadConnection(n){Object.keys(this._callbackMap||{}).forEach(e=>{let t=this._callbackMap[e];delete this._callbackMap[e],clearTimeout(t.timeout),delete t.timeout;let i=`Event "${t.event}" was aborted due to a bad connection`,s=new (0, _chunkKMDXU75Pjs.n)(i,n),r=t.callback;r&&(delete t.callback,r.call(t,s,t))})}_destroy(n,e){let t=_chunkKMDXU75Pjs.p[n];!e&&_chunkKMDXU75Pjs.p[n]&&(e=_chunkKMDXU75Pjs.p[n]),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:n,reason:e})):this.state===c.CONNECTING?(this.state=c.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:n,reason:e})):this.state===c.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(n,e){if(n&&n.event!=null)if(n.cid==null)this._onInboundTransmitHandler(_chunkMY4YFY5Tjs.a.call(void 0, {},n));else{let t=new (0, _chunkKMDXU75Pjs.z)(this,n.cid,n.event,n.data);this._onInboundInvokeHandler(t)}else if(n&&n.rid!=null){let t=this._callbackMap[n.rid];if(t&&(clearTimeout(t.timeout),delete t.timeout,delete this._callbackMap[n.rid],t.callback)){let i=_chunkKMDXU75Pjs.s.call(void 0, n.error);t.callback(i,n.data)}}else this._onEventHandler({event:"raw",data:{message:e}})}_onMessage(n){if(this._onEventHandler({event:"message",data:{message:n}}),this._handlePing(n))return;let e=this.decode(n);if(Array.isArray(e)){let t=e.length;for(let i=0;i<t;i++)this._processInboundPacket(e[i],n)}else this._processInboundPacket(e,n)}_onError(n){this._onErrorHandler({error:n})}_resetPingTimeout(){if(this.pingTimeoutDisabled)return;let n=new Date().getTime();clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout)}},T= exports.TGTransport =c;T.CONNECTING="connecting",T.OPEN="open",T.CLOSED="closed";var ee=typeof window!="undefined",H=_chunkKMDXU75Pjs.t.call(void 0, ),l=class extends _chunkKMDXU75Pjs.v{constructor(e){super();this._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),i=this._channelMap[t];i&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(i))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken(e)}};this._privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new (0, _chunkKMDXU75Pjs.j)("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(e),t.end()}};let i=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=i.version||null,this.protocolVersion=i.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=i.clientId,this.wsOptions=i.wsOptions,this.connectTimeout=i.connectTimeout,this.ackTimeout=i.ackTimeout,this.channelPrefix=i.channelPrefix||null,this.disconnectOnUnload=i.disconnectOnUnload==null?!0:i.disconnectOnUnload,this.authTokenName=i.authTokenName,i.pingTimeout=i.connectTimeout,this.pingTimeout=i.pingTimeout,this.pingTimeoutDisabled=!!i.pingTimeoutDisabled;let s=Math.pow(2,31)-1,r=a=>{if(this[a]>s)throw new (0, _chunkKMDXU75Pjs.h)(`The ${a} value provided exceeded the maximum amount allowed`)};if(r("connectTimeout"),r("ackTimeout"),r("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=i.batchOnHandshake,this.batchOnHandshakeDuration=i.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new w,this._channelMap={},this._channelEventDemux=new _chunkKMDXU75Pjs.u,this._channelDataDemux=new _chunkKMDXU75Pjs.u,this._receiverDemux=new _chunkKMDXU75Pjs.u,this._procedureDemux=new _chunkKMDXU75Pjs.u,this.options=i,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let a=this.options.autoReconnectOptions;a.initialDelay==null&&(a.initialDelay=1e4),a.randomness==null&&(a.randomness=1e4),a.multiplier==null&&(a.multiplier=1.5),a.maxDelay==null&&(a.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new L,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunkKMDXU75Pjs.w,this.options.protocol){let a=new (0, _chunkKMDXU75Pjs.h)('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(a)}if(this.options.query=i.query||{},typeof this.options.query=="string"){let a=new URLSearchParams(this.options.query),h={};a.forEach((g,k)=>{let S=h[k];S==null?h[k]=g:(Array.isArray(S)||(h[k]=[S]),h[k].push(g))}),this.options.query=h}ee&&this.disconnectOnUnload&&H.addEventListener&&H.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()}deauthenticate(){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let e;try{e=yield 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(),yield P(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 T(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 (0, _chunkKMDXU75Pjs.h)("If specified, the code argument must be a number");let i=this.state===l.CONNECTING;i||this.state===l.OPEN?(this.state=l.CLOSED,this._destroy(e,t,i),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return _2.Buffer.from(e,"base64").toString("utf8")}encodeBase64(e){return _2.Buffer.from(e,"utf8").toString("base64")}getAuthToken(){return this.authToken}getSignedAuthToken(){return this.signedAuthToken}authenticate(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t;try{t=yield this.invoke("#authenticate",e)}catch(i){throw i.name!=="BadConnectionError"&&i.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),yield P(0),i}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=_chunkKMDXU75Pjs.s.call(void 0, t.authError)):t={isAuthenticated:this.authState,authError:null},t.isAuthenticated?this._changeToAuthenticatedState(e):this._changeToUnauthenticatedStateAndClearTokens(),_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){try{yield this.auth.saveToken(this.authTokenName,e,{})}catch(i){this._onError(i)}}),yield P(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,i){return this._processOutboundEvent(e,t,i)}invoke(e,t,i){return this._processOutboundEvent(e,t,i,!0)}transmitPublish(e,t){let i={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",i)}invokePublish(e,t){let i={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",i)}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 i=this._channelMap[e],s={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(s.priority=t.priority),t.data!==void 0&&(s.data=t.data),i?t&&(i.options=s):(i={name:e,state:_chunk26YZNXPKjs.a.PENDING,options:s},this._channelMap[e]=i,this._trySubscribe(i)),new (0, _chunk26YZNXPKjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}unsubscribe(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){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){let t=this._channelMap[e];return new (0, _chunk26YZNXPKjs.a)(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:_chunk26YZNXPKjs.a.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?_chunkMY4YFY5Tjs.a.call(void 0, {},t.options):{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.close(i)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.kill(i)})}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,i)=>(i.forEach(s=>{t.push(s)}),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(i=>this._channelEventDemux.getBackpressure(i));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,i){return this._channelEventDemux.hasConsumer(`${e}/${t}`,i)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(i=>this._channelEventDemux.hasConsumer(i,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(i=>{(e||this._channelMap[i].state===_chunk26YZNXPKjs.a.SUBSCRIBED)&&t.push(i)}),t}isSubscribed(e,t){let i=this._channelMap[e];return t?!!i:!!i&&i.state===_chunk26YZNXPKjs.a.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let i=this._channelMap[t];i.state===_chunk26YZNXPKjs.a.PENDING&&e.push(i)}),e.sort((t,i)=>{let s=t.options.priority||0,r=i.options.priority||0;return s>r?-1:s<r?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(i=>i.stream.indexOf(`${e}/`)===0).reduce((i,s)=>(i[s.stream]=!0,i),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===l.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let i=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",i,t)}}_triggerChannelUnsubscribe(e,t){let i=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===_chunk26YZNXPKjs.a.SUBSCRIBED){let s={oldChannelState:e.state,newChannelState:t?_chunk26YZNXPKjs.a.PENDING:_chunk26YZNXPKjs.a.UNSUBSCRIBED};this._channelEventDemux.write(`${i}/subscribeStateChange`,s),this._channelEventDemux.write(`${i}/unsubscribe`,{}),this.emit("subscribeStateChange",_chunkMY4YFY5Tjs.a.call(void 0, {channel:i},s)),this.emit("unsubscribe",{channel:i})}t?e.state=_chunk26YZNXPKjs.a.PENDING:delete this._channelMap[i]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===l.AUTHENTICATED;if(this.state===l.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let i={noTimeout:!0},s={};e.options.waitForAuth&&(i.waitForAuth=!0,s.waitForAuth=i.waitForAuth),e.options.data&&(s.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",_chunkMY4YFY5Tjs.a.call(void 0, {channel:this._decorateChannelName(e.name)},s),i,r=>{if(r){if(r.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(r,e,s)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,s)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:s})}}_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,i){let s=t.name,r=!t.options.waitForAuth||this.authState===l.AUTHENTICATED;!!this._channelMap[s]&&r&&(delete this._channelMap[s],this._channelEventDemux.write(`${s}/subscribeFail`,{error:e,subscriptionOptions:i}),this.emit("subscribeFail",{error:e,channel:s,subscriptionOptions:i}))}_triggerChannelSubscribe(e,t){let i=e.name;if(e.state!==_chunk26YZNXPKjs.a.SUBSCRIBED){let s=e.state;e.state=_chunk26YZNXPKjs.a.SUBSCRIBED;let r={oldChannelState:s,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${i}/subscribeStateChange`,r),this._channelEventDemux.write(`${i}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",_chunkMY4YFY5Tjs.a.call(void 0, {channel:i},r)),this.emit("subscribe",{channel:i,subscriptionOptions:t})}}_processOutboundEvent(e,t,i,s){i=i||{},this.state===l.CLOSED&&this.connect();let r={event:e,data:null},a;s?a=new Promise((k,S)=>{r.callback=(V,Y)=>{if(V){S(V);return}k(Y)}}):a=Promise.resolve();let h=new B;this.options.cloneData?r.data=_chunkKMDXU75Pjs.y.call(void 0, t):r.data=t,h.data=r;let g=i.ackTimeout==null?this.ackTimeout:i.ackTimeout;return r.timeout=setTimeout(()=>{this._handleEventAckTimeout(r,h)},g),this._outboundBuffer.append(h),this.state===l.OPEN&&this._flushOutboundBuffer(),a}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let i=e.callback;if(i){delete e.callback;let s=new (0, _chunkKMDXU75Pjs.m)(`Event response for "${e.event}" timed out`);i.call(e,s,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let i=e.data;e.detach(),this.transport.transmitObject(i),e=t}}_onInboundInvoke(e){let{procedure:t,data:i}=e,s=this._privateRPCHandlerMap[t];s?s.call(this,i,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let i=this._privateDataHandlerMap[e];i?i.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,i){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),i?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 s;t?s="Socket connection closed with status code "+e+" and reason: "+t:s="Socket connection closed with status code "+e;let r=new (0, _chunkKMDXU75Pjs.k)(l.errorStatuses[e]||s,e);this._onError(r)}this._abortAllPendingEventsDueToBadConnection(i?"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,i;for(;t;){i=t.next;let s=t.data;clearTimeout(s.timeout),delete s.timeout,t.detach(),t=i;let r=s.callback;if(r){delete s.callback;let a=`Event "${s.event}" was aborted due to a bad connection`,h=new (0, _chunkKMDXU75Pjs.n)(a,e);r.call(s,h,s)}s.cid&&this.transport.cancelPendingResponse(s.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++,i=this.options.autoReconnectOptions,s;if(e==null||t>0){let r=Math.round(i.initialDelay+(i.randomness||0)*Math.random());s=Math.round(r*Math.pow(i.multiplier,t))}else s=e;s>i.maxDelay&&(s=i.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=s,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},s)}_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",_chunkMY4YFY5Tjs.b.call(void 0, _chunkMY4YFY5Tjs.a.call(void 0, {},e),{processPendingSubscriptions:()=>{this.processPendingSubscriptions()}})),this.state===l.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let i=(e||"").split(".")[1];if(i!=null){let s=i;try{return s=this.decodeBase64(s),JSON.parse(s)}catch(r){return s}}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 i={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",i)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==l.UNAUTHENTICATED){let e=this.authState,t=this.authToken,i=this.signedAuthToken;this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let s={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",s),this.emit("deauthenticate",{oldSignedAuthToken:i,oldAuthToken:t})}}_handleBrowserUnload(){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let e=()=>{this.disconnect()},t=!1,i=()=>{t||(t=!0,H.addEventListener("beforeunload",e,!1))},s=()=>{t&&(t=!1,H.removeEventListener("beforeunload",e,!1))};_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let r=this.listener("connecting").createConsumer();for(;!(yield r.next()).done;)i()}),_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let r=this.listener("close").createConsumer();for(;!(yield r.next()).done;)s()})})}_setAuthToken(e){this._changeToAuthenticatedState(e.token),_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){try{yield this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})}_removeAuthToken(e){_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t;try{t=yield this.auth.removeToken(this.authTokenName)}catch(i){this._onError(i);return}this.emit("removeAuthToken",{oldAuthToken:t})}),this._changeToUnauthenticatedStateAndClearTokens()}},m= exports.TGClientSocket =l;m.CONNECTING="connecting",m.OPEN="open",m.CLOSED="closed",m.AUTHENTICATED="authenticated",m.UNAUTHENTICATED="unauthenticated",m.SUBSCRIBED="subscribed",m.PENDING="pending",m.UNSUBSCRIBED="unsubscribed",m.ignoreStatuses=_chunkKMDXU75Pjs.q,m.errorStatuses=_chunkKMDXU75Pjs.p;var G=_chunkKMDXU75Pjs.t.call(void 0, );function te(){return G.location&&location.protocol==="https:"}function ne(o,n){let e=o.secure==null?n:o.secure;return o.port||(G.location&&location.port?parseFloat(location.port):e?443:80)}function X(o){if(o=o||{},o.host&&!o.host.match(/[^:]+:\d{2,5}/))throw new (0, _chunkKMDXU75Pjs.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, _chunkKMDXU75Pjs.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, _chunkKMDXU75Pjs.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 n=te(),e={clientId:J(),port:ne(o,n),hostname:G.location&&location.hostname||"localhost",secure:n};return Object.assign(e,o),new m(e)}var C=_chunkKMDXU75Pjs.t.call(void 0, ),U=(C==null?void 0:C.WebSocket)||(C==null?void 0:C.MozWebSocket);function ie(o,n,e){let t;return n?t=new U(o,n):t=new U(o),t}U&&(ie.prototype=U.prototype);var se="1.0.0";function Ye(o){return X(_chunkMY4YFY5Tjs.b.call(void 0, _chunkMY4YFY5Tjs.a.call(void 0, {},o),{version:se}))}exports.AuthEngine = L; exports.TGClientSocket = m; exports.TGTransport = T; exports.create = Ye; exports.version = se; exports.ws = ie; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _class;var _chunk2MN4DLM7js = require('./chunk-2MN4DLM7.js');var _chunkFOM74K3Hjs = require('./chunk-FOM74K3H.js');var _chunkWSYY47HQjs = require('./chunk-WSYY47HQ.js');var _chunkEQT5ZTTXjs = require('./chunk-EQT5ZTTX.js');var _webcrypto = require('@peculiar/webcrypto');var T=new _webcrypto.Crypto;if(typeof T>"u"||!T.subtle)throw new Error("SubtleCrypto not supported!");function Q(h){return new Uint8Array(Array.prototype.map.call(atob(h.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),e=>e.charCodeAt(0)))}function G(h){return btoa(String.fromCharCode.apply(0,h)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Z={ES256:{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}},ES384:{name:"ECDSA",namedCurve:"P-384",hash:{name:"SHA-384"}},ES512:{name:"ECDSA",namedCurve:"P-521",hash:{name:"SHA-512"}},HS256:{name:"HMAC",hash:{name:"SHA-256"}},HS384:{name:"HMAC",hash:{name:"SHA-384"}},HS512:{name:"HMAC",hash:{name:"SHA-512"}},RS256:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},RS384:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}},RS512:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}}};function w(h){return Q(btoa(unescape(encodeURIComponent(h))))}function ee(h){h=atob(h);let e=new ArrayBuffer(h.length),t=new Uint8Array(e);for(let i=0,r=h.length;i<r;i++)t[i]=h.charCodeAt(i);return e}function X(h){switch(h.length%4){case 0:break;case 2:h+="==";break;case 3:h+="=";break;default:throw new Error("Illegal base64url string!")}try{return JSON.parse(decodeURIComponent(escape(atob(h))))}catch (e2){return null}}async function te(h,e,t={algorithm:"HS256",header:{typ:"JWT"}}){if(typeof t=="string"&&(t={algorithm:t,header:{typ:"JWT"}}),t={algorithm:"HS256",header:{typ:"JWT"},...t},h===null||typeof h!="object")throw new Error("payload must be an object");if(typeof e!="string"&&typeof e!="object")throw new Error("secret must be a string or a JWK object");if(typeof t.algorithm!="string")throw new Error("options.algorithm must be a string");let i=Z[t.algorithm];if(!i)throw new Error("algorithm not found");h.iat||(h.iat=Math.floor(Date.now()/1e3));let r=JSON.stringify(h),n=`${G(w(JSON.stringify({...t.header,alg:t.algorithm})))}.${G(w(r))}`,s="raw",a;typeof e=="object"?(s="jwk",a=e):typeof e=="string"&&e.startsWith("-----BEGIN")?(s="pkcs8",a=ee(e.replace(/-----BEGIN.*?-----/g,"").replace(/-----END.*?-----/g,"").replace(/\s/g,""))):a=w(e);let o=await T.subtle.importKey(s,a,i,!1,["sign"]),d=await T.subtle.sign(i,o,w(n));return`${n}.${G(new Uint8Array(d))}`}async function ie(h,e,t={algorithm:"HS256",throwError:!1}){if(typeof t=="string"&&(t={algorithm:t,throwError:!1}),t={algorithm:"HS256",throwError:!1,...t},typeof h!="string")throw new Error("token must be a string");if(typeof e!="string"&&typeof e!="object")throw new Error("secret must be a string or a JWK object");if(typeof t.algorithm!="string")throw new Error("options.algorithm must be a string");let i=h.split(".");if(i.length!==3)throw new Error("token must consist of 3 parts");let r=Z[t.algorithm];if(!r)throw new Error("algorithm not found");let{payload:n}=ye(h);if(!n){if(t.throwError)throw new (0, _chunk2MN4DLM7js.d)("ParseError");return!1}if(n.nbf&&n.nbf>Math.floor(Date.now()/1e3)){if(t.throwError)throw new (0, _chunk2MN4DLM7js.d)("NotYetValid");return!1}if(n.exp&&n.exp<=Math.floor(Date.now()/1e3)){if(t.throwError)throw new (0, _chunk2MN4DLM7js.d)("TokenExpiredError");return!1}let s="raw",a;typeof e=="object"?(s="jwk",a=e):typeof e=="string"&&e.startsWith("-----BEGIN")?(s="spki",a=ee(e.replace(/-----BEGIN.*?-----/g,"").replace(/-----END.*?-----/g,"").replace(/\s/g,""))):a=w(e);let o=await T.subtle.importKey(s,a,r,!1,["verify"]);return await T.subtle.verify(r,o,Q(i[2]),w(`${i[0]}.${i[1]}`))}function ye(h){return{header:X(h.split(".")[0].replace(/-/g,"+").replace(/_/g,"/")),payload:X(h.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"))}}var N=class{verifyToken(e,t,i){i=i||{};let r=Object.assign({},i);return delete r.socket,typeof e=="string"||e==null?new Promise((n,s)=>{ie(e,t,r).then(a=>{a?n(e):s(new (0, _chunk2MN4DLM7js.d)("Invalid token"))}).catch(a=>s(a))}):Promise.reject(new (0, _chunk2MN4DLM7js.h)("Invalid token format - Token must be a string"))}signToken(e,t,i){i=i||{};let r=Object.assign({},i);return new Promise((n,s)=>{te(e,t,r).then(a=>{a?n(a):s(new (0, _chunk2MN4DLM7js.d)("Sign token error"))}).catch(a=>s(a))})}};var ke=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function re(h){let e=0,t="",i=new Uint8Array(h);for(;e<i.length;e++)t+=ke[i[e]];return t}var Ce=new _webcrypto.Crypto;function ne(h=9,e){let t=new Uint8Array(h);try{return Ce.getRandomValues(t),e&&e(null,t),re(t)}catch(i){return e&&e(i,t),null}}var P=class extends _chunk2MN4DLM7js.v{constructor(e){super(),this.id="exchange",this._broker=e,this._channelMap={},this._channelEventDemux=new _chunk2MN4DLM7js.u,this._channelDataDemux=new _chunk2MN4DLM7js.u}transmit(e,t){e==="#publish"&&this._channelDataDemux.write(t.channel,t.data)}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllChannelsBackpressure())}destroy(){this._broker.closeAllListeners()}async transmitPublish(e,t){return this._broker.transmitPublish(e,t)}async invokePublish(e,t){return this._broker.invokePublish(e,t)}subscribe(e){let t=this._channelMap[e];return t||(t={name:e,state:_chunkFOM74K3Hjs.a.PENDING},this._channelMap[e]=t,this._triggerChannelSubscribe(t)),new (0, _chunkFOM74K3Hjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&this._triggerChannelUnsubscribe(t)}channel(e){let t=this._channelMap[e];return new (0, _chunkFOM74K3Hjs.a)(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:_chunkFOM74K3Hjs.a.UNSUBSCRIBED}getChannelOptions(e){return{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.close(i)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.kill(i)})}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,i)=>(i.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(i=>this._channelEventDemux.getBackpressure(i));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,i){return this._channelEventDemux.hasConsumer(`${e}/${t}`,i)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(i=>this._channelEventDemux.hasConsumer(i,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(i=>{(e||this._channelMap[i].state===_chunkFOM74K3Hjs.a.SUBSCRIBED)&&t.push(i)}),t}isSubscribed(e,t){let i=this._channelMap[e];return t?!!i:!!i&&i.state===_chunkFOM74K3Hjs.a.SUBSCRIBED}_triggerChannelSubscribe(e){let t=e.name;e.state=_chunkFOM74K3Hjs.a.SUBSCRIBED,this._channelEventDemux.write(`${t}/subscribe`,{}),this._broker.subscribeClient(this,t),this.emit("subscribe",{channel:t})}_triggerChannelUnsubscribe(e){let t=e.name;delete this._channelMap[t],e.state===_chunkFOM74K3Hjs.a.SUBSCRIBED&&(this._channelEventDemux.write(`${t}/unsubscribe`,{}),this._broker.unsubscribeClient(this,t),this.emit("unsubscribe",{channel:t}))}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(i=>i.stream.indexOf(`${e}/`)===0).reduce((i,r)=>(i[r.stream]=!0,i),{});return Object.keys(t)}};var M=class extends _chunk2MN4DLM7js.v{constructor(){super(),this.isReady=!1,this._codec=null,this._exchangeClient=new P(this),this._clientSubscribers={},this._clientSubscribersCounter={},setTimeout(()=>{this.isReady=!0,this.emit("ready",{})},0)}exchange(){return this._exchangeClient}async subscribeClient(e,t){this._clientSubscribers[t]||(this._clientSubscribers[t]={},this._clientSubscribersCounter[t]=0,this.emit("subscribe",{channel:t})),this._clientSubscribers[t][e.id]||this._clientSubscribersCounter[t]++,this._clientSubscribers[t][e.id]=e}async subscribeSocket(e,t){return this.subscribeClient(e,t)}async unsubscribeClient(e,t){this._clientSubscribers[t]&&this._clientSubscribers[t][e.id]&&(this._clientSubscribersCounter[t]--,delete this._clientSubscribers[t][e.id],this._clientSubscribersCounter[t]<=0&&(delete this._clientSubscribers[t],delete this._clientSubscribersCounter[t],this.emit("unsubscribe",{channel:t})))}async unsubscribeSocket(e,t){return this.unsubscribeClient(e,t)}subscriptions(){return Object.keys(this._clientSubscribers)}isSubscribed(e){return!!this._clientSubscribers[e]}setCodecEngine(e){this._codec=e}invokePublish(e,t,i){return this.transmitPublish(e,t,i)}async transmitPublish(e,t,i){let r={channel:e,data:t},n={};if(this._codec)try{n.stringifiedData=this._codec.encode({event:"#publish",data:r})}catch(a){this.emit("error",{error:a});return}let s=this._clientSubscribers[e]||{};Object.keys(s).forEach(a=>{s[a].transmit("#publish",r,n)}),i||this.emit("publish",r)}};function se(){return Math.abs(Math.random()*Math.random()*Date.now()|0).toString()+Math.abs(Math.random()*Math.random()*Date.now()|0).toString()}function ae(){return typeof process=="object"}var oe="handshakeWS",he="handshakeSC",le="message",ue="transmit",ce="invoke",de="subscribe",me="publishIn",pe="publishOut",be="authenticate",m= exports.TGAction =class{constructor(){this.outcome=null,this.HANDSHAKE_WS=oe,this.HANDSHAKE_SC=he,this.MESSAGE=le,this.TRANSMIT=ue,this.INVOKE=ce,this.SUBSCRIBE=de,this.PUBLISH_IN=me,this.PUBLISH_OUT=pe,this.AUTHENTICATE=be,this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}allow(e){if(this.outcome)throw new (0, _chunk2MN4DLM7js.g)(`AGAction ${this.type} has already been ${this.outcome}; cannot allow`);this.outcome="allowed",this._resolve(e)}block(e){if(this.outcome)throw new (0, _chunk2MN4DLM7js.g)(`AGAction ${this.type} has already been ${this.outcome}; cannot block`);this.outcome="blocked",this._reject(e)}};_chunkEQT5ZTTXjs.a.call(void 0, m,"HANDSHAKE_WS",oe),_chunkEQT5ZTTXjs.a.call(void 0, m,"HANDSHAKE_SC",he),_chunkEQT5ZTTXjs.a.call(void 0, m,"MESSAGE",le),_chunkEQT5ZTTXjs.a.call(void 0, m,"TRANSMIT",ue),_chunkEQT5ZTTXjs.a.call(void 0, m,"INVOKE",ce),_chunkEQT5ZTTXjs.a.call(void 0, m,"SUBSCRIBE",de),_chunkEQT5ZTTXjs.a.call(void 0, m,"PUBLISH_IN",me),_chunkEQT5ZTTXjs.a.call(void 0, m,"PUBLISH_OUT",pe),_chunkEQT5ZTTXjs.a.call(void 0, m,"AUTHENTICATE",be);var De=4008,c= (_class =class extends _chunk2MN4DLM7js.v{__init() {this._batchingIntervalId=null}constructor(e,t,i,r){super();_class.prototype.__init.call(this);,this.id=e,this.server=t,this.socket=i,this.state=c.CONNECTING,this.authState=c.UNAUTHENTICATED,this.protocolVersion=r,this._receiverDemux=new _chunk2MN4DLM7js.u,this._procedureDemux=new _chunk2MN4DLM7js.u,this.request=this.socket.upgradeReq,this.inboundReceivedMessageCount=0,this.inboundProcessedMessageCount=0,this.outboundPreparedMessageCount=0,this.outboundSentMessageCount=0,this.cloneData=this.server.options.cloneData,this.inboundMessageStream=new _chunkWSYY47HQjs.a,this.outboundPacketStream=new _chunkWSYY47HQjs.a,this.middlewareHandshakeStream=this.request[g.SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM],this.middlewareInboundRawStream=new _chunkWSYY47HQjs.a,this.middlewareInboundRawStream.type=g.MIDDLEWARE_INBOUND_RAW,this.middlewareInboundStream=new _chunkWSYY47HQjs.a,this.middlewareInboundStream.type=g.MIDDLEWARE_INBOUND,this.middlewareOutboundStream=new _chunkWSYY47HQjs.a,this.middlewareOutboundStream.type=g.MIDDLEWARE_OUTBOUND,this.request.connection?(this.remoteAddress=this.request.connection.remoteAddress,this.remoteFamily=this.request.connection.remoteFamily,this.remotePort=this.request.connection.remotePort):(this.remoteAddress=this.request.remoteAddress,this.remoteFamily=this.request.remoteFamily,this.remotePort=this.request.remotePort),this.request.forwardedForAddress&&(this.forwardedForAddress=this.request.forwardedForAddress),this.isBufferingBatch=!1,this.isBatching=!1,this.batchOnHandshake=this.server.options.batchOnHandshake,this.batchOnHandshakeDuration=this.server.options.batchOnHandshakeDuration,this.batchInterval=this.server.options.batchInterval,this._batchBuffer=[],this._batchingIntervalId=null,this._cid=1,this._callbackMap={},this.channelSubscriptions={},this.channelSubscriptionsCount=0,this._on("error",async s=>{this.emitError(s)}),this._on("close",async(s,a)=>{let o=a&&a.toString();this._destroy(s,o)});let n;this.protocolVersion===1?(n="#2",this._sendPing=()=>{this.state!==c.CLOSED&&this.send("#1")}):(n="",this._sendPing=()=>{this.state!==c.CLOSED&&this.send("")}),this.server.pingTimeoutDisabled||(this._pingIntervalTicker=setInterval(()=>{this._sendPing()},this.server.pingInterval)),this._resetPongTimeout(),this._handshakeTimeoutRef=setTimeout(()=>{this._handleHandshakeTimeout()},this.server.handshakeTimeout),this.server.pendingClients[this.id]=this,this.server.pendingClientsCount++,this._handleInboundMessageStream(n),this._handleOutboundPacketStream(),this._on("message",async(s,a)=>{let o=a?s:s.toString();if(this.inboundReceivedMessageCount++,o===n&&this._resetPongTimeout(),this.server.hasMiddleware(g.MIDDLEWARE_INBOUND_RAW)){let l=new m;l.socket=this,l.type=m.MESSAGE,l.data=o;try{let{data:u}=await this.server.processMiddlewareAction(this.middlewareInboundRawStream,l,this);o=u}catch (e3){this.inboundProcessedMessageCount++;return}}this.inboundMessageStream.write(o),this.emit("message",{message:o})})}getBackpressure(){return Math.max(this.getInboundBackpressure(),this.getOutboundBackpressure(),this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure())}getInboundBackpressure(){return this.inboundReceivedMessageCount-this.inboundProcessedMessageCount}getOutboundBackpressure(){return this.outboundPreparedMessageCount-this.outboundSentMessageCount}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)}emit(e,t){return super.emit(e,t)}getState(){return this.state}getBytesReceived(){return this.socket.bytesReceived}emitError(e){this.emit("error",{error:e}),this.server.emitWarning(e)}closeAllMiddlewares(){this.middlewareHandshakeStream.close(),this.middlewareInboundRawStream.close(),this.middlewareInboundStream.close(),this.middlewareOutboundStream.close()}closeInput(){this.inboundMessageStream.close()}closeOutput(){this.outboundPacketStream.close()}closeIO(){this.closeInput(),this.closeOutput()}closeAllStreams(){this.closeAllMiddlewares(),this.closeIO(),this.closeAllReceivers(),this.closeAllProcedures(),this.closeAllListeners()}killAllMiddlewares(){this.middlewareHandshakeStream.kill(),this.middlewareInboundRawStream.kill(),this.middlewareInboundStream.kill(),this.middlewareOutboundStream.kill()}killInput(){this.inboundMessageStream.kill()}killOutput(){this.outboundPacketStream.kill()}killIO(){this.killInput(),this.killOutput()}killAllStreams(){this.killAllMiddlewares(),this.killIO(),this.killAllReceivers(),this.killAllProcedures(),this.killAllListeners()}async disconnect(e,t){if(e=e||1e3,typeof e!="number"){let i=new (0, _chunk2MN4DLM7js.h)("If specified, the code argument must be a number");this.emitError(i)}this.state!==c.CLOSED&&(await this._destroy(e,t),this.socket.close(e,t))}terminate(){this.server.options.isNode?this.socket.terminate():this.disconnect()}send(e,t){this.server.options.isNode?this.socket.send(e,t,i=>{i&&(this.emitError(i),this._destroy(1006,i.toString()))}):this.socket.send(e)}decode(e){return this.server.codec.decode(e)}encode(e){return this.server.codec.encode(e)}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=[]}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}serializeObject(e){let t;try{t=this.encode(e)}catch(i){return this.emitError(i),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}async transmit(e,t,i){if(this.state!==c.OPEN){let r=new (0, _chunk2MN4DLM7js.n)(`Socket transmit "${e}" was aborted due to a bad connection`,"connectAbort");this.emitError(r);return}this._transmit(e,t,i)}async invoke(e,t,i){if(this.state!==c.OPEN){let r=new (0, _chunk2MN4DLM7js.n)(`Socket invoke "${e}" was aborted due to a bad connection`,"connectAbort");throw this.emitError(r),r}return this.cloneData&&(t=_chunk2MN4DLM7js.y.call(void 0, t)),this.outboundPreparedMessageCount++,new Promise((r,n)=>{this.outboundPacketStream.write({event:e,data:t,options:i,resolve:r,reject:n})})}triggerAuthenticationEvents(e){if(e!==c.AUTHENTICATED){let t={oldState:e,newState:this.authState,authToken:this.authToken};this.emit("authStateChange",t),this.server.emit("authenticationStateChange",{socket:this,...t})}this.emit("authenticate",{authToken:this.authToken}),this.server.emit("authentication",{socket:this,authToken:this.authToken})}async setAuthToken(e,t){if(this.state===c.CONNECTING){let l=new (0, _chunk2MN4DLM7js.g)("Cannot call setAuthToken before completing the handshake");throw this.emitError(l),l}let i=_chunk2MN4DLM7js.y.call(void 0, e),r=this.authState;if(this.authState=c.AUTHENTICATED,t==null)t={};else if(t={...t},t.algorithm!=null){delete t.algorithm;let l=new (0, _chunk2MN4DLM7js.h)("Cannot change auth token algorithm at runtime - It must be specified as a config option on launch");this.emitError(l)}let n=t.rejectOnFailedDelivery;delete t.rejectOnFailedDelivery;let s=this.server.defaultSignatureOptions,a;e.exp==null?a=s.expiresIn:a=e.exp,i?i.exp==null?e.exp=a:delete e.exp:e.exp=a,s.algorithm!=null&&(t.algorithm=s.algorithm),this.authToken=i;let o;try{o=await this.server.auth.signToken(i,this.server.signatureKey,t)}catch(l){throw this.emitError(l),this._destroy(4002,l.toString()),this.socket.close(4002),l}this.authToken===i&&(this.signedAuthToken=o,this.emit("authTokenSigned",{signedAuthToken:o})),this.triggerAuthenticationEvents(r);let d={token:o};if(n){try{await this.invoke("#setAuthToken",d)}catch(l){let u=new (0, _chunk2MN4DLM7js.e)(`Failed to deliver auth token to client - ${l}`);throw this.emitError(u),u}return}this.transmit("#setAuthToken",d)}getAuthToken(){return this.authToken}deauthenticateSelf(){let e=this.authState,t=this.authToken;if(this.signedAuthToken=null,this.authToken=null,this.authState=c.UNAUTHENTICATED,e!==c.UNAUTHENTICATED){let i={oldState:e,newState:this.authState};this.emit("authStateChange",i),this.server.emit("authenticationStateChange",{socket:this,...i})}this.emit("deauthenticate",{oldAuthToken:t}),this.server.emit("deauthentication",{socket:this,oldAuthToken:t})}async deauthenticate(e){if(this.deauthenticateSelf(),e&&e.rejectOnFailedDelivery){try{await this.invoke("#removeAuthToken")}catch(t){if(this.emitError(t),e&&e.rejectOnFailedDelivery)throw t}return}this._transmit("#removeAuthToken")}kickOut(e,t){let i=e;return i||(i=Object.keys(this.channelSubscriptions)),Array.isArray(i)||(i=[e]),Promise.all(i.map(r=>(this.transmit("#kickOut",{channel:r,message:t}),this._unsubscribe(r))))}subscriptions(){return Object.keys(this.channelSubscriptions)}isSubscribed(e){return!!this.channelSubscriptions[e]}isAuthTokenExpired(e){if(e&&e.exp!=null){let t=Date.now(),i=e.exp*1e3;return t>i}return!1}async _processAuthentication({signedAuthToken:e,authTokenError:t,authToken:i,authState:r}){if(t)throw this.signedAuthToken=null,this.authToken=null,this.authState=c.UNAUTHENTICATED,e!=null&&(this.emitError(t),t.isBadToken&&this._emitBadAuthTokenError(t,e)),t;this.signedAuthToken=e,this.authToken=i,this.authState=c.AUTHENTICATED;let n=new m;n.socket=this,n.type=m.AUTHENTICATE,n.signedAuthToken=this.signedAuthToken,n.authToken=this.authToken;try{await this.server.processMiddlewareAction(this.middlewareInboundStream,n,this)}catch(s){throw this.authToken=null,this.authState=c.UNAUTHENTICATED,s.isBadToken&&this._emitBadAuthTokenError(s,e),s}}async _validateAuthToken(e){let t=Object.assign({},this.server.defaultVerificationOptions,{socket:this,throwError:!0}),i;try{i=await this.server.auth.verifyToken(e,this.server.verificationKey,t)}catch(r){let n=this._processTokenError(r);return{signedAuthToken:e,authTokenError:n,authToken:null,authState:c.UNAUTHENTICATED}}return{signedAuthToken:e,authTokenError:null,authToken:i,authState:c.AUTHENTICATED}}_emitBadAuthTokenError(e,t){this.emit("badAuthToken",{authError:e,signedAuthToken:t}),this.server.emit("badSocketAuthToken",{socket:this,authError:e,signedAuthToken:t})}_processTokenError(e){if(e){if(e.message==="TokenExpiredError"){let i=new (0, _chunk2MN4DLM7js.a)(e.message,e.expiredAt);return i.isBadToken=!0,i}if(e.message==="ParseError"){let i=new (0, _chunk2MN4DLM7js.b)(e.message);return i.isBadToken=!0,i}if(e.message==="NotYetValid"){let i=new (0, _chunk2MN4DLM7js.c)(e.message,e.date);return i.isBadToken=!1,i}let t=new (0, _chunk2MN4DLM7js.d)(e.message);return t.isBadToken=!0,t}return null}_processAuthTokenExpiry(){let e=this.getAuthToken();return this.isAuthTokenExpired(e)?(this.deauthenticate(),new (0, _chunk2MN4DLM7js.a)("The socket auth token has expired",e.exp)):null}async _invoke(e,t,i){return i=i||{},new Promise((r,n)=>{let s={event:e,cid:this._nextCallId()};t!==void 0&&(s.data=t);let a=i.ackTimeout==null?this.server.ackTimeout:i.ackTimeout,o=setTimeout(()=>{let d=new (0, _chunk2MN4DLM7js.m)(`Event response for "${e}" timed out`);delete this._callbackMap[s.cid],n(d)},a);this._callbackMap[s.cid]={event:e,callback:(d,l)=>{if(d){n(d);return}r(l)},timeout:o},i.useCache&&i.stringifiedData!=null&&!this.isBufferingBatch?this.send(i.stringifiedData):this.sendObject(s)})}async _processTransmit(e,t,i){let r,n=i?i.useCache:!1,s={event:e,data:t},a=e==="#publish";if(a){let o=new m;o.socket=this,o.type=m.PUBLISH_OUT,t!==void 0&&(o.channel=t.channel,o.data=t.data),n=!this.server.hasMiddleware(this.middlewareOutboundStream.type);try{let{data:d,options:l}=await this.server.processMiddlewareAction(this.middlewareOutboundStream,o,this);r=d,n=l==null?n:l.useCache}catch (e4){return}}else r=s.data;if(i&&n&&i.stringifiedData!=null&&!this.isBufferingBatch)this.send(i.stringifiedData);else{let o={event:e};a?(o.data=t||{},o.data.data=r):o.data=r,this.sendObject(o)}}async _transmit(e,t,i){this.cloneData&&t&&(t=_chunk2MN4DLM7js.y.call(void 0, t)),this.outboundPreparedMessageCount++,this.outboundPacketStream.write({event:e,data:t,options:i})}async _handleOutboundPacketStream(){for await(let e of this.outboundPacketStream){if(e.resolve){(async()=>{let t;try{t=await this._invoke(e.event,e.data,e.options)}catch(i){e.reject(i);return}e.resolve(t)})(),this.outboundSentMessageCount++;continue}await this._processTransmit(e.event,e.data,e.options),this.outboundSentMessageCount++}}_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.batchInterval))}async _destroy(e,t){if(clearInterval(this._pingIntervalTicker),clearTimeout(this._pingTimeoutTicker),this._cancelBatching(),this.state===c.CLOSED)this._abortAllPendingEventsDueToBadConnection("connectAbort");else{!t&&c.errorStatuses[e]&&(t=c.errorStatuses[e]);let i=this.state;if(this.state=c.CLOSED,i===c.CONNECTING?(this._abortAllPendingEventsDueToBadConnection("connectAbort"),this.emit("connectAbort",{code:e,reason:t}),this.server.emit("connectionAbort",{socket:this,code:e,reason:t})):(this._abortAllPendingEventsDueToBadConnection("disconnect"),this.emit("disconnect",{code:e,reason:t}),this.server.emit("disconnection",{socket:this,code:e,reason:t})),this.emit("close",{code:e,reason:t}),this.server.emit("closure",{socket:this,code:e,reason:t}),clearTimeout(this._handshakeTimeoutRef),!!this.server.clients[this.id]&&(delete this.server.clients[this.id],this.server.clientsCount--),!!this.server.pendingClients[this.id]&&(delete this.server.pendingClients[this.id],this.server.pendingClientsCount--),!c.ignoreStatuses[e]){let a;if(t){let d;if(typeof t=="object")try{d=JSON.stringify(t)}catch (e5){d=t.toString()}else d=t;a=`Socket connection closed with status code ${e} and reason: ${d}`}else a=`Socket connection closed with status code ${e}`;let o=new (0, _chunk2MN4DLM7js.k)(c.errorStatuses[e]||a,e);this.emitError(o)}await this._unsubscribeFromAllChannels();let s=this.server.options.socketStreamCleanupMode;s==="kill"?(async()=>(await this.listener("end").once(),this.killAllStreams()))():s==="close"&&(async()=>(await this.listener("end").once(),this.closeAllStreams()))(),this.emit("end")}}_abortAllPendingEventsDueToBadConnection(e){Object.keys(this._callbackMap||{}).forEach(t=>{let i=this._callbackMap[t];delete this._callbackMap[t],clearTimeout(i.timeout),delete i.timeout;let r=`Event "${i.event}" was aborted due to a bad connection`,n=new (0, _chunk2MN4DLM7js.n)(r,e),s=i.callback;delete i.callback,s.call(i,n,i)})}async _handleInboundMessageStream(e){for await(let t of this.inboundMessageStream){if(this.inboundProcessedMessageCount++,t===e){if(this.server.strictHandshake&&this.state===c.CONNECTING){this._destroy(4009),this.socket.close(4009);continue}let n=this.getAuthToken();this.isAuthTokenExpired(n)&&this.deauthenticate();continue}let r;try{r=this.decode(t)}catch(n){n.name==="Error"&&(n.name="InvalidMessageError"),this.emitError(n),this.server.strictHandshake&&this.state===c.CONNECTING&&(this._destroy(4009),this.socket.close(4009));continue}if(Array.isArray(r)){let n=r.length;for(let s=0;s<n;s++)await this._processInboundPacket(r[s],t)}else await this._processInboundPacket(r,t)}}_handleHandshakeTimeout(){this.disconnect(4005)}async _processHandshakeRequest(e){let i=(e.data||{}).authToken||null;clearTimeout(this._handshakeTimeoutRef);let r=await this._validateAuthToken(i),n=new m;n.request=this.request,n.socket=this,n.type=m.HANDSHAKE_SC,n.data=r;try{await this.server.processMiddlewareAction(this.middlewareHandshakeStream,n)}catch(d){d.statusCode==null&&(d.statusCode=De),e.error(d),this.disconnect(d.statusCode);return}let s={id:this.id,pingTimeout:this.server.pingTimeout,isAuthenticated:!1},a={id:this.id,pingTimeout:this.server.pingTimeout,isAuthenticated:!1},o=this.authState;try{if(await this._processAuthentication(r),this.state===c.CLOSED)return}catch(d){i!=null&&(s.authError=_chunk2MN4DLM7js.r.call(void 0, d),a.authError=d,d.isBadToken&&this.deauthenticate())}s.isAuthenticated=!!this.authToken,a.isAuthenticated=s.isAuthenticated,this.server.pendingClients[this.id]&&(delete this.server.pendingClients[this.id],this.server.pendingClientsCount--),this.server.clients[this.id]=this,this.server.clientsCount++,this.state=c.OPEN,s.isAuthenticated&&(async()=>(await this.listener("connect").once(),this.triggerAuthenticationEvents(o)))(),e.end(s),this.batchOnHandshake&&this._startBatchOnHandshake(),this.emit("connect",a),this.server.emit("connection",{socket:this,...a}),this.middlewareHandshakeStream.close()}_startBatchOnHandshake(){this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)}async _processAuthenticateRequest(e){let t=e.data,i=this.authState,r=await this._validateAuthToken(t);try{await this._processAuthentication(r)}catch(n){if(n.isBadToken){this.deauthenticate(),e.error(n);return}e.end({isAuthenticated:!!this.authToken,authError:t==null?null:_chunk2MN4DLM7js.r.call(void 0, n)});return}this.triggerAuthenticationEvents(i),e.end({isAuthenticated:!!this.authToken,authError:null})}async _subscribeSocket(e,t){if(e===void 0||!t)throw new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} provided a malformated channel payload`);if(this.server.socketChannelLimit&&this.channelSubscriptionsCount>=this.server.socketChannelLimit)throw new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} tried to exceed the channel subscription limit of ${this.server.socketChannelLimit}`);if(typeof e!="string")throw new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} provided an invalid channel name`);this.channelSubscriptionsCount==null&&(this.channelSubscriptionsCount=0),this.channelSubscriptions[e]==null&&(this.channelSubscriptions[e]=!0,this.channelSubscriptionsCount++);try{await this.server.brokerEngine.subscribeSocket(this,e)}catch(i){throw delete this.channelSubscriptions[e],this.channelSubscriptionsCount--,i}this.emit("subscribe",{channel:e,subscriptionOptions:t}),this.server.emit("subscription",{socket:this,channel:e,subscriptionOptions:t})}async _processSubscribeRequest(e){let t=Object.assign({},e.data),i=t.channel;if(delete t.channel,this.state===c.OPEN){try{await this._subscribeSocket(i,t)}catch(n){let s=new (0, _chunk2MN4DLM7js.o)(`Failed to subscribe socket to the ${i} channel - ${n}`);this.emitError(s),e.error(s);return}e.end();return}let r=new (0, _chunk2MN4DLM7js.g)("Cannot subscribe socket to a channel before it has completed the handshake");this.emitError(r),e.error(r)}_unsubscribeFromAllChannels(){let e=Object.keys(this.channelSubscriptions);return Promise.all(e.map(t=>this._unsubscribe(t)))}async _unsubscribe(e){if(typeof e!="string")throw new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} tried to unsubscribe from an invalid channel name`);if(!this.channelSubscriptions[e])throw new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} tried to unsubscribe from a channel which it is not subscribed to`);try{await this.server.brokerEngine.unsubscribeSocket(this,e),delete this.channelSubscriptions[e],this.channelSubscriptionsCount!=null&&this.channelSubscriptionsCount--,this.emit("unsubscribe",{channel:e}),this.server.emit("unsubscription",{socket:this,channel:e})}catch(t){let i=new (0, _chunk2MN4DLM7js.o)(`Failed to unsubscribe socket from the ${e} channel - ${t}`);this.emitError(i)}}async _processUnsubscribePacket(e){let t=e.data;try{await this._unsubscribe(t)}catch(i){let r=new (0, _chunk2MN4DLM7js.o)(`Failed to unsubscribe socket from the ${t} channel - ${i}`);this.emitError(r)}}async _processUnsubscribeRequest(e){let t=e.data;try{await this._unsubscribe(t)}catch(i){let r=new (0, _chunk2MN4DLM7js.o)(`Failed to unsubscribe socket from the ${t} channel - ${i}`);this.emitError(r),e.error(r);return}e.end()}async _processInboundPublishPacket(e){let t=e.data||{};if(typeof t.channel!="string"){let i=new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} tried to invoke publish to an invalid "${t.channel}" channel`);this.emitError(i);return}try{await this.server.exchange.invokePublish(t.channel,t.data)}catch(i){this.emitError(i)}}async _processInboundPublishRequest(e){let t=e.data||{};if(typeof t.channel!="string"){let i=new (0, _chunk2MN4DLM7js.g)(`Socket ${this.id} tried to transmit publish to an invalid "${t.channel}" channel`);this.emitError(i),e.error(i);return}try{await this.server.exchange.invokePublish(t.channel,t.data)}catch(i){this.emitError(i),e.error(i);return}e.end()}async _processInboundPacket(e,t){if(e&&e.event!=null){let i=e.event,r=e.cid!=null;if(i==="#handshake"){let u=new (0, _chunk2MN4DLM7js.z)(this,e.cid,i,e.data);await this._processHandshakeRequest(u),this._procedureDemux.write(i,u);return}if(this.server.strictHandshake&&this.state===c.CONNECTING){this._destroy(4009),this.socket.close(4009);return}if(i==="#authenticate"){let u=new (0, _chunk2MN4DLM7js.z)(this,e.cid,i,e.data);await this._processAuthenticateRequest(u),this._procedureDemux.write(i,u);return}if(i==="#removeAuthToken"){this.deauthenticateSelf(),this._receiverDemux.write(i,e.data);return}let n=new m;n.socket=this;let s=this._processAuthTokenExpiry();s&&(n.authTokenExpiredError=s);let a=i==="#publish",o=i==="#subscribe",d=i==="#unsubscribe";if(a){if(!this.server.allowClientPublish){let u=new (0, _chunk2MN4DLM7js.g)("Client publish feature is disabled");this.emitError(u),r&&new (0, _chunk2MN4DLM7js.z)(this,e.cid,i,e.data).error(u);return}n.type=m.PUBLISH_IN,e.data&&(n.channel=e.data.channel,n.data=e.data.data)}else if(o)n.type=m.SUBSCRIBE,e.data&&(n.channel=e.data.channel,n.data=e.data.data);else if(d){if(r){let u=new (0, _chunk2MN4DLM7js.z)(this,e.cid,i,e.data);await this._processUnsubscribeRequest(u),this._procedureDemux.write(i,u);return}await this._processUnsubscribePacket(e),this._receiverDemux.write(i,e.data);return}else r?(n.type=m.INVOKE,n.procedure=e.event,e.data!==void 0&&(n.data=e.data)):(n.type=m.TRANSMIT,n.receiver=e.event,e.data!==void 0&&(n.data=e.data));let l;if(r){let u=new (0, _chunk2MN4DLM7js.z)(this,e.cid,i,e.data);try{let{data:I}=await this.server.processMiddlewareAction(this.middlewareInboundStream,n,this);l=I}catch(I){u.error(I);return}o?(u.data||(u.data={}),u.data.data=l,await this._processSubscribeRequest(u)):a?(u.data||(u.data={}),u.data.data=l,await this._processInboundPublishRequest(u)):u.data=l,this._procedureDemux.write(i,u);return}try{let{data:u}=await this.server.processMiddlewareAction(this.middlewareInboundStream,n,this);l=u}catch (e6){return}a&&(e.data||(e.data={}),e.data.data=l,await this._processInboundPublishPacket(e)),this._receiverDemux.write(i,l);return}if(this.server.strictHandshake&&this.state===c.CONNECTING){this._destroy(4009),this.socket.close(4009);return}if(e&&e.rid!=null){let i=this._callbackMap[e.rid];if(i){clearTimeout(i.timeout),delete this._callbackMap[e.rid];let r=_chunk2MN4DLM7js.s.call(void 0, e.error);i.callback(r,e.data)}return}this.emit("raw",{message:t})}_resetPongTimeout(){this.server.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4001),this.socket.close(4001)},this.server.pingTimeout))}_nextCallId(){return this._cid++}_on(e,t){if(this.server.options.isNode)this.socket.on(e,t);else switch(e){case"message":this.socket.addEventListener(e,i=>t(i.data));break;case"close":case"error":this.socket.addEventListener(e,i=>t(i));break}}}, _class),f= exports.TGServerSocket =c;_chunkEQT5ZTTXjs.a.call(void 0, f,"CONNECTING","connecting"),_chunkEQT5ZTTXjs.a.call(void 0, f,"OPEN","open"),_chunkEQT5ZTTXjs.a.call(void 0, f,"CLOSED","closed"),_chunkEQT5ZTTXjs.a.call(void 0, f,"AUTHENTICATED","authenticated"),_chunkEQT5ZTTXjs.a.call(void 0, f,"UNAUTHENTICATED","unauthenticated"),_chunkEQT5ZTTXjs.a.call(void 0, f,"ignoreStatuses",_chunk2MN4DLM7js.q),_chunkEQT5ZTTXjs.a.call(void 0, f,"errorStatuses",_chunk2MN4DLM7js.p);var ge="handshake",Se= exports.MIDDLEWARE_INBOUND_RAW ="inboundRaw",fe= exports.MIDDLEWARE_INBOUND ="inbound",ve= exports.MIDDLEWARE_OUTBOUND ="outbound";var S=class extends _chunk2MN4DLM7js.v{constructor(e){super();let t={brokerEngine:new M,wsEngine:"ws",wsEngineServerOptions:{},maxPayload:null,allowClientPublish:!0,ackTimeout:1e4,handshakeTimeout:1e4,strictHandshake:!0,pingTimeout:2e4,pingTimeoutDisabled:!1,pingInterval:8e3,origins:"*:*",path:"/topgunsocket/",protocolVersion:2,authDefaultExpiry:86400,batchOnHandshake:!1,batchOnHandshakeDuration:400,batchInterval:50,middlewareEmitFailures:!0,socketStreamCleanupMode:"kill",cloneData:!1,isNode:ae()};if(this.options=Object.assign(t,e),this._middleware={},this.origins=this.options.origins,this._allowAllOrigins=this.origins.indexOf("*:*")!==-1,this.ackTimeout=this.options.ackTimeout,this.handshakeTimeout=this.options.handshakeTimeout,this.pingInterval=this.options.pingInterval,this.pingTimeout=this.options.pingTimeout,this.pingTimeoutDisabled=this.options.pingTimeoutDisabled,this.allowClientPublish=this.options.allowClientPublish,this.perMessageDeflate=this.options.perMessageDeflate,this.httpServer=this.options.httpServer,this.socketChannelLimit=this.options.socketChannelLimit,this.protocolVersion=this.options.protocolVersion,this.strictHandshake=this.options.strictHandshake,this.brokerEngine=this.options.brokerEngine,this.middlewareEmitFailures=this.options.middlewareEmitFailures,this._path=t.path,(async()=>{for await(let{error:n}of this.brokerEngine.listener("error"))this.emitWarning(n)})(),this.brokerEngine.isReady?(this.isReady=!0,this.emit("ready",{})):(this.isReady=!1,(async()=>(await this.brokerEngine.listener("ready").once(),this.isReady=!0,this.emit("ready",{})))()),!this.options.wsEngine)throw new (0, _chunk2MN4DLM7js.i)("The wsEngine option must be a path or module name which points to a valid WebSocket engine module with a compatible interface");let i=this.options.wsEngine;if(this.options.authPrivateKey!=null||this.options.authPublicKey!=null){if(this.options.authPrivateKey==null)throw new (0, _chunk2MN4DLM7js.i)("The authPrivateKey option must be specified if authPublicKey is specified");if(this.options.authPublicKey==null)throw new (0, _chunk2MN4DLM7js.i)("The authPublicKey option must be specified if authPrivateKey is specified");this.signatureKey=this.options.authPrivateKey,this.verificationKey=this.options.authPublicKey}else this.options.authKey==null&&(this.options.authKey=ne(32).toString()),this.signatureKey=this.options.authKey,this.verificationKey=this.options.authKey;this.defaultVerificationOptions={},this.options.authVerifyAlgorithm!=null?this.defaultVerificationOptions.algorithm=this.options.authVerifyAlgorithm:this.options.authAlgorithm!=null&&(this.defaultVerificationOptions.algorithm=this.options.authAlgorithm),this.defaultSignatureOptions={expiresIn:this.options.authDefaultExpiry},this.options.authAlgorithm!=null&&(this.defaultSignatureOptions.algorithm=this.options.authAlgorithm),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new N,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunk2MN4DLM7js.w,this.brokerEngine.setCodecEngine(this.codec),this.exchange=this.brokerEngine.exchange(),this.clients={},this.clientsCount=0,this.pendingClients={},this.pendingClientsCount=0;let r=this.options.wsEngineServerOptions||{};r.server=this.httpServer,r.verifyClient=this.verifyHandshake.bind(this),r.path==null&&this._path!=null&&(r.path=this._path),r.perMessageDeflate==null&&this.perMessageDeflate!=null&&(r.perMessageDeflate=this.perMessageDeflate),r.handleProtocols==null&&this.options.handleProtocols!=null&&(r.handleProtocols=this.options.handleProtocols),r.maxPayload==null&&t.maxPayload!=null&&(r.maxPayload=t.maxPayload),r.clientTracking==null&&(r.clientTracking=!1),this.options.isNode?(this.wsServer=new i(r),this.wsServer.on("error",this._handleServerError.bind(this)),this.wsServer.on("connection",this._handleSocketConnection.bind(this))):(this.wsServer=i,this.wsServer.addEventListener("close",this._closeOrErrorHandler.bind(this)),this.wsServer.addEventListener("error",this._closeOrErrorHandler.bind(this)))}setAuthEngine(e){this.auth=e}setCodecEngine(e){this.codec=e,this.brokerEngine.setCodecEngine(e)}emit(e,t){return super.emit(e,t)}listener(e){return super.listener(e)}emitError(e){this.emit("error",{error:e})}emitWarning(e){this.emit("warning",{warning:e})}close(e){return this.isReady=!1,new Promise((t,i)=>{if(this.wsServer.close(r=>{if(r){i(r);return}t()}),!e)for(let r of Object.values(this.clients))r.terminate()})}getPath(){return this._path}generateId(){return se()}setMiddleware(e,t){if(e!==S.MIDDLEWARE_HANDSHAKE&&e!==S.MIDDLEWARE_INBOUND_RAW&&e!==S.MIDDLEWARE_INBOUND&&e!==S.MIDDLEWARE_OUTBOUND)throw new (0, _chunk2MN4DLM7js.h)(`Middleware type "${e}" is not supported`);if(this._middleware[e])throw new (0, _chunk2MN4DLM7js.g)(`Middleware type "${e}" has already been set`);this._middleware[e]=t}removeMiddleware(e){delete this._middleware[e]}hasMiddleware(e){return!!this._middleware[e]}async verifyHandshake(e,t){let i=e.req,r=e.origin;(r==="null"||r==null)&&(r="*");let n=!1;if(this._allowAllOrigins)n=!0;else try{let l=new URL(r),u=l.port||(l.protocol==="https:"?443:80);n=~this.origins.indexOf(l.hostname+":"+u)||~this.origins.indexOf(l.hostname+":*")||~this.origins.indexOf("*:"+u)}catch (e7){}let s=new _chunkWSYY47HQjs.a;s.type=S.MIDDLEWARE_HANDSHAKE,i[S.SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM]=s;let a=this._middleware[S.MIDDLEWARE_HANDSHAKE];a&&a(s);let o=new m;o.request=i,o.type=m.HANDSHAKE_WS;try{await this.processMiddlewareAction(s,o)}catch(l){s.close(),t(!1,401,typeof l=="string"?l:l.message);return}if(n){t(!0);return}let d=new (0, _chunk2MN4DLM7js.l)(`Failed to authorize socket handshake - Invalid origin: ${r}`);this.emitWarning(d),s.close(),t(!1,403,d.message)}async processMiddlewareAction(e,t,i){if(!this.hasMiddleware(e.type))return{data:t.data,options:null};e.write(t);let r,n=null;try{let s=await t.promise;s&&(r=s.data,n=s.options)}catch(s){let a;throw s?s.silent?a=new (0, _chunk2MN4DLM7js.f)(`The ${t.type} AGAction was blocked by ${e.type} middleware`,e.type):a=s:(s=new (0, _chunk2MN4DLM7js.f)(`The ${t.type} AGAction was blocked by ${e.type} middleware`,e.type),a=s),this.middlewareEmitFailures&&(i?i.emitError(s):this.emitWarning(s)),a}return r===void 0&&(r=t.data),{data:r,options:n}}_closeOrErrorHandler(e){e&&this.emitError(e),this.close()}_handleServerError(e){typeof e=="string"&&(e=new (0, _chunk2MN4DLM7js.l)(e)),this.emitError(e)}_handleSocketConnection(e,t){e.upgradeReq||(e.upgradeReq=t);let i=this.generateId(),r=new f(i,this,e,this.protocolVersion);r.exchange=this.exchange;let n=this._middleware[S.MIDDLEWARE_INBOUND_RAW];n&&n(r.middlewareInboundRawStream);let s=this._middleware[S.MIDDLEWARE_INBOUND];s&&s(r.middlewareInboundStream);let a=this._middleware[S.MIDDLEWARE_OUTBOUND];a&&a(r.middlewareOutboundStream),this.emit("handshake",{socket:r})}},g= exports.TGServerSocketGateway =S;_chunkEQT5ZTTXjs.a.call(void 0, g,"MIDDLEWARE_HANDSHAKE",ge),_chunkEQT5ZTTXjs.a.call(void 0, g,"MIDDLEWARE_INBOUND_RAW",Se),_chunkEQT5ZTTXjs.a.call(void 0, g,"MIDDLEWARE_INBOUND",fe),_chunkEQT5ZTTXjs.a.call(void 0, g,"MIDDLEWARE_OUTBOUND",ve),_chunkEQT5ZTTXjs.a.call(void 0, g,"SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM",Symbol("handshakeStream"));function $t(h,e){return _chunk2MN4DLM7js.x.call(void 0, e)||(e={}),e.httpServer=h,new g(e)}exports.MIDDLEWARE_HANDSHAKE = ge; exports.MIDDLEWARE_INBOUND = fe; exports.MIDDLEWARE_INBOUND_RAW = Se; exports.MIDDLEWARE_OUTBOUND = ve; exports.TGAction = m; exports.TGServerSocket = f; exports.TGServerSocketGateway = g; exports.attach = $t; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkKMDXU75Pjs = require('./chunk-KMDXU75P.js');var _chunk26YZNXPKjs = require('./chunk-26YZNXPK.js');var _chunk4FLQOCQEjs = require('./chunk-4FLQOCQE.js');var _chunkMY4YFY5Tjs = require('./chunk-MY4YFY5T.js');var _topgunwebcrypto = require('topgun-webcrypto'); var _topgunwebcrypto2 = _interopRequireDefault(_topgunwebcrypto);var I=_topgunwebcrypto2.default;if(typeof I=="undefined"||!I.subtle)throw new Error("SubtleCrypto not supported!");function ie(d){return new Uint8Array(Array.prototype.map.call(atob(d.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),o=>o.charCodeAt(0)))}function J(d){return btoa(String.fromCharCode.apply(0,d)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var re={ES256:{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}},ES384:{name:"ECDSA",namedCurve:"P-384",hash:{name:"SHA-384"}},ES512:{name:"ECDSA",namedCurve:"P-521",hash:{name:"SHA-512"}},HS256:{name:"HMAC",hash:{name:"SHA-256"}},HS384:{name:"HMAC",hash:{name:"SHA-384"}},HS512:{name:"HMAC",hash:{name:"SHA-512"}},RS256:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},RS384:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}},RS512:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}}};function _(d){return ie(btoa(unescape(encodeURIComponent(d))))}function ne(d){d=atob(d);let o=new ArrayBuffer(d.length),e=new Uint8Array(o);for(let t=0,i=d.length;t<i;t++)e[t]=d.charCodeAt(t);return o}function te(d){switch(d.length%4){case 0:break;case 2:d+="==";break;case 3:d+="=";break;default:throw new Error("Illegal base64url string!")}try{return JSON.parse(decodeURIComponent(escape(atob(d))))}catch(o){return null}}function se(t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,arguments,function*(d,o,e={algorithm:"HS256",header:{typ:"JWT"}}){if(typeof e=="string"&&(e={algorithm:e,header:{typ:"JWT"}}),e=_chunkMY4YFY5Tjs.a.call(void 0, {algorithm:"HS256",header:{typ:"JWT"}},e),d===null||typeof d!="object")throw new Error("payload must be an object");if(typeof o!="string"&&typeof o!="object")throw new Error("secret must be a string or a JWK object");if(typeof e.algorithm!="string")throw new Error("options.algorithm must be a string");let r=re[e.algorithm];if(!r)throw new Error("algorithm not found");d.iat||(d.iat=Math.floor(Date.now()/1e3));let s=JSON.stringify(d),n=`${J(_(JSON.stringify(_chunkMY4YFY5Tjs.b.call(void 0, _chunkMY4YFY5Tjs.a.call(void 0, {},e.header),{alg:e.algorithm}))))}.${J(_(s))}`,a="raw",h;typeof o=="object"?(a="jwk",h=o):typeof o=="string"&&o.startsWith("-----BEGIN")?(a="pkcs8",h=ne(o.replace(/-----BEGIN.*?-----/g,"").replace(/-----END.*?-----/g,"").replace(/\s/g,""))):h=_(o);let c=yield I.subtle.importKey(a,h,r,!1,["sign"]),u=yield I.subtle.sign(r,c,_(n));return`${n}.${J(new Uint8Array(u))}`})}function ae(t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,arguments,function*(d,o,e={algorithm:"HS256",throwError:!1}){if(typeof e=="string"&&(e={algorithm:e,throwError:!1}),e=_chunkMY4YFY5Tjs.a.call(void 0, {algorithm:"HS256",throwError:!1},e),typeof d!="string")throw new Error("token must be a string");if(typeof o!="string"&&typeof o!="object")throw new Error("secret must be a string or a JWK object");if(typeof e.algorithm!="string")throw new Error("options.algorithm must be a string");let r=d.split(".");if(r.length!==3)throw new Error("token must consist of 3 parts");let s=re[e.algorithm];if(!s)throw new Error("algorithm not found");let{payload:n}=De(d);if(!n){if(e.throwError)throw new (0, _chunkKMDXU75Pjs.d)("ParseError");return!1}if(n.nbf&&n.nbf>Math.floor(Date.now()/1e3)){if(e.throwError)throw new (0, _chunkKMDXU75Pjs.d)("NotYetValid");return!1}if(n.exp&&n.exp<=Math.floor(Date.now()/1e3)){if(e.throwError)throw new (0, _chunkKMDXU75Pjs.d)("TokenExpiredError");return!1}let a="raw",h;typeof o=="object"?(a="jwk",h=o):typeof o=="string"&&o.startsWith("-----BEGIN")?(a="spki",h=ne(o.replace(/-----BEGIN.*?-----/g,"").replace(/-----END.*?-----/g,"").replace(/\s/g,""))):h=_(o);let c=yield I.subtle.importKey(a,h,s,!1,["verify"]);return yield I.subtle.verify(s,c,ie(r[2]),_(`${r[0]}.${r[1]}`))})}function De(d){return{header:te(d.split(".")[0].replace(/-/g,"+").replace(/_/g,"/")),payload:te(d.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"))}}var H=class{verifyToken(o,e,t){t=t||{};let i=Object.assign({},t);return delete i.socket,typeof o=="string"||o==null?new Promise((r,s)=>{ae(o,e,i).then(n=>{n?r(o):s(new (0, _chunkKMDXU75Pjs.d)("Invalid token"))}).catch(n=>s(n))}):Promise.reject(new (0, _chunkKMDXU75Pjs.h)("Invalid token format - Token must be a string"))}signToken(o,e,t){t=t||{};let i=Object.assign({},t);return new Promise((r,s)=>{se(o,e,i).then(n=>{n?r(n):s(new (0, _chunkKMDXU75Pjs.d)("Sign token error"))}).catch(n=>s(n))})}};var we=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function oe(d){let o=0,e="",t=new Uint8Array(d);for(;o<t.length;o++)e+=we[t[o]];return e}var _e=_topgunwebcrypto2.default;function he(d=9,o){let e=new Uint8Array(d);try{return _e.getRandomValues(e),o&&o(null,e),oe(e)}catch(t){return o&&o(t,e),null}}var R=class extends _chunkKMDXU75Pjs.v{constructor(e){super();this.id="exchange",this._broker=e,this._channelMap={},this._channelEventDemux=new _chunkKMDXU75Pjs.u,this._channelDataDemux=new _chunkKMDXU75Pjs.u}transmit(e,t){e==="#publish"&&this._channelDataDemux.write(t.channel,t.data)}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllChannelsBackpressure())}destroy(){this._broker.closeAllListeners()}transmitPublish(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){return this._broker.transmitPublish(e,t)})}invokePublish(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){return this._broker.invokePublish(e,t)})}subscribe(e){let t=this._channelMap[e];return t||(t={name:e,state:_chunk26YZNXPKjs.a.PENDING},this._channelMap[e]=t,this._triggerChannelSubscribe(t)),new (0, _chunk26YZNXPKjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}unsubscribe(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=this._channelMap[e];t&&this._triggerChannelUnsubscribe(t)})}channel(e){let t=this._channelMap[e];return new (0, _chunk26YZNXPKjs.a)(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:_chunk26YZNXPKjs.a.UNSUBSCRIBED}getChannelOptions(e){return{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.close(i)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){let t=this._getAllChannelStreamNames(e).forEach(i=>{this._channelEventDemux.kill(i)})}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,i)=>(i.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(i=>this._channelEventDemux.getBackpressure(i));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,i){return this._channelEventDemux.hasConsumer(`${e}/${t}`,i)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(i=>this._channelEventDemux.hasConsumer(i,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(i=>{(e||this._channelMap[i].state===_chunk26YZNXPKjs.a.SUBSCRIBED)&&t.push(i)}),t}isSubscribed(e,t){let i=this._channelMap[e];return t?!!i:!!i&&i.state===_chunk26YZNXPKjs.a.SUBSCRIBED}_triggerChannelSubscribe(e){let t=e.name;e.state=_chunk26YZNXPKjs.a.SUBSCRIBED,this._channelEventDemux.write(`${t}/subscribe`,{}),this._broker.subscribeClient(this,t),this.emit("subscribe",{channel:t})}_triggerChannelUnsubscribe(e){let t=e.name;delete this._channelMap[t],e.state===_chunk26YZNXPKjs.a.SUBSCRIBED&&(this._channelEventDemux.write(`${t}/unsubscribe`,{}),this._broker.unsubscribeClient(this,t),this.emit("unsubscribe",{channel:t}))}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(i=>i.stream.indexOf(`${e}/`)===0).reduce((i,r)=>(i[r.stream]=!0,i),{});return Object.keys(t)}};var U=class extends _chunkKMDXU75Pjs.v{constructor(){super();this.isReady=!1,this._codec=null,this._exchangeClient=new R(this),this._clientSubscribers={},this._clientSubscribersCounter={},setTimeout(()=>{this.isReady=!0,this.emit("ready",{})},0)}exchange(){return this._exchangeClient}subscribeClient(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){this._clientSubscribers[t]||(this._clientSubscribers[t]={},this._clientSubscribersCounter[t]=0,this.emit("subscribe",{channel:t})),this._clientSubscribers[t][e.id]||this._clientSubscribersCounter[t]++,this._clientSubscribers[t][e.id]=e})}subscribeSocket(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){return this.subscribeClient(e,t)})}unsubscribeClient(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){this._clientSubscribers[t]&&this._clientSubscribers[t][e.id]&&(this._clientSubscribersCounter[t]--,delete this._clientSubscribers[t][e.id],this._clientSubscribersCounter[t]<=0&&(delete this._clientSubscribers[t],delete this._clientSubscribersCounter[t],this.emit("unsubscribe",{channel:t})))})}unsubscribeSocket(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){return this.unsubscribeClient(e,t)})}subscriptions(){return Object.keys(this._clientSubscribers)}isSubscribed(e){return!!this._clientSubscribers[e]}setCodecEngine(e){this._codec=e}invokePublish(e,t,i){return this.transmitPublish(e,t,i)}transmitPublish(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let r={channel:e,data:t},s={};if(this._codec)try{s.stringifiedData=this._codec.encode({event:"#publish",data:r})}catch(a){this.emit("error",{error:a});return}let n=this._clientSubscribers[e]||{};Object.keys(n).forEach(a=>{n[a].transmit("#publish",r,s)}),i||this.emit("publish",r)})}};function le(){return Math.abs(Math.random()*Math.random()*Date.now()|0).toString()+Math.abs(Math.random()*Math.random()*Date.now()|0).toString()}function ue(){return typeof process=="object"}var ce="handshakeWS",de="handshakeSC",me="message",be="transmit",pe="invoke",ge="subscribe",Se="publishIn",fe="publishOut",ve="authenticate",p= exports.TGAction =class{constructor(){this.outcome=null,this.HANDSHAKE_WS=ce,this.HANDSHAKE_SC=de,this.MESSAGE=me,this.TRANSMIT=be,this.INVOKE=pe,this.SUBSCRIBE=ge,this.PUBLISH_IN=Se,this.PUBLISH_OUT=fe,this.AUTHENTICATE=ve,this.promise=new Promise((o,e)=>{this._resolve=o,this._reject=e})}allow(o){if(this.outcome)throw new (0, _chunkKMDXU75Pjs.g)(`AGAction ${this.type} has already been ${this.outcome}; cannot allow`);this.outcome="allowed",this._resolve(o)}block(o){if(this.outcome)throw new (0, _chunkKMDXU75Pjs.g)(`AGAction ${this.type} has already been ${this.outcome}; cannot block`);this.outcome="blocked",this._reject(o)}};p.HANDSHAKE_WS=ce,p.HANDSHAKE_SC=de,p.MESSAGE=me,p.TRANSMIT=be,p.INVOKE=pe,p.SUBSCRIBE=ge,p.PUBLISH_IN=Se,p.PUBLISH_OUT=fe,p.AUTHENTICATE=ve;var Ie=4008,b=class extends _chunkKMDXU75Pjs.v{constructor(e,t,i,r){super();this._batchingIntervalId=null;this.id=e,this.server=t,this.socket=i,this.state=b.CONNECTING,this.authState=b.UNAUTHENTICATED,this.protocolVersion=r,this._receiverDemux=new _chunkKMDXU75Pjs.u,this._procedureDemux=new _chunkKMDXU75Pjs.u,this.request=this.socket.upgradeReq,this.inboundReceivedMessageCount=0,this.inboundProcessedMessageCount=0,this.outboundPreparedMessageCount=0,this.outboundSentMessageCount=0,this.cloneData=this.server.options.cloneData,this.inboundMessageStream=new _chunk4FLQOCQEjs.a,this.outboundPacketStream=new _chunk4FLQOCQEjs.a,this.middlewareHandshakeStream=this.request[S.SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM],this.middlewareInboundRawStream=new _chunk4FLQOCQEjs.a,this.middlewareInboundRawStream.type=S.MIDDLEWARE_INBOUND_RAW,this.middlewareInboundStream=new _chunk4FLQOCQEjs.a,this.middlewareInboundStream.type=S.MIDDLEWARE_INBOUND,this.middlewareOutboundStream=new _chunk4FLQOCQEjs.a,this.middlewareOutboundStream.type=S.MIDDLEWARE_OUTBOUND,this.request.connection?(this.remoteAddress=this.request.connection.remoteAddress,this.remoteFamily=this.request.connection.remoteFamily,this.remotePort=this.request.connection.remotePort):(this.remoteAddress=this.request.remoteAddress,this.remoteFamily=this.request.remoteFamily,this.remotePort=this.request.remotePort),this.request.forwardedForAddress&&(this.forwardedForAddress=this.request.forwardedForAddress),this.isBufferingBatch=!1,this.isBatching=!1,this.batchOnHandshake=this.server.options.batchOnHandshake,this.batchOnHandshakeDuration=this.server.options.batchOnHandshakeDuration,this.batchInterval=this.server.options.batchInterval,this._batchBuffer=[],this._batchingIntervalId=null,this._cid=1,this._callbackMap={},this.channelSubscriptions={},this.channelSubscriptionsCount=0,this._on("error",n=>_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){this.emitError(n)})),this._on("close",(n,a)=>_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let h=a&&a.toString();this._destroy(n,h)}));let s;this.protocolVersion===1?(s="#2",this._sendPing=()=>{this.state!==b.CLOSED&&this.send("#1")}):(s="",this._sendPing=()=>{this.state!==b.CLOSED&&this.send("")}),this.server.pingTimeoutDisabled||(this._pingIntervalTicker=setInterval(()=>{this._sendPing()},this.server.pingInterval)),this._resetPongTimeout(),this._handshakeTimeoutRef=setTimeout(()=>{this._handleHandshakeTimeout()},this.server.handshakeTimeout),this.server.pendingClients[this.id]=this,this.server.pendingClientsCount++,this._handleInboundMessageStream(s),this._handleOutboundPacketStream(),this._on("message",(n,a)=>_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let h=a?n:n.toString();if(this.inboundReceivedMessageCount++,h===s&&this._resetPongTimeout(),this.server.hasMiddleware(S.MIDDLEWARE_INBOUND_RAW)){let u=new p;u.socket=this,u.type=p.MESSAGE,u.data=h;try{let{data:m}=yield this.server.processMiddlewareAction(this.middlewareInboundRawStream,u,this);h=m}catch(m){this.inboundProcessedMessageCount++;return}}this.inboundMessageStream.write(h),this.emit("message",{message:h})}))}getBackpressure(){return Math.max(this.getInboundBackpressure(),this.getOutboundBackpressure(),this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure())}getInboundBackpressure(){return this.inboundReceivedMessageCount-this.inboundProcessedMessageCount}getOutboundBackpressure(){return this.outboundPreparedMessageCount-this.outboundSentMessageCount}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)}emit(e,t){return super.emit(e,t)}getState(){return this.state}getBytesReceived(){return this.socket.bytesReceived}emitError(e){this.emit("error",{error:e}),this.server.emitWarning(e)}closeAllMiddlewares(){this.middlewareHandshakeStream.close(),this.middlewareInboundRawStream.close(),this.middlewareInboundStream.close(),this.middlewareOutboundStream.close()}closeInput(){this.inboundMessageStream.close()}closeOutput(){this.outboundPacketStream.close()}closeIO(){this.closeInput(),this.closeOutput()}closeAllStreams(){this.closeAllMiddlewares(),this.closeIO(),this.closeAllReceivers(),this.closeAllProcedures(),this.closeAllListeners()}killAllMiddlewares(){this.middlewareHandshakeStream.kill(),this.middlewareInboundRawStream.kill(),this.middlewareInboundStream.kill(),this.middlewareOutboundStream.kill()}killInput(){this.inboundMessageStream.kill()}killOutput(){this.outboundPacketStream.kill()}killIO(){this.killInput(),this.killOutput()}killAllStreams(){this.killAllMiddlewares(),this.killIO(),this.killAllReceivers(),this.killAllProcedures(),this.killAllListeners()}disconnect(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(e=e||1e3,typeof e!="number"){let i=new (0, _chunkKMDXU75Pjs.h)("If specified, the code argument must be a number");this.emitError(i)}this.state!==b.CLOSED&&(yield this._destroy(e,t),this.socket.close(e,t))})}terminate(){this.server.options.isNode?this.socket.terminate():this.disconnect()}send(e,t){this.server.options.isNode?this.socket.send(e,t,i=>{i&&(this.emitError(i),this._destroy(1006,i.toString()))}):this.socket.send(e)}decode(e){return this.server.codec.decode(e)}encode(e){return this.server.codec.encode(e)}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=[]}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}serializeObject(e){let t;try{t=this.encode(e)}catch(i){return this.emitError(i),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}transmit(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(this.state!==b.OPEN){let r=new (0, _chunkKMDXU75Pjs.n)(`Socket transmit "${e}" was aborted due to a bad connection`,"connectAbort");this.emitError(r);return}this._transmit(e,t,i)})}invoke(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(this.state!==b.OPEN){let r=new (0, _chunkKMDXU75Pjs.n)(`Socket invoke "${e}" was aborted due to a bad connection`,"connectAbort");throw this.emitError(r),r}return this.cloneData&&(t=_chunkKMDXU75Pjs.y.call(void 0, t)),this.outboundPreparedMessageCount++,new Promise((r,s)=>{this.outboundPacketStream.write({event:e,data:t,options:i,resolve:r,reject:s})})})}triggerAuthenticationEvents(e){if(e!==b.AUTHENTICATED){let t={oldState:e,newState:this.authState,authToken:this.authToken};this.emit("authStateChange",t),this.server.emit("authenticationStateChange",_chunkMY4YFY5Tjs.a.call(void 0, {socket:this},t))}this.emit("authenticate",{authToken:this.authToken}),this.server.emit("authentication",{socket:this,authToken:this.authToken})}setAuthToken(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(this.state===b.CONNECTING){let u=new (0, _chunkKMDXU75Pjs.g)("Cannot call setAuthToken before completing the handshake");throw this.emitError(u),u}let i=_chunkKMDXU75Pjs.y.call(void 0, e),r=this.authState;if(this.authState=b.AUTHENTICATED,t==null)t={};else if(t=_chunkMY4YFY5Tjs.a.call(void 0, {},t),t.algorithm!=null){delete t.algorithm;let u=new (0, _chunkKMDXU75Pjs.h)("Cannot change auth token algorithm at runtime - It must be specified as a config option on launch");this.emitError(u)}let s=t.rejectOnFailedDelivery;delete t.rejectOnFailedDelivery;let n=this.server.defaultSignatureOptions,a;e.exp==null?a=n.expiresIn:a=e.exp,i?i.exp==null?e.exp=a:delete e.exp:e.exp=a,n.algorithm!=null&&(t.algorithm=n.algorithm),this.authToken=i;let h;try{h=yield this.server.auth.signToken(i,this.server.signatureKey,t)}catch(u){throw this.emitError(u),this._destroy(4002,u.toString()),this.socket.close(4002),u}this.authToken===i&&(this.signedAuthToken=h,this.emit("authTokenSigned",{signedAuthToken:h})),this.triggerAuthenticationEvents(r);let c={token:h};if(s){try{yield this.invoke("#setAuthToken",c)}catch(u){let m=new (0, _chunkKMDXU75Pjs.e)(`Failed to deliver auth token to client - ${u}`);throw this.emitError(m),m}return}this.transmit("#setAuthToken",c)})}getAuthToken(){return this.authToken}deauthenticateSelf(){let e=this.authState,t=this.authToken;if(this.signedAuthToken=null,this.authToken=null,this.authState=b.UNAUTHENTICATED,e!==b.UNAUTHENTICATED){let i={oldState:e,newState:this.authState};this.emit("authStateChange",i),this.server.emit("authenticationStateChange",_chunkMY4YFY5Tjs.a.call(void 0, {socket:this},i))}this.emit("deauthenticate",{oldAuthToken:t}),this.server.emit("deauthentication",{socket:this,oldAuthToken:t})}deauthenticate(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(this.deauthenticateSelf(),e&&e.rejectOnFailedDelivery){try{yield this.invoke("#removeAuthToken")}catch(t){if(this.emitError(t),e&&e.rejectOnFailedDelivery)throw t}return}this._transmit("#removeAuthToken")})}kickOut(e,t){let i=e;return i||(i=Object.keys(this.channelSubscriptions)),Array.isArray(i)||(i=[e]),Promise.all(i.map(r=>(this.transmit("#kickOut",{channel:r,message:t}),this._unsubscribe(r))))}subscriptions(){return Object.keys(this.channelSubscriptions)}isSubscribed(e){return!!this.channelSubscriptions[e]}isAuthTokenExpired(e){if(e&&e.exp!=null){let t=Date.now(),i=e.exp*1e3;return t>i}return!1}_processAuthentication(s){return _chunkMY4YFY5Tjs.c.call(void 0, this,arguments,function*({signedAuthToken:e,authTokenError:t,authToken:i,authState:r}){if(t)throw this.signedAuthToken=null,this.authToken=null,this.authState=b.UNAUTHENTICATED,e!=null&&(this.emitError(t),t.isBadToken&&this._emitBadAuthTokenError(t,e)),t;this.signedAuthToken=e,this.authToken=i,this.authState=b.AUTHENTICATED;let n=new p;n.socket=this,n.type=p.AUTHENTICATE,n.signedAuthToken=this.signedAuthToken,n.authToken=this.authToken;try{yield this.server.processMiddlewareAction(this.middlewareInboundStream,n,this)}catch(a){throw this.authToken=null,this.authState=b.UNAUTHENTICATED,a.isBadToken&&this._emitBadAuthTokenError(a,e),a}})}_validateAuthToken(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=Object.assign({},this.server.defaultVerificationOptions,{socket:this,throwError:!0}),i;try{i=yield this.server.auth.verifyToken(e,this.server.verificationKey,t)}catch(r){let s=this._processTokenError(r);return{signedAuthToken:e,authTokenError:s,authToken:null,authState:b.UNAUTHENTICATED}}return{signedAuthToken:e,authTokenError:null,authToken:i,authState:b.AUTHENTICATED}})}_emitBadAuthTokenError(e,t){this.emit("badAuthToken",{authError:e,signedAuthToken:t}),this.server.emit("badSocketAuthToken",{socket:this,authError:e,signedAuthToken:t})}_processTokenError(e){if(e){if(e.message==="TokenExpiredError"){let i=new (0, _chunkKMDXU75Pjs.a)(e.message,e.expiredAt);return i.isBadToken=!0,i}if(e.message==="ParseError"){let i=new (0, _chunkKMDXU75Pjs.b)(e.message);return i.isBadToken=!0,i}if(e.message==="NotYetValid"){let i=new (0, _chunkKMDXU75Pjs.c)(e.message,e.date);return i.isBadToken=!1,i}let t=new (0, _chunkKMDXU75Pjs.d)(e.message);return t.isBadToken=!0,t}return null}_processAuthTokenExpiry(){let e=this.getAuthToken();return this.isAuthTokenExpired(e)?(this.deauthenticate(),new (0, _chunkKMDXU75Pjs.a)("The socket auth token has expired",e.exp)):null}_invoke(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){return i=i||{},new Promise((r,s)=>{let n={event:e,cid:this._nextCallId()};t!==void 0&&(n.data=t);let a=i.ackTimeout==null?this.server.ackTimeout:i.ackTimeout,h=setTimeout(()=>{let c=new (0, _chunkKMDXU75Pjs.m)(`Event response for "${e}" timed out`);delete this._callbackMap[n.cid],s(c)},a);this._callbackMap[n.cid]={event:e,callback:(c,u)=>{if(c){s(c);return}r(u)},timeout:h},i.useCache&&i.stringifiedData!=null&&!this.isBufferingBatch?this.send(i.stringifiedData):this.sendObject(n)})})}_processTransmit(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let r,s=i?i.useCache:!1,n={event:e,data:t},a=e==="#publish";if(a){let h=new p;h.socket=this,h.type=p.PUBLISH_OUT,t!==void 0&&(h.channel=t.channel,h.data=t.data),s=!this.server.hasMiddleware(this.middlewareOutboundStream.type);try{let{data:c,options:u}=yield this.server.processMiddlewareAction(this.middlewareOutboundStream,h,this);r=c,s=u==null?s:u.useCache}catch(c){return}}else r=n.data;if(i&&s&&i.stringifiedData!=null&&!this.isBufferingBatch)this.send(i.stringifiedData);else{let h={event:e};a?(h.data=t||{},h.data.data=r):h.data=r,this.sendObject(h)}})}_transmit(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){this.cloneData&&t&&(t=_chunkKMDXU75Pjs.y.call(void 0, t)),this.outboundPreparedMessageCount++,this.outboundPacketStream.write({event:e,data:t,options:i})})}_handleOutboundPacketStream(){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){try{for(var e=_chunkMY4YFY5Tjs.d.call(void 0, this.outboundPacketStream),t,i,r;t=!(i=yield e.next()).done;t=!1){let s=i.value;if(s.resolve){_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let n;try{n=yield this._invoke(s.event,s.data,s.options)}catch(a){s.reject(a);return}s.resolve(n)}),this.outboundSentMessageCount++;continue}yield this._processTransmit(s.event,s.data,s.options),this.outboundSentMessageCount++}}catch(i){r=[i]}finally{try{t&&(i=e.return)&&(yield i.call(e))}finally{if(r)throw r[0]}}})}_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.batchInterval))}_destroy(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(clearInterval(this._pingIntervalTicker),clearTimeout(this._pingTimeoutTicker),this._cancelBatching(),this.state===b.CLOSED)this._abortAllPendingEventsDueToBadConnection("connectAbort");else{!t&&b.errorStatuses[e]&&(t=b.errorStatuses[e]);let i=this.state;if(this.state=b.CLOSED,i===b.CONNECTING?(this._abortAllPendingEventsDueToBadConnection("connectAbort"),this.emit("connectAbort",{code:e,reason:t}),this.server.emit("connectionAbort",{socket:this,code:e,reason:t})):(this._abortAllPendingEventsDueToBadConnection("disconnect"),this.emit("disconnect",{code:e,reason:t}),this.server.emit("disconnection",{socket:this,code:e,reason:t})),this.emit("close",{code:e,reason:t}),this.server.emit("closure",{socket:this,code:e,reason:t}),clearTimeout(this._handshakeTimeoutRef),!!this.server.clients[this.id]&&(delete this.server.clients[this.id],this.server.clientsCount--),!!this.server.pendingClients[this.id]&&(delete this.server.pendingClients[this.id],this.server.pendingClientsCount--),!b.ignoreStatuses[e]){let a;if(t){let c;if(typeof t=="object")try{c=JSON.stringify(t)}catch(u){c=t.toString()}else c=t;a=`Socket connection closed with status code ${e} and reason: ${c}`}else a=`Socket connection closed with status code ${e}`;let h=new (0, _chunkKMDXU75Pjs.k)(b.errorStatuses[e]||a,e);this.emitError(h)}yield this._unsubscribeFromAllChannels();let n=this.server.options.socketStreamCleanupMode;n==="kill"?_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){yield this.listener("end").once(),this.killAllStreams()}):n==="close"&&_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){yield this.listener("end").once(),this.closeAllStreams()}),this.emit("end")}})}_abortAllPendingEventsDueToBadConnection(e){Object.keys(this._callbackMap||{}).forEach(t=>{let i=this._callbackMap[t];delete this._callbackMap[t],clearTimeout(i.timeout),delete i.timeout;let r=`Event "${i.event}" was aborted due to a bad connection`,s=new (0, _chunkKMDXU75Pjs.n)(r,e),n=i.callback;delete i.callback,n.call(i,s,i)})}_handleInboundMessageStream(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){try{for(var t=_chunkMY4YFY5Tjs.d.call(void 0, this.inboundMessageStream),i,r,s;i=!(r=yield t.next()).done;i=!1){let n=r.value;if(this.inboundProcessedMessageCount++,n===e){if(this.server.strictHandshake&&this.state===b.CONNECTING){this._destroy(4009),this.socket.close(4009);continue}let c=this.getAuthToken();this.isAuthTokenExpired(c)&&this.deauthenticate();continue}let h;try{h=this.decode(n)}catch(c){c.name==="Error"&&(c.name="InvalidMessageError"),this.emitError(c),this.server.strictHandshake&&this.state===b.CONNECTING&&(this._destroy(4009),this.socket.close(4009));continue}if(Array.isArray(h)){let c=h.length;for(let u=0;u<c;u++)yield this._processInboundPacket(h[u],n)}else yield this._processInboundPacket(h,n)}}catch(r){s=[r]}finally{try{i&&(r=t.return)&&(yield r.call(t))}finally{if(s)throw s[0]}}})}_handleHandshakeTimeout(){this.disconnect(4005)}_processHandshakeRequest(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let i=(e.data||{}).authToken||null;clearTimeout(this._handshakeTimeoutRef);let r=yield this._validateAuthToken(i),s=new p;s.request=this.request,s.socket=this,s.type=p.HANDSHAKE_SC,s.data=r;try{yield this.server.processMiddlewareAction(this.middlewareHandshakeStream,s)}catch(c){c.statusCode==null&&(c.statusCode=Ie),e.error(c),this.disconnect(c.statusCode);return}let n={id:this.id,pingTimeout:this.server.pingTimeout,isAuthenticated:!1},a={id:this.id,pingTimeout:this.server.pingTimeout,isAuthenticated:!1},h=this.authState;try{if(yield this._processAuthentication(r),this.state===b.CLOSED)return}catch(c){i!=null&&(n.authError=_chunkKMDXU75Pjs.r.call(void 0, c),a.authError=c,c.isBadToken&&this.deauthenticate())}n.isAuthenticated=!!this.authToken,a.isAuthenticated=n.isAuthenticated,this.server.pendingClients[this.id]&&(delete this.server.pendingClients[this.id],this.server.pendingClientsCount--),this.server.clients[this.id]=this,this.server.clientsCount++,this.state=b.OPEN,n.isAuthenticated&&_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){yield this.listener("connect").once(),this.triggerAuthenticationEvents(h)}),e.end(n),this.batchOnHandshake&&this._startBatchOnHandshake(),this.emit("connect",a),this.server.emit("connection",_chunkMY4YFY5Tjs.a.call(void 0, {socket:this},a)),this.middlewareHandshakeStream.close()})}_startBatchOnHandshake(){this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)}_processAuthenticateRequest(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=e.data,i=this.authState,r=yield this._validateAuthToken(t);try{yield this._processAuthentication(r)}catch(s){if(s.isBadToken){this.deauthenticate(),e.error(s);return}e.end({isAuthenticated:!!this.authToken,authError:t==null?null:_chunkKMDXU75Pjs.r.call(void 0, s)});return}this.triggerAuthenticationEvents(i),e.end({isAuthenticated:!!this.authToken,authError:null})})}_subscribeSocket(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(e===void 0||!t)throw new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} provided a malformated channel payload`);if(this.server.socketChannelLimit&&this.channelSubscriptionsCount>=this.server.socketChannelLimit)throw new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} tried to exceed the channel subscription limit of ${this.server.socketChannelLimit}`);if(typeof e!="string")throw new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} provided an invalid channel name`);this.channelSubscriptionsCount==null&&(this.channelSubscriptionsCount=0),this.channelSubscriptions[e]==null&&(this.channelSubscriptions[e]=!0,this.channelSubscriptionsCount++);try{yield this.server.brokerEngine.subscribeSocket(this,e)}catch(i){throw delete this.channelSubscriptions[e],this.channelSubscriptionsCount--,i}this.emit("subscribe",{channel:e,subscriptionOptions:t}),this.server.emit("subscription",{socket:this,channel:e,subscriptionOptions:t})})}_processSubscribeRequest(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=Object.assign({},e.data),i=t.channel;if(delete t.channel,this.state===b.OPEN){try{yield this._subscribeSocket(i,t)}catch(s){let n=new (0, _chunkKMDXU75Pjs.o)(`Failed to subscribe socket to the ${i} channel - ${s}`);this.emitError(n),e.error(n);return}e.end();return}let r=new (0, _chunkKMDXU75Pjs.g)("Cannot subscribe socket to a channel before it has completed the handshake");this.emitError(r),e.error(r)})}_unsubscribeFromAllChannels(){let e=Object.keys(this.channelSubscriptions);return Promise.all(e.map(t=>this._unsubscribe(t)))}_unsubscribe(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(typeof e!="string")throw new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} tried to unsubscribe from an invalid channel name`);if(!this.channelSubscriptions[e])throw new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} tried to unsubscribe from a channel which it is not subscribed to`);try{yield this.server.brokerEngine.unsubscribeSocket(this,e),delete this.channelSubscriptions[e],this.channelSubscriptionsCount!=null&&this.channelSubscriptionsCount--,this.emit("unsubscribe",{channel:e}),this.server.emit("unsubscription",{socket:this,channel:e})}catch(t){let i=new (0, _chunkKMDXU75Pjs.o)(`Failed to unsubscribe socket from the ${e} channel - ${t}`);this.emitError(i)}})}_processUnsubscribePacket(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=e.data;try{yield this._unsubscribe(t)}catch(i){let r=new (0, _chunkKMDXU75Pjs.o)(`Failed to unsubscribe socket from the ${t} channel - ${i}`);this.emitError(r)}})}_processUnsubscribeRequest(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=e.data;try{yield this._unsubscribe(t)}catch(i){let r=new (0, _chunkKMDXU75Pjs.o)(`Failed to unsubscribe socket from the ${t} channel - ${i}`);this.emitError(r),e.error(r);return}e.end()})}_processInboundPublishPacket(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=e.data||{};if(typeof t.channel!="string"){let i=new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} tried to invoke publish to an invalid "${t.channel}" channel`);this.emitError(i);return}try{yield this.server.exchange.invokePublish(t.channel,t.data)}catch(i){this.emitError(i)}})}_processInboundPublishRequest(e){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let t=e.data||{};if(typeof t.channel!="string"){let i=new (0, _chunkKMDXU75Pjs.g)(`Socket ${this.id} tried to transmit publish to an invalid "${t.channel}" channel`);this.emitError(i),e.error(i);return}try{yield this.server.exchange.invokePublish(t.channel,t.data)}catch(i){this.emitError(i),e.error(i);return}e.end()})}_processInboundPacket(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(e&&e.event!=null){let i=e.event,r=e.cid!=null;if(i==="#handshake"){let m=new (0, _chunkKMDXU75Pjs.z)(this,e.cid,i,e.data);yield this._processHandshakeRequest(m),this._procedureDemux.write(i,m);return}if(this.server.strictHandshake&&this.state===b.CONNECTING){this._destroy(4009),this.socket.close(4009);return}if(i==="#authenticate"){let m=new (0, _chunkKMDXU75Pjs.z)(this,e.cid,i,e.data);yield this._processAuthenticateRequest(m),this._procedureDemux.write(i,m);return}if(i==="#removeAuthToken"){this.deauthenticateSelf(),this._receiverDemux.write(i,e.data);return}let s=new p;s.socket=this;let n=this._processAuthTokenExpiry();n&&(s.authTokenExpiredError=n);let a=i==="#publish",h=i==="#subscribe",c=i==="#unsubscribe";if(a){if(!this.server.allowClientPublish){let m=new (0, _chunkKMDXU75Pjs.g)("Client publish feature is disabled");this.emitError(m),r&&new (0, _chunkKMDXU75Pjs.z)(this,e.cid,i,e.data).error(m);return}s.type=p.PUBLISH_IN,e.data&&(s.channel=e.data.channel,s.data=e.data.data)}else if(h)s.type=p.SUBSCRIBE,e.data&&(s.channel=e.data.channel,s.data=e.data.data);else if(c){if(r){let m=new (0, _chunkKMDXU75Pjs.z)(this,e.cid,i,e.data);yield this._processUnsubscribeRequest(m),this._procedureDemux.write(i,m);return}yield this._processUnsubscribePacket(e),this._receiverDemux.write(i,e.data);return}else r?(s.type=p.INVOKE,s.procedure=e.event,e.data!==void 0&&(s.data=e.data)):(s.type=p.TRANSMIT,s.receiver=e.event,e.data!==void 0&&(s.data=e.data));let u;if(r){let m=new (0, _chunkKMDXU75Pjs.z)(this,e.cid,i,e.data);try{let{data:B}=yield this.server.processMiddlewareAction(this.middlewareInboundStream,s,this);u=B}catch(B){m.error(B);return}h?(m.data||(m.data={}),m.data.data=u,yield this._processSubscribeRequest(m)):a?(m.data||(m.data={}),m.data.data=u,yield this._processInboundPublishRequest(m)):m.data=u,this._procedureDemux.write(i,m);return}try{let{data:m}=yield this.server.processMiddlewareAction(this.middlewareInboundStream,s,this);u=m}catch(m){return}a&&(e.data||(e.data={}),e.data.data=u,yield this._processInboundPublishPacket(e)),this._receiverDemux.write(i,u);return}if(this.server.strictHandshake&&this.state===b.CONNECTING){this._destroy(4009),this.socket.close(4009);return}if(e&&e.rid!=null){let i=this._callbackMap[e.rid];if(i){clearTimeout(i.timeout),delete this._callbackMap[e.rid];let r=_chunkKMDXU75Pjs.s.call(void 0, e.error);i.callback(r,e.data)}return}this.emit("raw",{message:t})})}_resetPongTimeout(){this.server.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4001),this.socket.close(4001)},this.server.pingTimeout))}_nextCallId(){return this._cid++}_on(e,t){if(this.server.options.isNode)this.socket.on(e,t);else switch(e){case"message":this.socket.addEventListener(e,i=>t(i.data));break;case"close":case"error":this.socket.addEventListener(e,i=>t(i));break}}},v= exports.TGServerSocket =b;v.CONNECTING="connecting",v.OPEN="open",v.CLOSED="closed",v.AUTHENTICATED="authenticated",v.UNAUTHENTICATED="unauthenticated",v.ignoreStatuses=_chunkKMDXU75Pjs.q,v.errorStatuses=_chunkKMDXU75Pjs.p;var Ae="handshake",ye= exports.MIDDLEWARE_INBOUND_RAW ="inboundRaw",ke= exports.MIDDLEWARE_INBOUND ="inbound",Ee= exports.MIDDLEWARE_OUTBOUND ="outbound";var f=class extends _chunkKMDXU75Pjs.v{constructor(e){super();let t={brokerEngine:new U,wsEngine:"ws",wsEngineServerOptions:{},maxPayload:null,allowClientPublish:!0,ackTimeout:1e4,handshakeTimeout:1e4,strictHandshake:!0,pingTimeout:2e4,pingTimeoutDisabled:!1,pingInterval:8e3,origins:"*:*",path:"/topgunsocket/",protocolVersion:2,authDefaultExpiry:86400,batchOnHandshake:!1,batchOnHandshakeDuration:400,batchInterval:50,middlewareEmitFailures:!0,socketStreamCleanupMode:"kill",cloneData:!1,isNode:ue()};if(this.options=Object.assign(t,e),this._middleware={},this.origins=this.options.origins,this._allowAllOrigins=this.origins.indexOf("*:*")!==-1,this.ackTimeout=this.options.ackTimeout,this.handshakeTimeout=this.options.handshakeTimeout,this.pingInterval=this.options.pingInterval,this.pingTimeout=this.options.pingTimeout,this.pingTimeoutDisabled=this.options.pingTimeoutDisabled,this.allowClientPublish=this.options.allowClientPublish,this.perMessageDeflate=this.options.perMessageDeflate,this.httpServer=this.options.httpServer,this.socketChannelLimit=this.options.socketChannelLimit,this.protocolVersion=this.options.protocolVersion,this.strictHandshake=this.options.strictHandshake,this.brokerEngine=this.options.brokerEngine,this.middlewareEmitFailures=this.options.middlewareEmitFailures,this._path=t.path,_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){try{for(var s=_chunkMY4YFY5Tjs.d.call(void 0, this.brokerEngine.listener("error")),n,a,h;n=!(a=yield s.next()).done;n=!1){let{error:c}=a.value;this.emitWarning(c)}}catch(a){h=[a]}finally{try{n&&(a=s.return)&&(yield a.call(s))}finally{if(h)throw h[0]}}}),this.brokerEngine.isReady?(this.isReady=!0,this.emit("ready",{})):(this.isReady=!1,_chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){yield this.brokerEngine.listener("ready").once(),this.isReady=!0,this.emit("ready",{})})),!this.options.wsEngine)throw new (0, _chunkKMDXU75Pjs.i)("The wsEngine option must be a path or module name which points to a valid WebSocket engine module with a compatible interface");let i=this.options.wsEngine;if(this.options.authPrivateKey!=null||this.options.authPublicKey!=null){if(this.options.authPrivateKey==null)throw new (0, _chunkKMDXU75Pjs.i)("The authPrivateKey option must be specified if authPublicKey is specified");if(this.options.authPublicKey==null)throw new (0, _chunkKMDXU75Pjs.i)("The authPublicKey option must be specified if authPrivateKey is specified");this.signatureKey=this.options.authPrivateKey,this.verificationKey=this.options.authPublicKey}else this.options.authKey==null&&(this.options.authKey=he(32).toString()),this.signatureKey=this.options.authKey,this.verificationKey=this.options.authKey;this.defaultVerificationOptions={},this.options.authVerifyAlgorithm!=null?this.defaultVerificationOptions.algorithm=this.options.authVerifyAlgorithm:this.options.authAlgorithm!=null&&(this.defaultVerificationOptions.algorithm=this.options.authAlgorithm),this.defaultSignatureOptions={expiresIn:this.options.authDefaultExpiry},this.options.authAlgorithm!=null&&(this.defaultSignatureOptions.algorithm=this.options.authAlgorithm),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new H,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunkKMDXU75Pjs.w,this.brokerEngine.setCodecEngine(this.codec),this.exchange=this.brokerEngine.exchange(),this.clients={},this.clientsCount=0,this.pendingClients={},this.pendingClientsCount=0;let r=this.options.wsEngineServerOptions||{};r.server=this.httpServer,r.verifyClient=this.verifyHandshake.bind(this),r.path==null&&this._path!=null&&(r.path=this._path),r.perMessageDeflate==null&&this.perMessageDeflate!=null&&(r.perMessageDeflate=this.perMessageDeflate),r.handleProtocols==null&&this.options.handleProtocols!=null&&(r.handleProtocols=this.options.handleProtocols),r.maxPayload==null&&t.maxPayload!=null&&(r.maxPayload=t.maxPayload),r.clientTracking==null&&(r.clientTracking=!1),this.options.isNode?(this.wsServer=new i(r),this.wsServer.on("error",this._handleServerError.bind(this)),this.wsServer.on("connection",this._handleSocketConnection.bind(this))):(this.wsServer=i,this.wsServer.addEventListener("close",this._closeOrErrorHandler.bind(this)),this.wsServer.addEventListener("error",this._closeOrErrorHandler.bind(this)))}setAuthEngine(e){this.auth=e}setCodecEngine(e){this.codec=e,this.brokerEngine.setCodecEngine(e)}emit(e,t){return super.emit(e,t)}listener(e){return super.listener(e)}emitError(e){this.emit("error",{error:e})}emitWarning(e){this.emit("warning",{warning:e})}close(e){return this.isReady=!1,new Promise((t,i)=>{if(this.wsServer.close(r=>{if(r){i(r);return}t()}),!e)for(let r of Object.values(this.clients))r.terminate()})}getPath(){return this._path}generateId(){return le()}setMiddleware(e,t){if(e!==f.MIDDLEWARE_HANDSHAKE&&e!==f.MIDDLEWARE_INBOUND_RAW&&e!==f.MIDDLEWARE_INBOUND&&e!==f.MIDDLEWARE_OUTBOUND)throw new (0, _chunkKMDXU75Pjs.h)(`Middleware type "${e}" is not supported`);if(this._middleware[e])throw new (0, _chunkKMDXU75Pjs.g)(`Middleware type "${e}" has already been set`);this._middleware[e]=t}removeMiddleware(e){delete this._middleware[e]}hasMiddleware(e){return!!this._middleware[e]}verifyHandshake(e,t){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){let i=e.req,r=e.origin;(r==="null"||r==null)&&(r="*");let s=!1;if(this._allowAllOrigins)s=!0;else try{let u=new URL(r),m=u.port||(u.protocol==="https:"?443:80);s=~this.origins.indexOf(u.hostname+":"+m)||~this.origins.indexOf(u.hostname+":*")||~this.origins.indexOf("*:"+m)}catch(u){}let n=new _chunk4FLQOCQEjs.a;n.type=f.MIDDLEWARE_HANDSHAKE,i[f.SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM]=n;let a=this._middleware[f.MIDDLEWARE_HANDSHAKE];a&&a(n);let h=new p;h.request=i,h.type=p.HANDSHAKE_WS;try{yield this.processMiddlewareAction(n,h)}catch(u){n.close(),t(!1,401,typeof u=="string"?u:u.message);return}if(s){t(!0);return}let c=new (0, _chunkKMDXU75Pjs.l)(`Failed to authorize socket handshake - Invalid origin: ${r}`);this.emitWarning(c),n.close(),t(!1,403,c.message)})}processMiddlewareAction(e,t,i){return _chunkMY4YFY5Tjs.c.call(void 0, this,null,function*(){if(!this.hasMiddleware(e.type))return{data:t.data,options:null};e.write(t);let r,s=null;try{let n=yield t.promise;n&&(r=n.data,s=n.options)}catch(n){let a;throw n?n.silent?a=new (0, _chunkKMDXU75Pjs.f)(`The ${t.type} AGAction was blocked by ${e.type} middleware`,e.type):a=n:(n=new (0, _chunkKMDXU75Pjs.f)(`The ${t.type} AGAction was blocked by ${e.type} middleware`,e.type),a=n),this.middlewareEmitFailures&&(i?i.emitError(n):this.emitWarning(n)),a}return r===void 0&&(r=t.data),{data:r,options:s}})}_closeOrErrorHandler(e){e&&this.emitError(e),this.close()}_handleServerError(e){typeof e=="string"&&(e=new (0, _chunkKMDXU75Pjs.l)(e)),this.emitError(e)}_handleSocketConnection(e,t){e.upgradeReq||(e.upgradeReq=t);let i=this.generateId(),r=new v(i,this,e,this.protocolVersion);r.exchange=this.exchange;let s=this._middleware[f.MIDDLEWARE_INBOUND_RAW];s&&s(r.middlewareInboundRawStream);let n=this._middleware[f.MIDDLEWARE_INBOUND];n&&n(r.middlewareInboundStream);let a=this._middleware[f.MIDDLEWARE_OUTBOUND];a&&a(r.middlewareOutboundStream),this.emit("handshake",{socket:r})}},S= exports.TGServerSocketGateway =f;S.MIDDLEWARE_HANDSHAKE=Ae,S.MIDDLEWARE_INBOUND_RAW=ye,S.MIDDLEWARE_INBOUND=ke,S.MIDDLEWARE_OUTBOUND=Ee,S.SYMBOL_MIDDLEWARE_HANDSHAKE_STREAM=Symbol("handshakeStream");function Yt(d,o){return _chunkKMDXU75Pjs.x.call(void 0, o)||(o={}),o.httpServer=d,new S(o)}exports.MIDDLEWARE_HANDSHAKE = Ae; exports.MIDDLEWARE_INBOUND = ke; exports.MIDDLEWARE_INBOUND_RAW = ye; exports.MIDDLEWARE_OUTBOUND = Ee; exports.TGAction = p; exports.TGServerSocket = v; exports.TGServerSocketGateway = S; exports.attach = Yt; |
@@ -1,1 +0,1 @@ | ||
var topGunSocket=(()=>{var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(i,e)=>{for(var t in e)a(i,t,{get:e[t],enumerable:!0})},p=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of c(e))!h.call(i,s)&&s!==t&&a(i,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return i};var b=i=>p(a({},"__esModule",{value:!0}),i);var y={};_(y,{WritableConsumableStream:()=>m});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){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.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=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),!(this.currentNode.consumerId&&this.currentNode.consumerId!==this.id))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 o=new Error("Stream consumer iteration timed out");(async()=>{let l=v(e);s=l.timeoutId,await l.promise,o.name="TimeoutError",delete this._resolve,r(o)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function v(i){let e,t=new Promise(r=>{e=setTimeout(r,i)});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 o of this._consumers.values())o.write(s.data)}};return b(y);})(); | ||
var topGunSocket=(()=>{var h=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var y=(i,t)=>{for(var e in t)h(i,e,{get:t[e],enumerable:!0})},f=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of b(t))!v.call(i,s)&&s!==e&&h(i,s,{get:()=>t[s],enumerable:!(r=p(t,s))||r.enumerable});return i};var C=i=>f(h({},"__esModule",{value:!0}),i);var u=(i,t,e)=>new Promise((r,s)=>{var o=n=>{try{d(e.next(n))}catch(c){s(c)}},a=n=>{try{d(e.throw(n))}catch(c){s(c)}},d=n=>n.done?r(n.value):Promise.resolve(n.value).then(o,a);d((e=e.apply(i,t)).next())});var T={};y(T,{WritableConsumableStream:()=>_});var m=class{next(t){return u(this,null,function*(){let e=this.createConsumer(t),r=yield e.next();return e.return(),r})}once(t){return u(this,null,function*(){let e=yield this.next(t);return e.done&&(yield new Promise(()=>{})),e.value})}createConsumer(t){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var l=class{constructor(t,e,r,s){this.id=e,this._backpressure=0,this.stream=t,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let t={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(t.timeout=this.timeout),t}applyBackpressure(t){this._backpressure++}releaseBackpressure(t){this._backpressure--}getBackpressure(){return this._backpressure}write(t){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(t),this._resolve&&(this._resolve(),delete this._resolve)}kill(t){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:t,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}next(){return u(this,null,function*(){for(this.stream.setConsumer(this.id,this);;){if(!this.currentNode.next)try{yield this._waitForNextItem(this.timeout)}catch(t){throw this._destroy(),t}if(this._killPacket){this._destroy();let t=this._killPacket;return delete this._killPacket,t}if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),!(this.currentNode.consumerId&&this.currentNode.consumerId!==this.id))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)}_waitForNextItem(t){return u(this,null,function*(){return new Promise((e,r)=>{this._resolve=e;let s;if(t!==void 0){let o=new Error("Stream consumer iteration timed out");u(this,null,function*(){let a=k(t);s=a.timeoutId,yield a.promise,o.name="TimeoutError",delete this._resolve,r(o)})}this._timeoutId=s})})}[Symbol.asyncIterator](){return this}};function k(i){let t,e=new Promise(r=>{t=setTimeout(r,i)});return{timeoutId:t,promise:e}}var _=class extends m{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,r){this._write(r,!1,e)}closeConsumer(e,r){this._write(r,!0,e)}kill(e){for(let r of this._consumers.keys())this.killConsumer(r,e)}killConsumer(e,r){let s=this._consumers.get(e);!s||s.kill(r)}getBackpressure(){let e=0;for(let r of this._consumers.values()){let s=r.getBackpressure();s>e&&(e=s)}return e}getConsumerBackpressure(e){let r=this._consumers.get(e);return r?r.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,r){this._consumers.set(e,r),r.currentNode||(r.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let r=this._consumers.get(e);if(r)return r.getStats()}getConsumerStatsList(){let e=[];for(let r of this._consumers.values())e.push(r.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,r,s){let o={data:{value:e,done:r},next:null};s&&(o.consumerId=s),this._tailNode.next=o,this._tailNode=o;for(let a of this._consumers.values())a.write(o.data)}};return C(T);})(); |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWSYY47HQjs = require('./chunk-WSYY47HQ.js');require('./chunk-EQT5ZTTX.js');exports.WritableConsumableStream = _chunkWSYY47HQjs.a; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4FLQOCQEjs = require('./chunk-4FLQOCQE.js');require('./chunk-MY4YFY5T.js');exports.WritableConsumableStream = _chunk4FLQOCQEjs.a; |
{ | ||
"name": "topgun-socket", | ||
"version": "1.0.5", | ||
"version": "1.1.0", | ||
"description": "Scalable realtime pub/sub and RPC serverless framework", | ||
@@ -11,14 +11,8 @@ "publishConfig": { | ||
"prepublishOnly": "pnpm run build", | ||
"test": "vitest run", | ||
"test": "jest", | ||
"format": "prettier --write \"src/**/*.ts\"", | ||
"lint": "eslint \"src/**/*.ts\" --fix", | ||
"prepare": "simple-git-hooks", | ||
"semantic-release": "semantic-release" | ||
}, | ||
"simple-git-hooks": { | ||
"pre-commit": "npx lint-staged" | ||
}, | ||
"lint-staged": { | ||
"src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [ | ||
"prettier --write" | ||
] | ||
}, | ||
"browser": "dist/client.global.js", | ||
@@ -91,4 +85,4 @@ "exports": { | ||
"dependencies": { | ||
"@peculiar/webcrypto": "^1.4.3", | ||
"buffer": "^5.2.1", | ||
"topgun-webcrypto": "^1.0.3", | ||
"ws": "^8.9.0" | ||
@@ -103,3 +97,10 @@ }, | ||
"@semantic-release/release-notes-generator": "^10.0.3", | ||
"@types/jest": "^29.5.0", | ||
"@types/node": "^18.15.11", | ||
"@typescript-eslint/eslint-plugin": "^5.58.0", | ||
"@typescript-eslint/parser": "^5.58.0", | ||
"eslint": "^8.38.0", | ||
"eslint-config-prettier": "^8.8.0", | ||
"eslint-plugin-import": "^2.27.5", | ||
"jest": "^29.5.0", | ||
"lint-staged": "^13.2.1", | ||
@@ -109,6 +110,15 @@ "prettier": "^2.8.7", | ||
"simple-git-hooks": "^2.8.1", | ||
"ts-jest": "^29.1.0", | ||
"tsup": "6.5.0", | ||
"typescript": "4.9.4", | ||
"vitest": "^0.29.8" | ||
"typescript": "4.9.4" | ||
}, | ||
"lint-staged": { | ||
"**/*.{ts}": [ | ||
"prettier --write \"src/**/*.ts\"", | ||
"eslint \"src/**/*.ts\" --fix" | ||
] | ||
}, | ||
"simple-git-hooks": { | ||
"pre-commit": "npx lint-staged" | ||
} | ||
} |
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 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
5
0
468645
21
2989
+ Addedtopgun-webcrypto@^1.0.3
+ Addedtopgun-webcrypto@1.0.5(transitive)
- Removed@peculiar/webcrypto@^1.4.3