New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

topgun-socket

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

topgun-socket - npm Package Compare versions

Comparing version 1.2.1 to 1.2.2

dist/channel-2c868064.d.ts

2

dist/channel.js

@@ -1,1 +0,1 @@

var u=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var C=(n,e,t)=>e in n?u(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var S=(n,e)=>{for(var t in e)u(n,t,{get:e[t],enumerable:!0})},b=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of h(e))!c.call(n,s)&&s!==t&&u(n,s,{get:()=>e[s],enumerable:!(r=o(e,s))||r.enumerable});return n};var p=n=>b(u({},"__esModule",{value:!0}),n);var l=(n,e,t)=>(C(n,typeof e!="symbol"?e+"":e,t),t);var d={};S(d,{TGChannel:()=>i});module.exports=p(d);var m=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var a=class extends m{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,r,s){super(),this.PENDING=a.PENDING,this.SUBSCRIBED=a.SUBSCRIBED,this.UNSUBSCRIBED=a.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=r,this._dataStream=s.stream(this.name)}get state(){return this.client.getChannelState(this.name)}set state(e){throw new Error("Cannot directly set channel state")}get options(){return this.client.getChannelOptions(this.name)}set options(e){throw new Error("Cannot directly set channel options")}createConsumer(e){return this._dataStream.createConsumer(e)}listener(e){return this._eventDemux.stream(`${this.name}/${e}`)}close(){this.client.closeChannel(this.name)}kill(){this.client.killChannel(this.name)}killOutputConsumer(e){this.hasOutputConsumer(e)&&this.client.killChannelOutputConsumer(e)}killListenerConsumer(e){this.hasAnyListenerConsumer(e)&&this.client.killChannelListenerConsumer(e)}getOutputConsumerStats(e){if(this.hasOutputConsumer(e))return this.client.getChannelOutputConsumerStats(e)}getListenerConsumerStats(e){if(this.hasAnyListenerConsumer(e))return this.client.getChannelListenerConsumerStats(e)}getBackpressure(){return this.client.getChannelBackpressure(this.name)}getListenerConsumerBackpressure(e){return this.hasAnyListenerConsumer(e)?this.client.getChannelListenerConsumerBackpressure(e):0}getOutputConsumerBackpressure(e){return this.hasOutputConsumer(e)?this.client.getChannelOutputConsumerBackpressure(e):0}closeOutput(){this.client.channelCloseOutput(this.name)}closeListener(e){this.client.channelCloseListener(this.name,e)}closeAllListeners(){this.client.channelCloseAllListeners(this.name)}killOutput(){this.client.channelKillOutput(this.name)}killListener(e){this.client.channelKillListener(this.name,e)}killAllListeners(){this.client.channelKillAllListeners(this.name)}getOutputConsumerStatsList(){return this.client.channelGetOutputConsumerStatsList(this.name)}getListenerConsumerStatsList(e){return this.client.channelGetListenerConsumerStatsList(this.name,e)}getAllListenersConsumerStatsList(){return this.client.channelGetAllListenersConsumerStatsList(this.name)}getOutputBackpressure(){return this.client.channelGetOutputBackpressure(this.name)}getListenerBackpressure(e){return this.client.channelGetListenerBackpressure(this.name,e)}getAllListenersBackpressure(){return this.client.channelGetAllListenersBackpressure(this.name)}hasOutputConsumer(e){return this.client.channelHasOutputConsumer(this.name,e)}hasListenerConsumer(e,t){return this.client.channelHasListenerConsumer(this.name,e,t)}hasAnyListenerConsumer(e){return this.client.channelHasAnyListenerConsumer(this.name,e)}subscribe(e){this.client.subscribe(this.name,e)}unsubscribe(){this.client.unsubscribe(this.name)}isSubscribed(e){return this.client.isSubscribed(this.name,e)}transmitPublish(e){return this.client.transmitPublish(this.name,e)}invokePublish(e){return this.client.invokePublish(this.name,e)}},i=a;l(i,"PENDING","pending"),l(i,"SUBSCRIBED","subscribed"),l(i,"UNSUBSCRIBED","unsubscribed");0&&(module.exports={TGChannel});
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk6CUHH3QPjs = require('./chunk-6CUHH3QP.js');require('./chunk-L63Q7CFL.js');exports.TGChannel = _chunk6CUHH3QPjs.a;

@@ -1,1 +0,1 @@

