UNPKG

@brainfish-ai/web-tracker

Version:

Brainfish Tracker for Web

1 lines 374 kB
"use strict";var e=Object.defineProperty,t=(t,s,r)=>((t,s,r)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r)(t,"symbol"!=typeof s?s+"":s,r);const s=Object.create(null);s.open="0",s.close="1",s.ping="2",s.pong="3",s.message="4",s.upgrade="5",s.noop="6";const r=Object.create(null);Object.keys(s).forEach(e=>{r[s[e]]=e});const n={type:"error",data:"parser error"},i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,a=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,l=({type:e,data:t},r,n)=>i&&t instanceof Blob?r?n(t):c(t,n):o&&(t instanceof ArrayBuffer||a(t))?r?n(t):c(new Blob([t]),n):n(s[e]+(t||"")),c=(e,t)=>{const s=new FileReader;return s.onload=function(){const e=s.result.split(",")[1];t("b"+(e||""))},s.readAsDataURL(e)};function h(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let u;const p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Qb=0;Qb<64;Qb++)d[p.charCodeAt(Qb)]=Qb;const f="function"==typeof ArrayBuffer,m=(e,t)=>{if("string"!=typeof e)return{type:"message",data:y(e,t)};const s=e.charAt(0);if("b"===s)return{type:"message",data:g(e.substring(1),t)};return r[s]?e.length>1?{type:r[s],data:e.substring(1)}:{type:r[s]}:n},g=(e,t)=>{if(f){const s=(e=>{let t,s,r,n,i,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const c=new ArrayBuffer(o),h=new Uint8Array(c);for(t=0;t<a;t+=4)s=d[e.charCodeAt(t)],r=d[e.charCodeAt(t+1)],n=d[e.charCodeAt(t+2)],i=d[e.charCodeAt(t+3)],h[l++]=s<<2|r>>4,h[l++]=(15&r)<<4|n>>2,h[l++]=(3&n)<<6|63&i;return c})(e);return y(s,t)}return{base64:!0,data:e}},y=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,w=String.fromCharCode(30);function b(){return new TransformStream({transform(e,t){!function(e,t){i&&e.data instanceof Blob?e.data.arrayBuffer().then(h).then(t):o&&(e.data instanceof ArrayBuffer||a(e.data))?t(h(e.data)):l(e,!1,e=>{u||(u=new TextEncoder),t(u.encode(e))})}(e,s=>{const r=s.length;let n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(s)})}})}let v;function C(e){return e.reduce((e,t)=>e+t.length,0)}function S(e,t){if(e[0].length===t)return e.shift();const s=new Uint8Array(t);let r=0;for(let n=0;n<t;n++)s[n]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),s}function k(e){if(e)return function(e){for(var t in k.prototype)e[t]=k.prototype[t];return e}(e)}k.prototype.on=k.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},k.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<r.length;n++)if((s=r[n])===t||s.fn===t){r.splice(n,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},k.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),s=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(s){r=0;for(var n=(s=s.slice(0)).length;r<n;++r)s[r].apply(this,t)}return this},k.prototype.emitReserved=k.prototype.emit,k.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},k.prototype.hasListeners=function(e){return!!this.listeners(e).length};const I="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),x="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function O(e,...t){return t.reduce((t,s)=>(e.hasOwnProperty(s)&&(t[s]=e[s]),t),{})}const A=x.setTimeout,E=x.clearTimeout;function R(e,t){t.useNativeTimers?(e.setTimeoutFn=A.bind(x),e.clearTimeoutFn=E.bind(x)):(e.setTimeoutFn=x.setTimeout.bind(x),e.clearTimeoutFn=x.clearTimeout.bind(x))}function M(e){return"string"==typeof e?function(e){let t=0,s=0;for(let r=0,n=e.length;r<n;r++)t=e.charCodeAt(r),t<128?s+=1:t<2048?s+=2:t<55296||t>=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))}function N(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class T extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class _ extends k{constructor(e){super(),this.writable=!1,R(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new T(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=m(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t}(e);return t.length?"?"+t:""}}class P extends _{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const s=e.split(w),r=[];for(let n=0;n<s.length;n++){const e=m(s[n],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const s=e.length,r=new Array(s);let n=0;e.forEach((e,i)=>{l(e,!1,e=>{r[i]=e,++n===s&&t(r.join(w))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=N()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let L=!1;try{L="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(qb){}const D=L;function B(){}class F extends P{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let s=location.port;s||(s=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class U extends k{constructor(e,t,s){super(),this.createRequest=e,R(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var e;const t=O(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&s.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{s.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var e;3===s.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=U.requestsCount++,U.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=B,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete U.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(U.requestsCount=0,U.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",j);else if("function"==typeof addEventListener){addEventListener("onpagehide"in x?"pagehide":"unload",j,!1)}function j(){for(let e in U.requests)U.requests.hasOwnProperty(e)&&U.requests[e].abort()}const z=function(){const e=V({xdomain:!1});return e&&null!==e.responseType}();function V(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||D))return new XMLHttpRequest}catch(s){}if(!t)try{return new(x[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(s){}}const W="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Y extends _{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=W?{}:O(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(qb){return this.emitReserved("error",qb)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;l(s,this.supportsBinary,e=>{try{this.doWrite(s,e)}catch(t){}r&&I(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=N()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const G=x.WebSocket||x.MozWebSocket;const Z={websocket:class extends Y{createSocket(e,t,s){return W?new G(e,t,s):t?new G(e,t):new G(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends _{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(qb){return this.emitReserved("error",qb)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){v||(v=new TextDecoder);const s=[];let r=0,i=-1,o=!1;return new TransformStream({transform(a,l){for(s.push(a);;){if(0===r){if(C(s)<1)break;const e=S(s,1);o=!(128&~e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(C(s)<2)break;const e=S(s,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(C(s)<8)break;const e=S(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){l.enqueue(n);break}i=o*Math.pow(2,32)+t.getUint32(4),r=3}else{if(C(s)<i)break;const e=S(s,i);l.enqueue(m(o?e:v.decode(e),t)),r=0}if(0===i||i>e){l.enqueue(n);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=b();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&I(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends F{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=z&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new U(V,this.uri(),e)}}},J=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,X=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function H(e){if(e.length>8e3)throw"URI too long";const t=e,s=e.indexOf("["),r=e.indexOf("]");-1!=s&&-1!=r&&(e=e.substring(0,s)+e.substring(s,r).replace(/:/g,";")+e.substring(r,e.length));let n=J.exec(e||""),i={},o=14;for(;o--;)i[X[o]]=n[o]||"";return-1!=s&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const s=/\/{2,9}/g,r=t.replace(s,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(e,t){const s={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(s[t]=r)}),s}(0,i.query),i}const K="function"==typeof addEventListener&&"function"==typeof removeEventListener,$=[];K&&addEventListener("offline",()=>{$.forEach(e=>e())},!1);class q extends k{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const s=H(e);t.hostname=s.host,t.secure="https"===s.protocol||"wss"===s.protocol,t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=H(t.host).host);R(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},s=e.split("&");for(let r=0,n=s.length;r<n;r++){let e=s[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),K&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},$.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&q.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",q.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const s=this.writeBuffer[t].data;if(s&&(e+=M(s)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,I(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:e,data:t,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(q.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),K&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=$.indexOf(this._offlineEventListener);-1!==e&&$.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}q.protocol=4;class Q extends q{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;q.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!s)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;q.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function n(){s||(s=!0,c(),t.close(),t=null)}const i=e=>{const s=new Error("probe error: "+e);s.transport=t.name,n(),this.emitReserved("upgradeError",s)};function o(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&n()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",o),this.off("close",a),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",o),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let ee=class extends Q{constructor(e,t={}){const s="object"==typeof e?e:t;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>Z[e]).filter(e=>!!e)),super(e,s)}};const te="function"==typeof ArrayBuffer,se=Object.prototype.toString,re="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===se.call(Blob),ne="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===se.call(File);function ie(e){return te&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||re&&e instanceof Blob||ne&&e instanceof File}function oe(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,s=e.length;t<s;t++)if(oe(e[t]))return!0;return!1}if(ie(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return oe(e.toJSON(),!0);for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&oe(e[s]))return!0;return!1}function ae(e){const t=[],s=e.data,r=e;return r.data=le(s,t),r.attachments=t.length,{packet:r,buffers:t}}function le(e,t){if(!e)return e;if(ie(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=le(e[r],t);return s}if("object"==typeof e&&!(e instanceof Date)){const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=le(e[r],t));return s}return e}function ce(e,t){return e.data=he(e.data,t),delete e.attachments,e}function he(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]=he(e[s],t);else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e[s]=he(e[s],t));return e}const ue=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var pe,de;(de=pe||(pe={}))[de.CONNECT=0]="CONNECT",de[de.DISCONNECT=1]="DISCONNECT",de[de.EVENT=2]="EVENT",de[de.ACK=3]="ACK",de[de.CONNECT_ERROR=4]="CONNECT_ERROR",de[de.BINARY_EVENT=5]="BINARY_EVENT",de[de.BINARY_ACK=6]="BINARY_ACK";function fe(e){return"[object Object]"===Object.prototype.toString.call(e)}class me extends k{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===pe.BINARY_EVENT;s||t.type===pe.BINARY_ACK?(t.type=s?pe.EVENT:pe.ACK,this.reconstructor=new ge(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!ie(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(void 0===pe[s.type])throw new Error("unknown packet type "+s.type);if(s.type===pe.BINARY_EVENT||s.type===pe.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(r,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");s.attachments=Number(n)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}s.nsp=e.substring(r,t)}else s.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const s=e.charAt(t);if(null==s||Number(s)!=s){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!me.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case pe.CONNECT:return fe(t);case pe.DISCONNECT:return void 0===t;case pe.CONNECT_ERROR:return"string"==typeof t||fe(t);case pe.EVENT:case pe.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ue.indexOf(t[0]));case pe.ACK:case pe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ge{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ce(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ye=Object.freeze(Object.defineProperty({__proto__:null,Decoder:me,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==pe.EVENT&&e.type!==pe.ACK||!oe(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===pe.EVENT?pe.BINARY_EVENT:pe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==pe.BINARY_EVENT&&e.type!==pe.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=ae(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}},get PacketType(){return pe},protocol:5},Symbol.toStringTag,{value:"Module"}));function we(e,t,s){return e.on(t,s),function(){e.off(t,s)}}const be=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ve extends k{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[we(e,"open",this.onopen.bind(this)),we(e,"packet",this.onpacket.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,r,n;if(be.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:pe.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,s=t.pop();this._registerAckCallback(e,s),i.id=e}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((s,r)=>{const n=(e,t)=>e?r(e):s(t);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(s!==this._queue[0])return;return null!==e?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:pe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case pe.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case pe.EVENT:case pe.BINARY_EVENT:this.onevent(e);break;case pe.ACK:case pe.BINARY_ACK:this.onack(e);break;case pe.DISCONNECT:this.ondisconnect();break;case pe.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:pe.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:pe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function Ce(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ce.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+s:e-s}return 0|Math.min(e,this.max)},Ce.prototype.reset=function(){this.attempts=0},Ce.prototype.setMin=function(e){this.ms=e},Ce.prototype.setMax=function(e){this.max=e},Ce.prototype.setJitter=function(e){this.jitter=e};class Se extends k{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,R(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=t.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new Ce({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||ye;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ee(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=we(t,"open",function(){s.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=we(t,"error",n);if(!1!==this._timeout){const e=this._timeout,s=this.setTimeoutFn(()=>{r(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(we(e,"ping",this.onping.bind(this)),we(e,"data",this.ondata.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this)),we(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){I(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new ve(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t){if(this.nsps[s].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ke={};function Ie(e,t){"object"==typeof e&&(t=e,e=void 0);const s=function(e,t="",s){let r=e;s=s||"undefined"!=typeof location&&location,null==e&&(e=s.protocol+"//"+s.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?s.protocol+e:s.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==s?s.protocol+"//"+e:"https://"+e),r=H(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port+t,r.href=r.protocol+"://"+n+(s&&s.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=s.source,n=s.id,i=s.path,o=ke[n]&&i in ke[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Se(r,t):(ke[n]||(ke[n]=new Se(r,t)),a=ke[n]),s.query&&!t.query&&(t.query=s.queryKey),a.socket(s.path,t)}Object.assign(Ie,{Manager:Se,Socket:ve,io:Ie,connect:Ie});class xe{constructor(e){t(this,"socket"),t(this,"encode"),t(this,"decode"),this.socket=Ie(e.baseUrl,{transports:["websocket"],path:"/analytics/ws",auth:{token:e.authToken},query:e.query}),this.encode=e.encoder??(e=>function(e){const t=(new TextEncoder).encode(e);if("undefined"!=typeof window&&"function"==typeof window.btoa){const e=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(e)}if("undefined"!=typeof Buffer)return Buffer.from(t).toString("base64");throw new Error("[utils.base64Encode]: Unsupported environment")}(JSON.stringify(e))),this.decode=e.decoder??(e=>JSON.parse((e=>{if("undefined"!=typeof window&&"function"==typeof window.atob){const t=atob(e),s=t.length,r=new Uint8Array(s);for(let e=0;e<s;e++)r[e]=t.charCodeAt(e);return(new TextDecoder).decode(r)}if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("[utils.base64Decode]: Unsupported environment")})(e)))}send(e,t,s){"function"==typeof s?this.socket.emit(e,this.encode(t),s):this.socket.emit(e,this.encode(t))}on(e,t){this.socket.on(e,e=>t(this.decode(e)))}}class Oe{constructor(e){t(this,"baseUrl"),t(this,"authToken"),t(this,"sdkMetadata"),this.baseUrl=e.baseUrl,this.authToken=e.authToken,this.sdkMetadata=e.sdkMetadata}async send(e,t){const s=new URL(e,this.baseUrl),r={...t,...this.sdkMetadata&&{sdk:this.sdkMetadata}};try{const e=await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json",...this.authToken&&{Authorization:`Bearer ${this.authToken}`}},body:JSON.stringify(r)});if(!e.ok)return null;let t;try{t=await e.json()}catch{t={}}return t}catch(n){}}}class Ae{constructor(e){if(t(this,"defaultTTL"),t(this,"items"),this.defaultTTL=e,e<=0)throw new Error("Default TTL must be a positive number.");this.items=new Map,this.defaultTTL=e,setInterval(()=>this.cleanup(),e)}add(e,t){const s=void 0!==t?t:this.defaultTTL;if(s<=0)throw new Error("TTL must be a positive number.");const r=Date.now()+s;this.items.set(e,r)}has(e){const t=this.items.get(e);return void 0!==t&&(!(Date.now()>t)||(this.items.delete(e),!1))}delete(e){this.items.delete(e)}get size(){return this.cleanup(),this.items.size}clear(){this.items.clear()}cleanup(){const e=Date.now();for(const[t,s]of this.items.entries())s<=e&&this.items.delete(t)}toArray(){return this.cleanup(),Array.from(this.items.keys())}}let Ee=null;var Re,Me,Ne,Te;"undefined"!=typeof window&&window.addEventListener("message",e=>{if("https://agent.brainfi.sh"===e.origin&&"REQUEST_USER_IDENTITY"===e.data?.type&&Ee&&e.source){const t=document.querySelector("#bf-iframe-container .trigger-iframe");if(!t||e.source!==t.contentWindow)return void console.warn("BrainfishWidgetWarn: Rejected REQUEST_USER_IDENTITY from untrusted iframe source:",e.origin);e.source.postMessage({type:"USER_IDENTIFY",payload:Ee},e.origin)}}),(Me=Re||(Re={})).OpenUrl="openUrl",Me.CallPhone="callPhone",Me.SendEmail="sendEmail",Me.TriggerEvent="triggerEvent",(Te=Ne||(Ne={})).Button="button",Te.Link="link";const _e=class e{constructor(s){t(this,"options"),t(this,"client"),t(this,"httpClient"),t(this,"userId"),t(this,"global"),t(this,"queue",[]),t(this,"knownEvents",["nudge.show"]),t(this,"eventListeners",{}),t(this,"recentNudgeIds",new Ae(1e3)),t(this,"trackingDisabled",!1),this.options=s;const r={sdk_name:s.sdk||"node",sdk_version:s.sdkVersion||""},n=s.apiUrl||"https://analytic.brainfi.sh",i=s.accessKey;this.client=new xe({baseUrl:n,authToken:i,query:r}),this.httpClient=new Oe({baseUrl:n,authToken:i,sdkMetadata:{name:s.sdk||"node",version:s.sdkVersion||""}}),"undefined"!=typeof window&&"undefined"!=typeof localStorage&&(this.trackingDisabled="true"===localStorage.getItem(e.TRACKING_DISABLED_KEY)),this.setupIncomingPayloadHandler()}init(){}ready(){this.options.waitForUser=!1,this.flush()}setupIncomingPayloadHandler(){this.client.on("e",this.handleIncomingPayload.bind(this))}handleIncomingPayload(e){if("nudge.show"===e.type){const{nudgeId:t}=e.payload;if(this.recentNudgeIds.has(t))return;this.recentNudgeIds.add(t),this.dispatchEventListeners("nudge.show",e.payload)}}dispatchEventListeners(e,t){this.eventListeners[e]?.forEach(e=>e(t))}on(e,t){this.knownEvents.includes(e)&&(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(t))}off(e,t){this.knownEvents.includes(e)&&this.eventListeners[e]&&(this.eventListeners[e]=this.eventListeners[e].filter(e=>e!==t),0===this.eventListeners[e].length&&delete this.eventListeners[e])}async send(e,t){return this.options.disabled||this.trackingDisabled||this.options.filter&&!this.options.filter(e)?Promise.resolve():this.options.waitForUser&&!this.userId?(this.queue.push(e),Promise.resolve()):this.client.send("t",e,t)}setGlobalProperties(e){this.global={...this.global,...e}}async track(e,t,s){return this.send({type:"event.track",payload:{name:e,userId:t?.userId??this.userId,properties:{...this.global??{},...t??{},...s?{_bfOverrides:s}:{}}}})}async identify(e){e.userId?(this.userId=e.userId,this.flush()):console.warn("BrainfishWidgetWarn: `.identify` called without a userId. User identification requires a valid userId to be provided.");const t=new Set(["userId","firstName","lastName","email","phone","avatar","properties"]),s=Object.keys(e).filter(e=>!t.has(e));s.length>0&&console.warn(`BrainfishWidgetWarn: The following fields are not recognized as main identifier fields: ${s.join(", ")}. Please place custom fields under the 'properties' object instead. Note: Using fields incorrectly may cause user identification to not work as expected.`),e.phone&&!/^\+[1-9]\d{1,14}$/.test(e.phone)&&console.warn("BrainfishWidgetWarn: phone should be in E.164 format (e.g., +14155552671). Providing the correct format ensures accurate user identification."),Ee=e;const r=document.querySelector("#bf-iframe-container .trigger-iframe");if(r){const t=()=>{r.contentWindow&&r.contentWindow.postMessage({type:"USER_IDENTIFY",payload:e},"*")};r.contentWindow&&t(),r.addEventListener("load",t)}if(Object.keys(e).length>1)return this.send({type:"user.identify",payload:{...e,properties:{...this.global,...e.properties}}})}async record(e){if(this.options.disabled)return Promise.resolve(null);if(this.trackingDisabled)return Promise.resolve(null);const t={type:"event.record",payload:{events:e,userId:this.userId}};if(this.options.filter&&!this.options.filter(t))return Promise.resolve(null);const s=await this.httpClient.send("/s",{events:e,userId:this.userId});return s?.sessionId||null}async alias(e){return this.send({type:"user.alias",payload:e})}async increment(e){return this.send({type:"user.increment",payload:e})}async decrement(e){return this.send({type:"user.decrement",payload:e})}clear(){this.userId=void 0}flush(){this.queue.forEach(e=>{this.send({...e,payload:{...e.payload,userId:e.payload.userId??this.userId}})}),this.queue=[]}disableTracking(){this.trackingDisabled=!0,"undefined"!=typeof window&&"undefined"!=typeof localStorage&&localStorage.setItem(e.TRACKING_DISABLED_KEY,"true")}enableTracking(){this.trackingDisabled=!1,"undefined"!=typeof window&&"undefined"!=typeof localStorage&&localStorage.removeItem(e.TRACKING_DISABLED_KEY),console.log("Brainfish tracking re-enabled. Refresh page for full effect.")}isTrackingDisabled(){return this.trackingDisabled}};t(_e,"TRACKING_DISABLED_KEY","bf_tracking_disabled");let Pe=_e;var Le,De=Object.defineProperty,Be=(e,t,s)=>((e,t,s)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),Fe=Object.defineProperty,Ue=(e,t,s)=>((e,t,s)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),je=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(je||{});const ze={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ve={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},We={};function Ye(e){if(We[e])return We[e];const t=globalThis[e],s=t.prototype,r=e in ze?ze[e]:void 0,n=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(s,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))})),i=e in Ve?Ve[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof s[e]&&(null==(t=s[e])?void 0:t.toString().includes("[native code]"))}));if(n&&o&&!globalThis.Zone)return We[e]=t.prototype,t.pr