var TopGunSocket=(()=>{var G=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var we=(r,e,t)=>e in r?G(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Oe=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},De=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xe(e))!Ae.call(r,s)&&s!==t&&G(r,s,{get:()=>e[s],enumerable:!(n=Ee(e,s))||n.enumerable});return r};var Be=r=>De(G({},"__esModule",{value:!0}),r);var h=(r,e,t)=>(we(r,typeof e!="symbol"?e+"":e,t),t);var yt={};Oe(yt,{AuthEngine:()=>H,TGClientSocket:()=>g,TGTransport:()=>w,create:()=>bt,version:()=>Te});function ae(r){let e=[],t=[];return function n(s,i){let o,u,a;if(typeof s=="object"&&s!==null&&!(s instanceof Boolean)&&!(s instanceof Date)&&!(s instanceof Number)&&!(s instanceof RegExp)&&!(s instanceof String)){for(o=0;o<e.length;o+=1)if(e[o]===s)return{$ref:t[o]};if(e.push(s),t.push(i),Object.prototype.toString.apply(s)==="[object Array]")for(a=[],o=0;o<s.length;o+=1)a[o]=n(s[o],i+"["+o+"]");else{a={};for(u in s)Object.prototype.hasOwnProperty.call(s,u)&&(a[u]=n(s[u],i+"["+JSON.stringify(u)+"]"))}return a}return s}(r,"$")}function I(){"use strict";return typeof function(){return this}()>"u"}var D=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,D.prototype),this.name="InvalidActionError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},b=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,b.prototype),this.name="InvalidArgumentsError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var B=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,B.prototype),this.name="InvalidMessageError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},P=class extends Error{code;constructor(e,t){super(e),Object.setPrototypeOf(this,P.prototype),this.name="SocketProtocolError",this.message=e,this.code=t,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var _=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_.prototype),this.name="TimeoutError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},E=class extends Error{type;constructor(e,t){super(e),Object.setPrototypeOf(this,E.prototype),this.name="BadConnectionError",this.message=e,this.type=t,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var N={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token",4005:"Did not receive #handshake from client before timeout",4006:"Failed to bind socket to message broker",4007:"Client connection establishment timed out",4008:"Server rejected handshake from client",4009:"Server received a message before the client handshake"},ue={1e3:"Socket closed normally",1001:"Socket hung up"},Pe={domain:1,domainEmitter:1,domainThrown:1};function ce(r,e){let t;if(r&&typeof r=="object"){t={message:r.message},e&&(t.stack=r.stack);for(let n in r)Pe[n]||(t[n]=r[n])}else typeof r=="function"?t="[function "+(r.name||"anonymous")+"]":t=r;return ae(t)}function R(r){let e=null;if(r!=null)if(typeof r=="object"){e=new Error(r.message);for(let t in r)r.hasOwnProperty(t)&&(e[t]=r[t])}else e=r;return e}function k(){return typeof WorkerGlobalScope<"u"?self:typeof window<"u"&&window||function(){return this}()}function le(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var C=[],y=[],Ie=typeof Uint8Array<"u"?Uint8Array:Array,Le=/[^+/0-9A-Za-z-_]/g,ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let r=0,e=ee.length;r<e;++r)C[r]=ee[r],y[ee.charCodeAt(r)]=r;y["-".charCodeAt(0)]=62;y["_".charCodeAt(0)]=63;function Ne(r){let e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let t=r.indexOf("=");t===-1&&(t=e);let n=t===e?0:4-t%4;return[t,n]}function Re(r,e,t){return(e+t)*3/4-t}function Ue(r){let e,t=Ne(r),n=t[0],s=t[1],i=new Ie(Re(r,n,s)),o=0,u=s>0?n-4:n,a;for(a=0;a<u;a+=4)e=y[r.charCodeAt(a)]<<18|y[r.charCodeAt(a+1)]<<12|y[r.charCodeAt(a+2)]<<6|y[r.charCodeAt(a+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=y[r.charCodeAt(a)]<<2|y[r.charCodeAt(a+1)]>>4,i[o++]=e&255),s===1&&(e=y[r.charCodeAt(a)]<<10|y[r.charCodeAt(a+1)]<<4|y[r.charCodeAt(a+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function He(r){return C[r>>18&63]+C[r>>12&63]+C[r>>6&63]+C[r&63]}function Ge(r,e,t){let n,s=[];for(let i=e;i<t;i+=3)n=(r[i]<<16&16711680)+(r[i+1]<<8&65280)+(r[i+2]&255),s.push(He(n));return s.join("")}function je(r){if(r=r.split("=")[0],r=r.trim().replace(Le,""),r.length<2)return"";for(;r.length%4!==0;)r=r+"=";return r}function de(r){return Ue(je(r))}function he(r){let e,t=r.length,n=t%3,s=[],i=16383;for(let o=0,u=t-n;o<u;o+=i)s.push(Ge(r,o,o+i>u?u:o+i));return n===1?(e=r[t-1],s.push(C[e>>2]+C[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],s.push(C[e>>10]+C[e>>4&63]+C[e<<2&63]+"=")),s.join("")}var te=2147483647;function Me(r,e,t){let n="";t=Math.min(r.length,t);for(let s=e;s<t;++s)n+=String.fromCharCode(r[s]&127);return n}function Ve(r,e,t){let n="";t=Math.min(r.length,t);for(let s=e;s<t;++s)n+=String.fromCharCode(r[s]);return n}function $e(r,e,t){return e===0&&t===r.length?he(r):he(r.slice(e,t))}function Fe(r,e,t){let n=r.slice(e,t),s="";for(let i=0;i<n.length-1;i+=2)s+=String.fromCharCode(n[i]+n[i+1]*256);return s}function ze(r,e,t,n){return j(de(e),r,t,n)}function We(r){let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t)&255);return e}function qe(r,e,t,n){return j(We(e),r,t,n)}function Ke(r,e,t,n){return j(se(e,r.length-t),r,t,n)}function j(r,e,t,n){let s;for(s=0;s<n&&!(s+t>=e.length||s>=r.length);++s)e[s+t]=r[s];return s}function Je(r,e,t,n){return j(Ze(e,r.length-t),r,t,n)}function Ze(r,e){let t,n,s,i=[];for(let o=0;o<r.length&&!((e-=2)<0);++o)t=r.charCodeAt(o),n=t>>8,s=t%256,i.push(s),i.push(n);return i}function Qe(r,e,t,n){t=Number(t)||0;let s=r.length-t;n?(n=Number(n),n>s&&(n=s)):n=s;let i=e.length;n>i/2&&(n=i/2);let o;for(o=0;o<n;++o){let u=parseInt(e.substr(o*2,2),16);if(fe(u))return o;r[t+o]=u}return o}function Xe(r){if(typeof r!="number")throw new TypeError('"size" argument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function Ye(r){if(d.isBuffer(r)){let e=pe(r.length)|0,t=x(e);return t.length===0||r.copy(t,0,0,e),t}if(r.length!==void 0)return typeof r.length!="number"||fe(r.length)?x(0):ne(r);if(r.type==="Buffer"&&Array.isArray(r.data))return ne(r.data)}function et(r,e){if((typeof e!="string"||e==="")&&(e="utf8"),!d.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=tt(r,e)|0,n=x(t),s=n.write(r,e);return s!==t&&(n=n.slice(0,s)),n}function tt(r,e){if(d.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||L(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&t===0)return 0;let s=!1;switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return se(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return de(r).length;default:if(s)return n?-1:se(r).length;e=(""+e).toLowerCase(),s=!0}}function ne(r){let e=r.length<0?0:pe(r.length)|0,t=x(e);for(let n=0;n<e;n+=1)t[n]=r[n]&255;return t}function pe(r){if(r>=te)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+te.toString(16)+" bytes");return r|0}function nt(r){if(L(r,Uint8Array)){let e=new Uint8Array(r);return re(e.buffer,e.byteOffset,e.byteLength)}return ne(r)}function re(r,e,t){if(e<0||r.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(r.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let n;return e===void 0&&t===void 0?n=new d(r):t===void 0?n=new d(r,e):n=new d(r,e,t),n}function se(r,e){e=e||1/0;let t,n=r.length,s=null,i=[];for(let o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!s){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&i.push(239,191,189);continue}s=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),s=t;continue}t=(s-55296<<10|t-56320)+65536}else s&&(e-=3)>-1&&i.push(239,191,189);if(s=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function x(r){if(r>te)throw new RangeError('The value "'+r+'" is invalid for option "size"');return new d(r)}function L(r,e){return r instanceof e||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===e.name}function fe(r){return r!==r}function rt(r,e,t){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(r||(r="utf8");;)switch(r){case"hex":return it(this,e,t);case"utf8":case"utf-8":return ge(this,e,t);case"ascii":return Me(this,e,t);case"latin1":case"binary":return Ve(this,e,t);case"base64":return $e(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Fe(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}var st=function(){let r="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let s=0;s<16;++s)e[n+s]=r[t]+r[s]}return e}();function it(r,e,t){let n=r.length;(!e||e<0)&&(e=0),(!t||t<0||t>n)&&(t=n);let s="";for(let i=e;i<t;++i)s+=st[r[i]];return s}function ge(r,e,t){t=Math.min(r.length,t);let n=[],s=e;for(;s<t;){let i=r[s],o=null,u=i>239?4:i>223?3:i>191?2:1;if(s+u<=t){let a,c,S,p;switch(u){case 1:i<128&&(o=i);break;case 2:a=r[s+1],(a&192)===128&&(p=(i&31)<<6|a&63,p>127&&(o=p));break;case 3:a=r[s+1],c=r[s+2],(a&192)===128&&(c&192)===128&&(p=(i&15)<<12|(a&63)<<6|c&63,p>2047&&(p<55296||p>57343)&&(o=p));break;case 4:a=r[s+1],c=r[s+2],S=r[s+3],(a&192)===128&&(c&192)===128&&(S&192)===128&&(p=(i&15)<<18|(a&63)<<12|(c&63)<<6|S&63,p>65535&&p<1114112&&(o=p))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),s+=u}return ot(n)}var me=4096;function ot(r){let e=r.length;if(e<=me)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=me));return t}var d=class extends Uint8Array{constructor(r,e,t){super(r,e,t),this._isBuffer=!0,this.poolSize=8192}static isEncoding(r){switch(String(r).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}}static isBuffer(r){return r!=null&&r._isBuffer===!0&&r!==d.prototype}static from(r,e,t){if(typeof r=="string")return et(r,e);if(ArrayBuffer.isView(r))return nt(r);if(r==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);if(L(r,ArrayBuffer)||r&&L(r.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(L(r,SharedArrayBuffer)||r&&L(r.buffer,SharedArrayBuffer)))return re(r,e,t);if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=r&&typeof r.valueOf=="function"&&r.valueOf();if(n!=null&&n!==r)return d.from(n,e,t);let s=Ye(r);if(s)return s;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function"){let i=r[Symbol.toPrimitive];return d.from(i("string"),e,t)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r)}static alloc(r,e,t){return Xe(r),r<=0?x(r):e!==void 0?typeof t=="string"?x(r).fill(e,t):x(r).fill(e):x(r)}write(r,e,t,n){if(e===void 0)n="utf8",t=this.length,e=0;else if(t===void 0&&typeof e=="string")n=e,t=this.length,e=0;else if(isFinite(e))e=e>>>0,isFinite(t)?(t=t>>>0,n===void 0&&(n="utf8")):(n=t,t=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-e;if((t===void 0||t>s)&&(t=s),r.length>0&&(t<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return Qe(this,r,e,t);case"utf8":case"utf-8":return Ke(this,r,e,t);case"ascii":case"latin1":case"binary":return qe(this,r,e,t);case"base64":return ze(this,r,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Je(this,r,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}}slice(r,e){let t=this.length;return r=~~r,e=e===void 0?t:~~e,r<0?(r+=t,r<0&&(r=0)):r>t&&(r=t),e<0?(e+=t,e<0&&(e=0)):e>t&&(e=t),e<r&&(e=r),d.from(this.subarray(r,e))}fill(r,e,t,n){if(typeof r=="string"){if(typeof e=="string"?(n=e,e=0,t=this.length):typeof t=="string"&&(n=t,t=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!d.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(r.length===1){let i=r.charCodeAt(0);(n==="utf8"&&i<128||n==="latin1")&&(r=i)}}else typeof r=="number"?r=r&255:typeof r=="boolean"&&(r=Number(r));if(e<0||this.length<e||this.length<t)throw new RangeError("Out of range index");if(t<=e)return this;e=e>>>0,t=t===void 0?this.length:t>>>0,r||(r=0);let s;if(typeof r=="number")for(s=e;s<t;++s)this[s]=r;else{let i=d.isBuffer(r)?r:d.from(r,n),o=i.length;if(o===0)throw new TypeError('The value "'+r+'" is invalid for argument "value"');for(s=0;s<t-e;++s)this[s+e]=i[s%o]}return this}copy(r,e,t,n){if(!d.isBuffer(r))throw new TypeError("argument should be a Buffer");if(t||(t=0),!n&&n!==0&&(n=this.length),e>=r.length&&(e=r.length),e||(e=0),n>0&&n<t&&(n=t),n===t||r.length===0||this.length===0)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(t<0||t>=this.length)throw new RangeError("Index out of range");if(n>=0){n>this.length&&(n=this.length),r.length-e<n-t&&(n=r.length-e+t);let s=n-t;return this===r&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(e,t,n):Uint8Array.prototype.set.call(r,this.subarray(t,n),e),s}else throw new RangeError("sourceEnd out of bounds")}toString(r,e,t){let n=this.length;return n===0?"":!r&&!e&&!t?ge(this,0,n):rt(r,e,t)}},at=class extends d{constructor(r,e,t){let n=d.from(r,e,t);super(n.length),n.copy(this)}},ie=at;var A=class{async next(e){let t=this.createConsumer(e),n=await t.next();return t.return(),n}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var M=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,n,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=n,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,n)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let o=ut(e);s=o.timeoutId,await o.promise,i.name="TimeoutError",delete this._resolve,n(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function ut(r){let e,t=new Promise(n=>{e=setTimeout(n,r)});return{timeoutId:e,promise:t}}var V=class extends A{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let n=this._consumers.get(e);!n||n.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let n=t.getBackpressure();n>e&&(e=n)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new M(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,n){let s={data:{value:e,done:t},next:null};n&&(s.consumerId=n),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};var $=class extends A{name;_streamDemux;constructor(e,t){super(),this.name=t,this._streamDemux=e}createConsumer(e){return this._streamDemux.createConsumer(this.name,e)}};var v=class{_mainStream;constructor(){this._mainStream=new V}write(e,t){this._mainStream.write({stream:e,data:{value:t,done:!1}})}close(e,t){this._mainStream.write({stream:e,data:{value:t,done:!0}})}closeAll(e){this._mainStream.close(e)}writeToConsumer(e,t){this._mainStream.writeToConsumer(e,{consumerId:e,data:{value:t,done:!1}})}closeConsumer(e,t){this._mainStream.closeConsumer(e,{consumerId:e,data:{value:t,done:!0}})}getConsumerStats(e){return this._mainStream.getConsumerStats(e)}getConsumerStatsList(e){return this._mainStream.getConsumerStatsList().filter(n=>n.stream===e)}getConsumerStatsListAll(){return this._mainStream.getConsumerStatsList()}kill(e,t){let n=this.getConsumerStatsList(e),s=n.length;for(let i=0;i<s;i++)this.killConsumer(n[i].id,t)}killAll(e){this._mainStream.kill(e)}killConsumer(e,t){this._mainStream.killConsumer(e,t)}getBackpressure(e){let t=this.getConsumerStatsList(e),n=t.length,s=0;for(let i=0;i<n;i++){let o=t[i];o.backpressure>s&&(s=o.backpressure)}return s}getBackpressureAll(){return this._mainStream.getBackpressure()}getConsumerBackpressure(e){return this._mainStream.getConsumerBackpressure(e)}hasConsumer(e,t){let n=this._mainStream.getConsumerStats(t);return!!n&&n.stream===e}hasConsumerAll(e){return this._mainStream.hasConsumer(e)}getConsumerCount(e){return this.getConsumerStatsList(e).length}getConsumerCountAll(){return this.getConsumerStatsListAll().length}createConsumer(e,t){let n=this._mainStream.createConsumer(t),s=n.next;n.next=async function(){for(;;){let a=arguments,c=await s.apply(this,a);if(c.value&&(c.value.stream===e||c.value.consumerId===this.id))return c.value.data.done&&this.return(),c.value.data;if(c.done)return c}};let i=n.getStats;n.getStats=function(){let a=arguments,c=i.apply(this,a);return c.stream=e,c};let o=n.applyBackpressure;n.applyBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){o.apply(this,c);return}a.done&&o.apply(this,c)};let u=n.releaseBackpressure;return n.releaseBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){u.apply(this,c);return}a.done&&u.apply(this,c)},n}stream(e){return new $(this,e)}};var F=class{_listenerDemux;constructor(){this._listenerDemux=new v}emit(e,t){this._listenerDemux.write(e,t)}listener(e){return this._listenerDemux.stream(e)}closeListener(e){this._listenerDemux.close(e)}closeAllListeners(){this._listenerDemux.closeAll()}getListenerConsumerStats(e){return this._listenerDemux.getConsumerStats(e)}getListenerConsumerStatsList(e){return this._listenerDemux.getConsumerStatsList(e)}getAllListenersConsumerStatsList(){return this._listenerDemux.getConsumerStatsListAll()}getListenerConsumerCount(e){return this._listenerDemux.getConsumerCount(e)}getAllListenersConsumerCount(){return this._listenerDemux.getConsumerCountAll()}killListener(e){this._listenerDemux.kill(e)}killAllListeners(){this._listenerDemux.killAll()}killListenerConsumer(e){this._listenerDemux.killConsumer(e)}getListenerBackpressure(e){return this._listenerDemux.getBackpressure(e)}getAllListenersBackpressure(){return this._listenerDemux.getBackpressureAll()}getListenerConsumerBackpressure(e){return this._listenerDemux.getConsumerBackpressure(e)}hasListenerConsumer(e,t){return this._listenerDemux.hasConsumer(e,t)}hasAnyListenerConsumer(e){return this._listenerDemux.hasConsumerAll(e)}};var U=class extends A{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,n,s){super(),this.PENDING=U.PENDING,this.SUBSCRIBED=U.SUBSCRIBED,this.UNSUBSCRIBED=U.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=n,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)}},m=U;h(m,"PENDING","pending"),h(m,"SUBSCRIBED","subscribed"),h(m,"UNSUBSCRIBED","unsubscribed");var z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ct=/^[ \n\r\t]*[{\[]/,O=k(),lt=function(r){let e=new Uint8Array(r),t=e.length,n="";for(let s=0;s<t;s+=3)n+=z[e[s]>>2],n+=z[(e[s]&3)<<4|e[s+1]>>4],n+=z[(e[s+1]&15)<<2|e[s+2]>>6],n+=z[e[s+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},ht=function(r,e){if(O.ArrayBuffer&&e instanceof O.ArrayBuffer)return{base64:!0,data:lt(e)};if(O.Buffer){if(e instanceof O.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&e.type==="Buffer"&&Array.isArray(e.data)){let t;return O.Buffer.from?t=O.Buffer.from(e.data):t=new O.Buffer(e.data),{base64:!0,data:t.toString("base64")}}}return e};function mt(r){if(r==null)return null;if(r==="#1"||r==="#2")return r;let e=r.toString();if(!ct.test(e))return e;try{return JSON.parse(e)}catch{}return e}function dt(r){return r==="#1"||r==="#2"?r:JSON.stringify(r,ht)}var be={encode:dt,decode:mt};function W(r,e){if(!e)return r;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)r.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];r.append(n)}}return r}var q=class{next;prev;list;constructor(){this.next=null,this.prev=null,this.list=null}append(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!t||this===e?!1:(e.detach(),this.next&&(e.next=this.next,this.next.prev=e),e.prev=this,e.list=t,this.next=e,(this===t.tail||!t.tail)&&(t.tail=e),t.size++,e)}prepend(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!t||this===e?!1:(e.detach(),this.prev&&(e.prev=this.prev,this.prev.next=e),e.next=this,e.list=t,this.prev=e,this===t.head&&(t.head=e),t.tail||(t.tail=this),t.size++,e)}detach(){let e=this.list;return e?(e.tail===this&&(e.tail=this.prev),e.head===this&&(e.head=this.next),e.tail===e.head&&(e.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,e.size--,this):this}};var K=class{item=null;constructor(e){this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}};var J=class{size;head;tail;static from(e){let t=new this;return W(t,e)}static of(...e){let t=new this;return W(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,W(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 K(this.head)}};function ye(r){return Object.prototype.toString.call(r)==="[object Date]"}function ke(r){return!!r&&typeof r=="object"&&Object.prototype.toString.call(r)!=="[object Array]"}function Z(r){if(ye(r))return new Date(r.getTime());if(Array.isArray(r))return[...r].map(e=>Z(e));if(r instanceof Map||r instanceof Set)return r;if(ke(r)){let e={};for(let t of Object.keys(r))e[t]=Z(r[t]);return e}return r}function Q(r=0){return new Promise(e=>{setTimeout(()=>e(),r)})}var T=k(),H=class{_internalStorage;isLocalStorageEnabled;constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&T.localStorage?T.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&T.localStorage?T.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&T.localStorage?t=T.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{T.localStorage,T.localStorage.setItem("__scLocalStorageTest",1),T.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var X=class{id;socket;procedure;data;sent;constructor(e,t,n,s){this.socket=e,this.id=t,this.procedure=n,this.data=s,this.sent=!1}end(e,t){let n={rid:this.id};e!==void 0&&(n.data=e),this._respond(n,t)}error(e,t){let n={rid:this.id,error:ce(e)};this._respond(n,t)}_respond(e,t){if(this.sent)throw new D(`Response to request ${this.id} has already been sent`);this.sent=!0,this.socket.sendObject(e,t)}};function Ce(r){return typeof r=="function"}function Se(r,e){let t=k();if(t&&Ce(t.WebSocket))return new t.WebSocket(r);throw Error("WebSocket instance not found")}var f=class{state;auth;codec;options;wsOptions;protocolVersion;connectTimeout;pingTimeout;pingTimeoutDisabled;callIdGenerator;authTokenName;isBufferingBatch;socket;_pingTimeoutTicker;_callbackMap;_batchBuffer;_onOpenHandler;_onOpenAbortHandler;_onCloseHandler;_onEventHandler;_onErrorHandler;_onInboundInvokeHandler;_onInboundTransmitHandler;_connectTimeoutRef;_handlePing;constructor(e,t,n,s,i){this.state=f.CLOSED,this.auth=e,this.codec=t,this.options=n,this.wsOptions=s,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],i||(i={}),this._onOpenHandler=i.onOpen||function(){},this._onOpenAbortHandler=i.onOpenAbort||function(){},this._onCloseHandler=i.onClose||function(){},this._onEventHandler=i.onEvent||function(){},this._onErrorHandler=i.onError||function(){},this._onInboundInvokeHandler=i.onInboundInvoke||function(){},this._onInboundTransmitHandler=i.onInboundTransmit||function(){},this.state=f.CONNECTING;let o=this.uri(),u=Se(o,s);u.binaryType=this.options.binaryType,this.socket=u,u.onopen=()=>{this._onOpen()},u.onclose=async a=>{let c;a.code==null?c=1005:c=a.code,this._destroy(c,a.reason)},u.onmessage=(a,c)=>{this._onMessage(a.data)},u.onerror=()=>{this.state===f.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=a=>a==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=a=>a===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let e=this.options.query||{},t;this.options.protocolScheme==null?t=this.options.secure?"wss":"ws":t=this.options.protocolScheme,this.options.timestampRequests&&(e[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[o,u]of Object.entries(e))if(Array.isArray(u))for(let a of u)n.append(o,a);else n.set(o,`${u}`);e=n.toString(),e.length&&(e="?"+e);let s,i;if(this.options.socketPath==null){if(this.options.host)s=this.options.host;else{let o="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="ws"&&this.options.port!==80)&&(o=":"+this.options.port),s=this.options.hostname+o}i=this.options.path}else s=this.options.socketPath,i=`:${this.options.path}`;return t+"://"+s+i+e}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let e=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(e)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(e,t){(this.state===f.OPEN||this.state===f.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 s={event:e,data:t};return(this.state===f.OPEN||n.force)&&this.transmitObject(s),Promise.resolve()}invokeRaw(e,t,n,s){let i={event:e,data:t,callback:s};n.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let o=null;return(this.state===f.OPEN||n.force)&&(o=this.transmitObject(i)),o}invoke(e,t,n){return new Promise((s,i)=>{this.invokeRaw(e,t,n,(o,u)=>{if(o){i(o);return}s(u)})})}cancelPendingResponse(e){delete this._callbackMap[e]}decode(e){return this.codec.decode(e)}encode(e){return this.codec.encode(e)}send(e){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(e)}serializeObject(e){let t;try{t=this.encode(e)}catch(n){return this._onError(n),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}_handleEventAckTimeout(e){e.cid&&delete this._callbackMap[e.cid],delete e.timeout;let t=e.callback;if(t){delete e.callback;let n=new _(`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=f.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=R(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 s=`Event "${n.event}" was aborted due to a bad connection`,i=new E(s,e),o=n.callback;o&&(delete n.callback,o.call(n,i,n))})}_destroy(e,t){!t&&N[e]&&(t=N[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===f.OPEN?(this.state=f.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===f.CONNECTING?(this.state=f.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===f.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new X(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 s=R(e.error);n.callback(s,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 s=0;s<n;s++)this._processInboundPacket(t[s],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},w=f;h(w,"CONNECTING","connecting"),h(w,"OPEN","open"),h(w,"CLOSED","closed");var pt=typeof window<"u",Y=k(),l=class extends F{options;id;clientId;version;protocolVersion;state;authState;signedAuthToken;authToken;authTokenName;wsOptions;pendingReconnect;pendingReconnectTimeout;preparingPendingSubscriptions;ackTimeout;connectTimeout;pingTimeout;pingTimeoutDisabled;channelPrefix;disconnectOnUnload;connectAttempts;isBatching;batchOnHandshake;batchOnHandshakeDuration;auth;codec;transport;poolIndex;_batchingIntervalId;_outboundBuffer;_channelMap;_channelEventDemux;_channelDataDemux;_receiverDemux;_procedureDemux;_cid;_reconnectTimeoutRef;_privateDataHandlerMap={"#publish":e=>{let t=this._undecorateChannelName(e.channel);this.isSubscribed(t,!0)&&this._channelDataDemux.write(t,e.data)},"#kickOut":e=>{let t=this._undecorateChannelName(e.channel),n=this._channelMap[t];n&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};_privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new B("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};constructor(e){super();let n=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},e);this.id=null,this.version=n.version||null,this.protocolVersion=n.protocolVersion,this.state=l.CLOSED,this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let s=Math.pow(2,31)-1,i=o=>{if(this[o]>s)throw new b(`The ${o} value provided exceeded the maximum amount allowed`)};if(i("connectTimeout"),i("ackTimeout"),i("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new J,this._channelMap={},this._channelEventDemux=new v,this._channelDataDemux=new v,this._receiverDemux=new v,this._procedureDemux=new v,this.options=n,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let o=this.options.autoReconnectOptions;o.initialDelay==null&&(o.initialDelay=1e4),o.randomness==null&&(o.randomness=1e4),o.multiplier==null&&(o.multiplier=1.5),o.maxDelay==null&&(o.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new H,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=be,this.options.protocol){let o=new b('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=n.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),u={};o.forEach((a,c)=>{let S=u[c];S==null?u[c]=a:(Array.isArray(S)||(u[c]=[S]),u[c].push(a))}),this.options.query=u}pt&&this.disconnectOnUnload&&Y.addEventListener&&Y.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this.state!==l.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await Q(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 w(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 b("If specified, the code argument must be a number");let n=this.state===l.CONNECTING;n||this.state===l.OPEN?(this.state=l.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return ie.from(e,"base64").toString("utf8")}encodeBase64(e){return ie.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 Q(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=R(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 Q(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],s={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(s.priority=t.priority),t.data!==void 0&&(s.data=t.data),n?t&&(n.options=s):(n={name:e,state:m.PENDING,options:s},this._channelMap[e]=n,this._trySubscribe(n)),new m(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&(this._triggerChannelUnsubscribe(t),this._tryUnsubscribe(t))}receiver(e){return this._receiverDemux.stream(e)}closeReceiver(e){this._receiverDemux.close(e)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(e){this._receiverDemux.kill(e)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(e){this._receiverDemux.killConsumer(e)}getReceiverConsumerStats(e){return this._receiverDemux.getConsumerStats(e)}getReceiverConsumerStatsList(e){return this._receiverDemux.getConsumerStatsList(e)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(e){return this._receiverDemux.getBackpressure(e)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(e){return this._receiverDemux.getConsumerBackpressure(e)}hasReceiverConsumer(e,t){return this._receiverDemux.hasConsumer(e,t)}hasAnyReceiverConsumer(e){return this._receiverDemux.hasConsumerAll(e)}procedure(e){return this._procedureDemux.stream(e)}closeProcedure(e){this._procedureDemux.close(e)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(e){this._procedureDemux.kill(e)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(e){this._procedureDemux.killConsumer(e)}getProcedureConsumerStats(e){return this._procedureDemux.getConsumerStats(e)}getProcedureConsumerStatsList(e){return this._procedureDemux.getConsumerStatsList(e)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(e){return this._procedureDemux.getBackpressure(e)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(e){return this._procedureDemux.getConsumerBackpressure(e)}hasProcedureConsumer(e,t){return this._procedureDemux.hasConsumer(e,t)}hasAnyProcedureConsumer(e){return this._procedureDemux.hasConsumerAll(e)}channel(e){return new m(e,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(e){this.channelCloseOutput(e),this.channelCloseAllListeners(e)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(e){this.channelKillOutput(e),this.channelKillAllListeners(e)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(e){this._channelDataDemux.killConsumer(e)}killChannelListenerConsumer(e){this._channelEventDemux.killConsumer(e)}getChannelOutputConsumerStats(e){return this._channelDataDemux.getConsumerStats(e)}getChannelListenerConsumerStats(e){return this._channelEventDemux.getConsumerStats(e)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(e){return Math.max(this.channelGetOutputBackpressure(e),this.channelGetAllListenersBackpressure(e))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(e){return this._channelEventDemux.getConsumerBackpressure(e)}getChannelOutputConsumerBackpressure(e){return this._channelDataDemux.getConsumerBackpressure(e)}hasAnyChannelOutputConsumer(e){return this._channelDataDemux.hasConsumerAll(e)}hasAnyChannelListenerConsumer(e){return this._channelEventDemux.hasConsumerAll(e)}getChannelState(e){let t=this._channelMap[e];return t?t.state:m.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?{...t.options}:{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.close(t)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.kill(t)})}channelGetOutputConsumerStatsList(e){return this._channelDataDemux.getConsumerStatsList(e)}channelGetListenerConsumerStatsList(e,t){return this._channelEventDemux.getConsumerStatsList(`${e}/${t}`)}channelGetAllListenersConsumerStatsList(e){return this._getAllChannelStreamNames(e).map(t=>this._channelEventDemux.getConsumerStatsList(t)).reduce((t,n)=>(n.forEach(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(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,n){return this._channelEventDemux.hasConsumer(`${e}/${t}`,n)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(n=>this._channelEventDemux.hasConsumer(n,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(n=>{(e||this._channelMap[n].state===m.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===m.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===m.PENDING&&e.push(n)}),e.sort((t,n)=>{let s=t.options.priority||0,i=n.options.priority||0;return s>i?-1:s<i?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,s)=>(n[s.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===l.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let n=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",n,t)}}_triggerChannelUnsubscribe(e,t){let n=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===m.SUBSCRIBED){let s={oldChannelState:e.state,newChannelState:t?m.PENDING:m.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,s),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...s}),this.emit("unsubscribe",{channel:n})}t?e.state=m.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===l.AUTHENTICATED;if(this.state===l.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},s={};e.options.waitForAuth&&(n.waitForAuth=!0,s.waitForAuth=n.waitForAuth),e.options.data&&(s.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...s},n,i=>{if(i){if(i.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(i,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,n){let s=t.name,i=!t.options.waitForAuth||this.authState===l.AUTHENTICATED;!!this._channelMap[s]&&i&&(delete this._channelMap[s],this._channelEventDemux.write(`${s}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:s,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==m.SUBSCRIBED){let s=e.state;e.state=m.SUBSCRIBED;let i={oldChannelState:s,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,s){n=n||{},this.state===l.CLOSED&&this.connect();let i={event:e,data:null},o;s?o=new Promise((c,S)=>{i.callback=(p,_e)=>{if(p){S(p);return}c(_e)}}):o=Promise.resolve();let u=new q;this.options.cloneData?i.data=Z(t):i.data=t,u.data=i;let a=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i,u)},a),this._outboundBuffer.append(u),this.state===l.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let s=new _(`Event response for "${e.event}" timed out`);n.call(e,s,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,s=this._privateRPCHandlerMap[t];s?s.call(this,n,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let n=this._privateDataHandlerMap[e];n?n.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!l.ignoreStatuses[e]){let s;t?s="Socket connection closed with status code "+e+" and reason: "+t:s="Socket connection closed with status code "+e;let i=new P(l.errorStatuses[e]||s,e);this._onError(i)}this._abortAllPendingEventsDueToBadConnection(n?"connectAbort":"disconnect"),this.options.autoReconnect&&(e===4e3||e===4001||e===1005?this._tryReconnect(0):e!==1e3&&e<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(e){let t=this._outboundBuffer.head,n;for(;t;){n=t.next;let s=t.data;clearTimeout(s.timeout),delete s.timeout,t.detach(),t=n;let i=s.callback;if(i){delete s.callback;let o=`Event "${s.event}" was aborted due to a bad connection`,u=new E(o,e);i.call(s,u,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++,n=this.options.autoReconnectOptions,s;if(e==null||t>0){let i=Math.round(n.initialDelay+(n.randomness||0)*Math.random());s=Math.round(i*Math.pow(n.multiplier,t))}else s=e;s>n.maxDelay&&(s=n.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",{...e,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===l.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let s=n;try{return s=this.decodeBase64(s),JSON.parse(s)}catch{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 n={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==l.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let s={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",s),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,Y.addEventListener("beforeunload",e,!1))},s=()=>{t&&(t=!1,Y.removeEventListener("beforeunload",e,!1))};(async()=>{let i=this.listener("connecting").createConsumer();for(;!(await i.next()).done;)n()})(),(async()=>{let i=this.listener("close").createConsumer();for(;!(await i.next()).done;)s()})()}_setAuthToken(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this._changeToUnauthenticatedStateAndClearTokens()}},g=l;h(g,"CONNECTING","connecting"),h(g,"OPEN","open"),h(g,"CLOSED","closed"),h(g,"AUTHENTICATED","authenticated"),h(g,"UNAUTHENTICATED","unauthenticated"),h(g,"SUBSCRIBED","subscribed"),h(g,"PENDING","pending"),h(g,"UNSUBSCRIBED","unsubscribed"),h(g,"ignoreStatuses",ue),h(g,"errorStatuses",N);var oe=k();function ft(){return oe.location&&location.protocol==="https:"}function gt(r,e){let t=r.secure==null?e:r.secure;return r.port||(oe.location&&location.port?parseFloat(location.port):t?443:80)}function ve(r){if(r=r||{},r.host&&!r.host.match(/[^:]+:\d{2,5}/))throw new b('The host option should include both the hostname and the port number in the format "hostname:port"');if(r.host&&r.hostname)throw new b('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(r.host&&r.port)throw new b('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=ft(),t={clientId:le(),port:gt(r,e),hostname:oe.location&&location.hostname||"localhost",secure:e};return Object.assign(t,r),new g(t)}var Te="1.0.0";function bt(r){return ve({...r,version:Te})}return Be(yt);})();
var TopGunSocket=(()=>{var G=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var we=(r,e,t)=>e in r?G(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Oe=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},De=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xe(e))!Ae.call(r,s)&&s!==t&&G(r,s,{get:()=>e[s],enumerable:!(n=Ee(e,s))||n.enumerable});return r};var Be=r=>De(G({},"__esModule",{value:!0}),r);var h=(r,e,t)=>(we(r,typeof e!="symbol"?e+"":e,t),t);var yt={};Oe(yt,{AuthEngine:()=>H,TGClientSocket:()=>g,TGTransport:()=>w,create:()=>bt,version:()=>Te});function ae(r){let e=[],t=[];return function n(s,i){let o,u,a;if(typeof s=="object"&&s!==null&&!(s instanceof Boolean)&&!(s instanceof Date)&&!(s instanceof Number)&&!(s instanceof RegExp)&&!(s instanceof String)){for(o=0;o<e.length;o+=1)if(e[o]===s)return{$ref:t[o]};if(e.push(s),t.push(i),Object.prototype.toString.apply(s)==="[object Array]")for(a=[],o=0;o<s.length;o+=1)a[o]=n(s[o],i+"["+o+"]");else{a={};for(u in s)Object.prototype.hasOwnProperty.call(s,u)&&(a[u]=n(s[u],i+"["+JSON.stringify(u)+"]"))}return a}return s}(r,"$")}function I(){"use strict";return typeof function(){return this}()>"u"}var D=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,D.prototype),this.name="InvalidActionError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},b=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,b.prototype),this.name="InvalidArgumentsError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var B=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,B.prototype),this.name="InvalidMessageError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},P=class extends Error{code;constructor(e,t){super(e),Object.setPrototypeOf(this,P.prototype),this.name="SocketProtocolError",this.message=e,this.code=t,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var _=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_.prototype),this.name="TimeoutError",this.message=e,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},E=class extends Error{type;constructor(e,t){super(e),Object.setPrototypeOf(this,E.prototype),this.name="BadConnectionError",this.message=e,this.type=t,Error.captureStackTrace&&!I()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var N={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token",4005:"Did not receive #handshake from client before timeout",4006:"Failed to bind socket to message broker",4007:"Client connection establishment timed out",4008:"Server rejected handshake from client",4009:"Server received a message before the client handshake"},ue={1e3:"Socket closed normally",1001:"Socket hung up"},Pe={domain:1,domainEmitter:1,domainThrown:1};function ce(r,e){let t;if(r&&typeof r=="object"){t={message:r.message},e&&(t.stack=r.stack);for(let n in r)Pe[n]||(t[n]=r[n])}else typeof r=="function"?t="[function "+(r.name||"anonymous")+"]":t=r;return ae(t)}function R(r){let e=null;if(r!=null)if(typeof r=="object"){e=new Error(r.message);for(let t in r)r.hasOwnProperty(t)&&(e[t]=r[t])}else e=r;return e}function k(){return typeof WorkerGlobalScope<"u"?self:typeof window<"u"&&window||function(){return this}()}function le(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var C=[],y=[],Ie=typeof Uint8Array<"u"?Uint8Array:Array,Le=/[^+/0-9A-Za-z-_]/g,ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let r=0,e=ee.length;r<e;++r)C[r]=ee[r],y[ee.charCodeAt(r)]=r;y["-".charCodeAt(0)]=62;y["_".charCodeAt(0)]=63;function Ne(r){let e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");let t=r.indexOf("=");t===-1&&(t=e);let n=t===e?0:4-t%4;return[t,n]}function Re(r,e,t){return(e+t)*3/4-t}function Ue(r){let e,t=Ne(r),n=t[0],s=t[1],i=new Ie(Re(r,n,s)),o=0,u=s>0?n-4:n,a;for(a=0;a<u;a+=4)e=y[r.charCodeAt(a)]<<18|y[r.charCodeAt(a+1)]<<12|y[r.charCodeAt(a+2)]<<6|y[r.charCodeAt(a+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=y[r.charCodeAt(a)]<<2|y[r.charCodeAt(a+1)]>>4,i[o++]=e&255),s===1&&(e=y[r.charCodeAt(a)]<<10|y[r.charCodeAt(a+1)]<<4|y[r.charCodeAt(a+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function He(r){return C[r>>18&63]+C[r>>12&63]+C[r>>6&63]+C[r&63]}function Ge(r,e,t){let n,s=[];for(let i=e;i<t;i+=3)n=(r[i]<<16&16711680)+(r[i+1]<<8&65280)+(r[i+2]&255),s.push(He(n));return s.join("")}function je(r){if(r=r.split("=")[0],r=r.trim().replace(Le,""),r.length<2)return"";for(;r.length%4!==0;)r=r+"=";return r}function de(r){return Ue(je(r))}function he(r){let e,t=r.length,n=t%3,s=[],i=16383;for(let o=0,u=t-n;o<u;o+=i)s.push(Ge(r,o,o+i>u?u:o+i));return n===1?(e=r[t-1],s.push(C[e>>2]+C[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],s.push(C[e>>10]+C[e>>4&63]+C[e<<2&63]+"=")),s.join("")}var te=2147483647;function Me(r,e,t){let n="";t=Math.min(r.length,t);for(let s=e;s<t;++s)n+=String.fromCharCode(r[s]&127);return n}function Ve(r,e,t){let n="";t=Math.min(r.length,t);for(let s=e;s<t;++s)n+=String.fromCharCode(r[s]);return n}function $e(r,e,t){return e===0&&t===r.length?he(r):he(r.slice(e,t))}function Fe(r,e,t){let n=r.slice(e,t),s="";for(let i=0;i<n.length-1;i+=2)s+=String.fromCharCode(n[i]+n[i+1]*256);return s}function ze(r,e,t,n){return j(de(e),r,t,n)}function We(r){let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t)&255);return e}function qe(r,e,t,n){return j(We(e),r,t,n)}function Ke(r,e,t,n){return j(se(e,r.length-t),r,t,n)}function j(r,e,t,n){let s;for(s=0;s<n&&!(s+t>=e.length||s>=r.length);++s)e[s+t]=r[s];return s}function Je(r,e,t,n){return j(Ze(e,r.length-t),r,t,n)}function Ze(r,e){let t,n,s,i=[];for(let o=0;o<r.length&&!((e-=2)<0);++o)t=r.charCodeAt(o),n=t>>8,s=t%256,i.push(s),i.push(n);return i}function Qe(r,e,t,n){t=Number(t)||0;let s=r.length-t;n?(n=Number(n),n>s&&(n=s)):n=s;let i=e.length;n>i/2&&(n=i/2);let o;for(o=0;o<n;++o){let u=parseInt(e.substr(o*2,2),16);if(fe(u))return o;r[t+o]=u}return o}function Xe(r){if(typeof r!="number")throw new TypeError('"size" argument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function Ye(r){if(d.isBuffer(r)){let e=pe(r.length)|0,t=x(e);return t.length===0||r.copy(t,0,0,e),t}if(r.length!==void 0)return typeof r.length!="number"||fe(r.length)?x(0):ne(r);if(r.type==="Buffer"&&Array.isArray(r.data))return ne(r.data)}function et(r,e){if((typeof e!="string"||e==="")&&(e="utf8"),!d.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=tt(r,e)|0,n=x(t),s=n.write(r,e);return s!==t&&(n=n.slice(0,s)),n}function tt(r,e){if(d.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||L(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&t===0)return 0;let s=!1;switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return se(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return de(r).length;default:if(s)return n?-1:se(r).length;e=(""+e).toLowerCase(),s=!0}}function ne(r){let e=r.length<0?0:pe(r.length)|0,t=x(e);for(let n=0;n<e;n+=1)t[n]=r[n]&255;return t}function pe(r){if(r>=te)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+te.toString(16)+" bytes");return r|0}function nt(r){if(L(r,Uint8Array)){let e=new Uint8Array(r);return re(e.buffer,e.byteOffset,e.byteLength)}return ne(r)}function re(r,e,t){if(e<0||r.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(r.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let n;return e===void 0&&t===void 0?n=new d(r):t===void 0?n=new d(r,e):n=new d(r,e,t),n}function se(r,e){e=e||1/0;let t,n=r.length,s=null,i=[];for(let o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!s){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&i.push(239,191,189);continue}s=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),s=t;continue}t=(s-55296<<10|t-56320)+65536}else s&&(e-=3)>-1&&i.push(239,191,189);if(s=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function x(r){if(r>te)throw new RangeError('The value "'+r+'" is invalid for option "size"');return new d(r)}function L(r,e){return r instanceof e||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===e.name}function fe(r){return r!==r}function rt(r,e,t){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(r||(r="utf8");;)switch(r){case"hex":return it(this,e,t);case"utf8":case"utf-8":return ge(this,e,t);case"ascii":return Me(this,e,t);case"latin1":case"binary":return Ve(this,e,t);case"base64":return $e(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Fe(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}var st=function(){let r="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let s=0;s<16;++s)e[n+s]=r[t]+r[s]}return e}();function it(r,e,t){let n=r.length;(!e||e<0)&&(e=0),(!t||t<0||t>n)&&(t=n);let s="";for(let i=e;i<t;++i)s+=st[r[i]];return s}function ge(r,e,t){t=Math.min(r.length,t);let n=[],s=e;for(;s<t;){let i=r[s],o=null,u=i>239?4:i>223?3:i>191?2:1;if(s+u<=t){let a,c,S,p;switch(u){case 1:i<128&&(o=i);break;case 2:a=r[s+1],(a&192)===128&&(p=(i&31)<<6|a&63,p>127&&(o=p));break;case 3:a=r[s+1],c=r[s+2],(a&192)===128&&(c&192)===128&&(p=(i&15)<<12|(a&63)<<6|c&63,p>2047&&(p<55296||p>57343)&&(o=p));break;case 4:a=r[s+1],c=r[s+2],S=r[s+3],(a&192)===128&&(c&192)===128&&(S&192)===128&&(p=(i&15)<<18|(a&63)<<12|(c&63)<<6|S&63,p>65535&&p<1114112&&(o=p))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),s+=u}return ot(n)}var me=4096;function ot(r){let e=r.length;if(e<=me)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=me));return t}var d=class extends Uint8Array{_isBuffer=!0;poolSize=8192;constructor(r,e,t){super(r,e,t)}static isEncoding(r){switch(String(r).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}}static isBuffer(r){return r!=null&&r._isBuffer===!0&&r!==d.prototype}static from(r,e,t){if(typeof r=="string")return et(r,e);if(ArrayBuffer.isView(r))return nt(r);if(r==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);if(L(r,ArrayBuffer)||r&&L(r.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(L(r,SharedArrayBuffer)||r&&L(r.buffer,SharedArrayBuffer)))return re(r,e,t);if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=r&&typeof r.valueOf=="function"&&r.valueOf();if(n!=null&&n!==r)return d.from(n,e,t);let s=Ye(r);if(s)return s;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function"){let i=r[Symbol.toPrimitive];return d.from(i("string"),e,t)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r)}static alloc(r,e,t){return Xe(r),r<=0?x(r):e!==void 0?typeof t=="string"?x(r).fill(e,t):x(r).fill(e):x(r)}write(r,e,t,n){if(e===void 0)n="utf8",t=this.length,e=0;else if(t===void 0&&typeof e=="string")n=e,t=this.length,e=0;else if(isFinite(e))e=e>>>0,isFinite(t)?(t=t>>>0,n===void 0&&(n="utf8")):(n=t,t=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-e;if((t===void 0||t>s)&&(t=s),r.length>0&&(t<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return Qe(this,r,e,t);case"utf8":case"utf-8":return Ke(this,r,e,t);case"ascii":case"latin1":case"binary":return qe(this,r,e,t);case"base64":return ze(this,r,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Je(this,r,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}}slice(r,e){let t=this.length;return r=~~r,e=e===void 0?t:~~e,r<0?(r+=t,r<0&&(r=0)):r>t&&(r=t),e<0?(e+=t,e<0&&(e=0)):e>t&&(e=t),e<r&&(e=r),d.from(this.subarray(r,e))}fill(r,e,t,n){if(typeof r=="string"){if(typeof e=="string"?(n=e,e=0,t=this.length):typeof t=="string"&&(n=t,t=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!d.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(r.length===1){let i=r.charCodeAt(0);(n==="utf8"&&i<128||n==="latin1")&&(r=i)}}else typeof r=="number"?r=r&255:typeof r=="boolean"&&(r=Number(r));if(typeof e=="number"&&typeof t=="number"){if(e<0||this.length<e||this.length<t)throw new RangeError("Out of range index");if(t<=e)return this}e=e>>>0,t=t===void 0?this.length:t>>>0,r||(r=0);let s;if(typeof r=="number")for(s=e;s<t;++s)this[s]=r;else{let i=d.isBuffer(r)?r:d.from(r,n),o=i.length;if(o===0)throw new TypeError('The value "'+r+'" is invalid for argument "value"');for(s=0;s<t-e;++s)this[s+e]=i[s%o]}return this}copy(r,e,t,n){if(!d.isBuffer(r))throw new TypeError("argument should be a Buffer");if(t||(t=0),!n&&n!==0&&(n=this.length),typeof e=="number"&&e>=r.length&&(e=r.length),e||(e=0),n>0&&n<t&&(n=t),n===t||r.length===0||this.length===0)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(t<0||t>=this.length)throw new RangeError("Index out of range");if(n>=0){n>this.length&&(n=this.length),r.length-e<n-t&&(n=r.length-e+t);let s=n-t;return this===r&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(e,t,n):Uint8Array.prototype.set.call(r,this.subarray(t,n),e),s}else throw new RangeError("sourceEnd out of bounds")}toString(r,e,t){let n=this.length;return n===0?"":!r&&!e&&!t?ge(this,0,n):rt(r,e,t)}},at=class extends d{constructor(r,e,t){let n=d.from(r,e,t);super(n.length),n.copy(this)}},ie=at;var A=class{async next(e){let t=this.createConsumer(e),n=await t.next();return t.return(),n}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var M=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,n,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=n,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,n)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let o=ut(e);s=o.timeoutId,await o.promise,i.name="TimeoutError",delete this._resolve,n(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function ut(r){let e,t=new Promise(n=>{e=setTimeout(n,r)});return{timeoutId:e,promise:t}}var V=class extends A{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let n=this._consumers.get(e);!n||n.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let n=t.getBackpressure();n>e&&(e=n)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new M(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,n){let s={data:{value:e,done:t},next:null};n&&(s.consumerId=n),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};var $=class extends A{name;_streamDemux;constructor(e,t){super(),this.name=t,this._streamDemux=e}createConsumer(e){return this._streamDemux.createConsumer(this.name,e)}};var v=class{_mainStream;constructor(){this._mainStream=new V}write(e,t){this._mainStream.write({stream:e,data:{value:t,done:!1}})}close(e,t){this._mainStream.write({stream:e,data:{value:t,done:!0}})}closeAll(e){this._mainStream.close(e)}writeToConsumer(e,t){this._mainStream.writeToConsumer(e,{consumerId:e,data:{value:t,done:!1}})}closeConsumer(e,t){this._mainStream.closeConsumer(e,{consumerId:e,data:{value:t,done:!0}})}getConsumerStats(e){return this._mainStream.getConsumerStats(e)}getConsumerStatsList(e){return this._mainStream.getConsumerStatsList().filter(n=>n.stream===e)}getConsumerStatsListAll(){return this._mainStream.getConsumerStatsList()}kill(e,t){let n=this.getConsumerStatsList(e),s=n.length;for(let i=0;i<s;i++)this.killConsumer(n[i].id,t)}killAll(e){this._mainStream.kill(e)}killConsumer(e,t){this._mainStream.killConsumer(e,t)}getBackpressure(e){let t=this.getConsumerStatsList(e),n=t.length,s=0;for(let i=0;i<n;i++){let o=t[i];o.backpressure>s&&(s=o.backpressure)}return s}getBackpressureAll(){return this._mainStream.getBackpressure()}getConsumerBackpressure(e){return this._mainStream.getConsumerBackpressure(e)}hasConsumer(e,t){let n=this._mainStream.getConsumerStats(t);return!!n&&n.stream===e}hasConsumerAll(e){return this._mainStream.hasConsumer(e)}getConsumerCount(e){return this.getConsumerStatsList(e).length}getConsumerCountAll(){return this.getConsumerStatsListAll().length}createConsumer(e,t){let n=this._mainStream.createConsumer(t),s=n.next;n.next=async function(){for(;;){let a=arguments,c=await s.apply(this,a);if(c.value&&(c.value.stream===e||c.value.consumerId===this.id))return c.value.data.done&&this.return(),c.value.data;if(c.done)return c}};let i=n.getStats;n.getStats=function(){let a=arguments,c=i.apply(this,a);return c.stream=e,c};let o=n.applyBackpressure;n.applyBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){o.apply(this,c);return}a.done&&o.apply(this,c)};let u=n.releaseBackpressure;return n.releaseBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){u.apply(this,c);return}a.done&&u.apply(this,c)},n}stream(e){return new $(this,e)}};var F=class{_listenerDemux;constructor(){this._listenerDemux=new v}emit(e,t){this._listenerDemux.write(e,t)}listener(e){return this._listenerDemux.stream(e)}closeListener(e){this._listenerDemux.close(e)}closeAllListeners(){this._listenerDemux.closeAll()}getListenerConsumerStats(e){return this._listenerDemux.getConsumerStats(e)}getListenerConsumerStatsList(e){return this._listenerDemux.getConsumerStatsList(e)}getAllListenersConsumerStatsList(){return this._listenerDemux.getConsumerStatsListAll()}getListenerConsumerCount(e){return this._listenerDemux.getConsumerCount(e)}getAllListenersConsumerCount(){return this._listenerDemux.getConsumerCountAll()}killListener(e){this._listenerDemux.kill(e)}killAllListeners(){this._listenerDemux.killAll()}killListenerConsumer(e){this._listenerDemux.killConsumer(e)}getListenerBackpressure(e){return this._listenerDemux.getBackpressure(e)}getAllListenersBackpressure(){return this._listenerDemux.getBackpressureAll()}getListenerConsumerBackpressure(e){return this._listenerDemux.getConsumerBackpressure(e)}hasListenerConsumer(e,t){return this._listenerDemux.hasConsumer(e,t)}hasAnyListenerConsumer(e){return this._listenerDemux.hasConsumerAll(e)}};var U=class extends A{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,n,s){super(),this.PENDING=U.PENDING,this.SUBSCRIBED=U.SUBSCRIBED,this.UNSUBSCRIBED=U.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=n,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)}},m=U;h(m,"PENDING","pending"),h(m,"SUBSCRIBED","subscribed"),h(m,"UNSUBSCRIBED","unsubscribed");var z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ct=/^[ \n\r\t]*[{\[]/,O=k(),lt=function(r){let e=new Uint8Array(r),t=e.length,n="";for(let s=0;s<t;s+=3)n+=z[e[s]>>2],n+=z[(e[s]&3)<<4|e[s+1]>>4],n+=z[(e[s+1]&15)<<2|e[s+2]>>6],n+=z[e[s+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},ht=function(r,e){if(O.ArrayBuffer&&e instanceof O.ArrayBuffer)return{base64:!0,data:lt(e)};if(O.Buffer){if(e instanceof O.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&e.type==="Buffer"&&Array.isArray(e.data)){let t;return O.Buffer.from?t=O.Buffer.from(e.data):t=new O.Buffer(e.data),{base64:!0,data:t.toString("base64")}}}return e};function mt(r){if(r==null)return null;if(r==="#1"||r==="#2")return r;let e=r.toString();if(!ct.test(e))return e;try{return JSON.parse(e)}catch{}return e}function dt(r){return r==="#1"||r==="#2"?r:JSON.stringify(r,ht)}var be={encode:dt,decode:mt};function W(r,e){if(!e)return r;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)r.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];r.append(n)}}return r}var q=class{next;prev;list;constructor(){this.next=null,this.prev=null,this.list=null}append(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!t||this===e?!1:(e.detach(),this.next&&(e.next=this.next,this.next.prev=e),e.prev=this,e.list=t,this.next=e,(this===t.tail||!t.tail)&&(t.tail=e),t.size++,e)}prepend(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!t||this===e?!1:(e.detach(),this.prev&&(e.prev=this.prev,this.prev.next=e),e.next=this,e.list=t,this.prev=e,this===t.head&&(t.head=e),t.tail||(t.tail=this),t.size++,e)}detach(){let e=this.list;return e?(e.tail===this&&(e.tail=this.prev),e.head===this&&(e.head=this.next),e.tail===e.head&&(e.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,e.size--,this):this}};var K=class{item=null;constructor(e){this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}};var J=class{size;head;tail;static from(e){let t=new this;return W(t,e)}static of(...e){let t=new this;return W(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,W(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 K(this.head)}};function ye(r){return Object.prototype.toString.call(r)==="[object Date]"}function ke(r){return!!r&&typeof r=="object"&&Object.prototype.toString.call(r)!=="[object Array]"}function Z(r){if(ye(r))return new Date(r.getTime());if(Array.isArray(r))return[...r].map(e=>Z(e));if(r instanceof Map||r instanceof Set)return r;if(ke(r)){let e={};for(let t of Object.keys(r))e[t]=Z(r[t]);return e}return r}function Q(r=0){return new Promise(e=>{setTimeout(()=>e(),r)})}var T=k(),H=class{_internalStorage;isLocalStorageEnabled;constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&T.localStorage?T.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&T.localStorage?T.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&T.localStorage?t=T.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{T.localStorage,T.localStorage.setItem("__scLocalStorageTest",1),T.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var X=class{id;socket;procedure;data;sent;constructor(e,t,n,s){this.socket=e,this.id=t,this.procedure=n,this.data=s,this.sent=!1}end(e,t){let n={rid:this.id};e!==void 0&&(n.data=e),this._respond(n,t)}error(e,t){let n={rid:this.id,error:ce(e)};this._respond(n,t)}_respond(e,t){if(this.sent)throw new D(`Response to request ${this.id} has already been sent`);this.sent=!0,this.socket.sendObject(e,t)}};function Ce(r){return typeof r=="function"}function Se(r,e){let t=k();if(t&&Ce(t.WebSocket))return new t.WebSocket(r);throw Error("WebSocket instance not found")}var f=class{state;auth;codec;options;wsOptions;protocolVersion;connectTimeout;pingTimeout;pingTimeoutDisabled;callIdGenerator;authTokenName;isBufferingBatch;socket;_pingTimeoutTicker;_callbackMap;_batchBuffer;_onOpenHandler;_onOpenAbortHandler;_onCloseHandler;_onEventHandler;_onErrorHandler;_onInboundInvokeHandler;_onInboundTransmitHandler;_connectTimeoutRef;_handlePing;constructor(e,t,n,s,i){this.state=f.CLOSED,this.auth=e,this.codec=t,this.options=n,this.wsOptions=s,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],i||(i={}),this._onOpenHandler=i.onOpen||function(){},this._onOpenAbortHandler=i.onOpenAbort||function(){},this._onCloseHandler=i.onClose||function(){},this._onEventHandler=i.onEvent||function(){},this._onErrorHandler=i.onError||function(){},this._onInboundInvokeHandler=i.onInboundInvoke||function(){},this._onInboundTransmitHandler=i.onInboundTransmit||function(){},this.state=f.CONNECTING;let o=this.uri(),u=Se(o,s);u.binaryType=this.options.binaryType,this.socket=u,u.onopen=()=>{this._onOpen()},u.onclose=async a=>{let c;a.code==null?c=1005:c=a.code,this._destroy(c,a.reason)},u.onmessage=(a,c)=>{this._onMessage(a.data)},u.onerror=()=>{this.state===f.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=a=>a==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=a=>a===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let e=this.options.query||{},t;this.options.protocolScheme==null?t=this.options.secure?"wss":"ws":t=this.options.protocolScheme,this.options.timestampRequests&&(e[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[o,u]of Object.entries(e))if(Array.isArray(u))for(let a of u)n.append(o,a);else n.set(o,`${u}`);e=n.toString(),e.length&&(e="?"+e);let s,i;if(this.options.socketPath==null){if(this.options.host)s=this.options.host;else{let o="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="ws"&&this.options.port!==80)&&(o=":"+this.options.port),s=this.options.hostname+o}i=this.options.path}else s=this.options.socketPath,i=`:${this.options.path}`;return t+"://"+s+i+e}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let e=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(e)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(e,t){(this.state===f.OPEN||this.state===f.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 s={event:e,data:t};return(this.state===f.OPEN||n.force)&&this.transmitObject(s),Promise.resolve()}invokeRaw(e,t,n,s){let i={event:e,data:t,callback:s};n.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let o=null;return(this.state===f.OPEN||n.force)&&(o=this.transmitObject(i)),o}invoke(e,t,n){return new Promise((s,i)=>{this.invokeRaw(e,t,n,(o,u)=>{if(o){i(o);return}s(u)})})}cancelPendingResponse(e){delete this._callbackMap[e]}decode(e){return this.codec.decode(e)}encode(e){return this.codec.encode(e)}send(e){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(e)}serializeObject(e){let t;try{t=this.encode(e)}catch(n){return this._onError(n),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}_handleEventAckTimeout(e){e.cid&&delete this._callbackMap[e.cid],delete e.timeout;let t=e.callback;if(t){delete e.callback;let n=new _(`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=f.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=R(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 s=`Event "${n.event}" was aborted due to a bad connection`,i=new E(s,e),o=n.callback;o&&(delete n.callback,o.call(n,i,n))})}_destroy(e,t){!t&&N[e]&&(t=N[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===f.OPEN?(this.state=f.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===f.CONNECTING?(this.state=f.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===f.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new X(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 s=R(e.error);n.callback(s,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 s=0;s<n;s++)this._processInboundPacket(t[s],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},w=f;h(w,"CONNECTING","connecting"),h(w,"OPEN","open"),h(w,"CLOSED","closed");var pt=typeof window<"u",Y=k(),l=class extends F{options;id;clientId;version;protocolVersion;state;authState;signedAuthToken;authToken;authTokenName;wsOptions;pendingReconnect;pendingReconnectTimeout;preparingPendingSubscriptions;ackTimeout;connectTimeout;pingTimeout;pingTimeoutDisabled;channelPrefix;disconnectOnUnload;connectAttempts;isBatching;batchOnHandshake;batchOnHandshakeDuration;auth;codec;transport;poolIndex;_batchingIntervalId;_outboundBuffer;_channelMap;_channelEventDemux;_channelDataDemux;_receiverDemux;_procedureDemux;_cid;_reconnectTimeoutRef;_privateDataHandlerMap={"#publish":e=>{let t=this._undecorateChannelName(e.channel);this.isSubscribed(t,!0)&&this._channelDataDemux.write(t,e.data)},"#kickOut":e=>{let t=this._undecorateChannelName(e.channel),n=this._channelMap[t];n&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};_privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new B("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};constructor(e){super();let n=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},e);this.id=null,this.version=n.version||null,this.protocolVersion=n.protocolVersion,this.state=l.CLOSED,this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let s=Math.pow(2,31)-1,i=o=>{if(this[o]>s)throw new b(`The ${o} value provided exceeded the maximum amount allowed`)};if(i("connectTimeout"),i("ackTimeout"),i("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new J,this._channelMap={},this._channelEventDemux=new v,this._channelDataDemux=new v,this._receiverDemux=new v,this._procedureDemux=new v,this.options=n,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let o=this.options.autoReconnectOptions;o.initialDelay==null&&(o.initialDelay=1e4),o.randomness==null&&(o.randomness=1e4),o.multiplier==null&&(o.multiplier=1.5),o.maxDelay==null&&(o.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new H,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=be,this.options.protocol){let o=new b('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=n.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),u={};o.forEach((a,c)=>{let S=u[c];S==null?u[c]=a:(Array.isArray(S)||(u[c]=[S]),u[c].push(a))}),this.options.query=u}pt&&this.disconnectOnUnload&&Y.addEventListener&&Y.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this.state!==l.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await Q(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 w(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 b("If specified, the code argument must be a number");let n=this.state===l.CONNECTING;n||this.state===l.OPEN?(this.state=l.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return ie.from(e,"base64").toString("utf8")}encodeBase64(e){return ie.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 Q(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=R(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 Q(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],s={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(s.priority=t.priority),t.data!==void 0&&(s.data=t.data),n?t&&(n.options=s):(n={name:e,state:m.PENDING,options:s},this._channelMap[e]=n,this._trySubscribe(n)),new m(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&(this._triggerChannelUnsubscribe(t),this._tryUnsubscribe(t))}receiver(e){return this._receiverDemux.stream(e)}closeReceiver(e){this._receiverDemux.close(e)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(e){this._receiverDemux.kill(e)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(e){this._receiverDemux.killConsumer(e)}getReceiverConsumerStats(e){return this._receiverDemux.getConsumerStats(e)}getReceiverConsumerStatsList(e){return this._receiverDemux.getConsumerStatsList(e)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(e){return this._receiverDemux.getBackpressure(e)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(e){return this._receiverDemux.getConsumerBackpressure(e)}hasReceiverConsumer(e,t){return this._receiverDemux.hasConsumer(e,t)}hasAnyReceiverConsumer(e){return this._receiverDemux.hasConsumerAll(e)}procedure(e){return this._procedureDemux.stream(e)}closeProcedure(e){this._procedureDemux.close(e)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(e){this._procedureDemux.kill(e)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(e){this._procedureDemux.killConsumer(e)}getProcedureConsumerStats(e){return this._procedureDemux.getConsumerStats(e)}getProcedureConsumerStatsList(e){return this._procedureDemux.getConsumerStatsList(e)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(e){return this._procedureDemux.getBackpressure(e)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(e){return this._procedureDemux.getConsumerBackpressure(e)}hasProcedureConsumer(e,t){return this._procedureDemux.hasConsumer(e,t)}hasAnyProcedureConsumer(e){return this._procedureDemux.hasConsumerAll(e)}channel(e){return new m(e,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(e){this.channelCloseOutput(e),this.channelCloseAllListeners(e)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(e){this.channelKillOutput(e),this.channelKillAllListeners(e)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(e){this._channelDataDemux.killConsumer(e)}killChannelListenerConsumer(e){this._channelEventDemux.killConsumer(e)}getChannelOutputConsumerStats(e){return this._channelDataDemux.getConsumerStats(e)}getChannelListenerConsumerStats(e){return this._channelEventDemux.getConsumerStats(e)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(e){return Math.max(this.channelGetOutputBackpressure(e),this.channelGetAllListenersBackpressure(e))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(e){return this._channelEventDemux.getConsumerBackpressure(e)}getChannelOutputConsumerBackpressure(e){return this._channelDataDemux.getConsumerBackpressure(e)}hasAnyChannelOutputConsumer(e){return this._channelDataDemux.hasConsumerAll(e)}hasAnyChannelListenerConsumer(e){return this._channelEventDemux.hasConsumerAll(e)}getChannelState(e){let t=this._channelMap[e];return t?t.state:m.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?{...t.options}:{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.close(t)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.kill(t)})}channelGetOutputConsumerStatsList(e){return this._channelDataDemux.getConsumerStatsList(e)}channelGetListenerConsumerStatsList(e,t){return this._channelEventDemux.getConsumerStatsList(`${e}/${t}`)}channelGetAllListenersConsumerStatsList(e){return this._getAllChannelStreamNames(e).map(t=>this._channelEventDemux.getConsumerStatsList(t)).reduce((t,n)=>(n.forEach(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(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,n){return this._channelEventDemux.hasConsumer(`${e}/${t}`,n)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(n=>this._channelEventDemux.hasConsumer(n,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(n=>{(e||this._channelMap[n].state===m.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===m.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===m.PENDING&&e.push(n)}),e.sort((t,n)=>{let s=t.options.priority||0,i=n.options.priority||0;return s>i?-1:s<i?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,s)=>(n[s.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===l.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let n=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",n,t)}}_triggerChannelUnsubscribe(e,t){let n=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===m.SUBSCRIBED){let s={oldChannelState:e.state,newChannelState:t?m.PENDING:m.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,s),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...s}),this.emit("unsubscribe",{channel:n})}t?e.state=m.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===l.AUTHENTICATED;if(this.state===l.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},s={};e.options.waitForAuth&&(n.waitForAuth=!0,s.waitForAuth=n.waitForAuth),e.options.data&&(s.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...s},n,i=>{if(i){if(i.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(i,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,n){let s=t.name,i=!t.options.waitForAuth||this.authState===l.AUTHENTICATED;!!this._channelMap[s]&&i&&(delete this._channelMap[s],this._channelEventDemux.write(`${s}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:s,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==m.SUBSCRIBED){let s=e.state;e.state=m.SUBSCRIBED;let i={oldChannelState:s,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,s){n=n||{},this.state===l.CLOSED&&this.connect();let i={event:e,data:null},o;s?o=new Promise((c,S)=>{i.callback=(p,_e)=>{if(p){S(p);return}c(_e)}}):o=Promise.resolve();let u=new q;this.options.cloneData?i.data=Z(t):i.data=t,u.data=i;let a=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i,u)},a),this._outboundBuffer.append(u),this.state===l.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let s=new _(`Event response for "${e.event}" timed out`);n.call(e,s,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,s=this._privateRPCHandlerMap[t];s?s.call(this,n,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let n=this._privateDataHandlerMap[e];n?n.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!l.ignoreStatuses[e]){let s;t?s="Socket connection closed with status code "+e+" and reason: "+t:s="Socket connection closed with status code "+e;let i=new P(l.errorStatuses[e]||s,e);this._onError(i)}this._abortAllPendingEventsDueToBadConnection(n?"connectAbort":"disconnect"),this.options.autoReconnect&&(e===4e3||e===4001||e===1005?this._tryReconnect(0):e!==1e3&&e<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(e){let t=this._outboundBuffer.head,n;for(;t;){n=t.next;let s=t.data;clearTimeout(s.timeout),delete s.timeout,t.detach(),t=n;let i=s.callback;if(i){delete s.callback;let o=`Event "${s.event}" was aborted due to a bad connection`,u=new E(o,e);i.call(s,u,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++,n=this.options.autoReconnectOptions,s;if(e==null||t>0){let i=Math.round(n.initialDelay+(n.randomness||0)*Math.random());s=Math.round(i*Math.pow(n.multiplier,t))}else s=e;s>n.maxDelay&&(s=n.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",{...e,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===l.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let s=n;try{return s=this.decodeBase64(s),JSON.parse(s)}catch{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 n={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==l.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let s={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",s),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,Y.addEventListener("beforeunload",e,!1))},s=()=>{t&&(t=!1,Y.removeEventListener("beforeunload",e,!1))};(async()=>{let i=this.listener("connecting").createConsumer();for(;!(await i.next()).done;)n()})(),(async()=>{let i=this.listener("close").createConsumer();for(;!(await i.next()).done;)s()})()}_setAuthToken(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this._changeToUnauthenticatedStateAndClearTokens()}},g=l;h(g,"CONNECTING","connecting"),h(g,"OPEN","open"),h(g,"CLOSED","closed"),h(g,"AUTHENTICATED","authenticated"),h(g,"UNAUTHENTICATED","unauthenticated"),h(g,"SUBSCRIBED","subscribed"),h(g,"PENDING","pending"),h(g,"UNSUBSCRIBED","unsubscribed"),h(g,"ignoreStatuses",ue),h(g,"errorStatuses",N);var oe=k();function ft(){return oe.location&&location.protocol==="https:"}function gt(r,e){let t=r.secure==null?e:r.secure;return r.port||(oe.location&&location.port?parseFloat(location.port):t?443:80)}function ve(r){if(r=r||{},r.host&&!r.host.match(/[^:]+:\d{2,5}/))throw new b('The host option should include both the hostname and the port number in the format "hostname:port"');if(r.host&&r.hostname)throw new b('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(r.host&&r.port)throw new b('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=ft(),t={clientId:le(),port:gt(r,e),hostname:oe.location&&location.hostname||"localhost",secure:e};return Object.assign(t,r),new g(t)}var Te="1.0.0";function bt(r){return ve({...r,version:Te})}return Be(yt);})();

@@ -1,1 +0,1 @@

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

@@ -1,1 +0,1 @@

var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});module.exports=b(v);var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};0&&(module.exports={WritableConsumableStream});
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkZNIU5T3Xjs = require('./chunk-ZNIU5T3X.js');require('./chunk-L63Q7CFL.js');exports.WritableConsumableStream = _chunkZNIU5T3Xjs.a;
{
"name": "topgun-socket",
"version": "1.2.1",
"version": "1.2.2",
"description": "Scalable realtime pub/sub and RPC serverless framework",

@@ -85,4 +85,4 @@ "publishConfig": {

"dependencies": {
"topgun-buffer": "1.0.2",
"topgun-webcrypto": "1.0.4"
"topgun-buffer": "1.0.3",
"topgun-webcrypto": "1.0.5"
},

@@ -89,0 +89,0 @@ "devDependencies": {

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc