@callimacus/thamyr-liquid 4.13.1 → 4.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.core.md CHANGED
@@ -3,6 +3,13 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.13.2](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.1...thamyr-core-v4.13.2) (2026-10-28)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **core:** the socket handshake carries the visitor's intent session id, so rounds get session intent on any API host ([#859](https://github.com/callimacus/thamyr-sdk/issues/859)) ([8270ac2](https://github.com/callimacus/thamyr-sdk/commit/8270ac2a90caacc53e7c89698ccc11ca3b5c81f2))
12
+
6
13
  ## [4.13.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.0...thamyr-core-v4.13.1) (2026-10-27)
7
14
 
8
15
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.13.2](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.13.1...thamyr-liquid-v4.13.2) (2026-10-28)
4
+
5
+
6
+ ### Miscellaneous Chores
7
+
8
+ * **thamyr-liquid:** Synchronize thamyr versions
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @callimacus/thamyr-core bumped from ^4.13.1 to ^4.13.2
16
+
3
17
  ## [4.13.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.13.0...thamyr-liquid-v4.13.1) (2026-10-27)
4
18
 
5
19
 
@@ -10,7 +10,7 @@
10
10
  * Socket.IO v4.8.4
11
11
  * (c) 2014-2026 Guillermo Rauch
12
12
  * Released under the MIT License.
13
- */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(s=>{e[t[s]]=s});const s={type:"error",data:"parser error"},i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>i&&s instanceof Blob?o?c(s):a(s,c):n&&(s instanceof ArrayBuffer||r(s))?o?c(s):a(new Blob([s]),c):c(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)u["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const d="function"==typeof ArrayBuffer,l=(t,i)=>{if("string"!=typeof t)return{type:"message",data:f(t,i)};const n=t.charAt(0);return"b"===n?{type:"message",data:p(t.substring(1),i)}:e[n]?t.length>1?{type:e[n],data:t.substring(1)}:{type:e[n]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,i,n,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),d=new Uint8Array(h);for(e=0;e<a;e+=4)s=u[t.charCodeAt(e)],i=u[t.charCodeAt(e+1)],n=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|i>>4,d[c++]=(15&i)<<4|n>>2,d[c++]=(3&n)<<6|63&r;return h})(t);return f(s,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){i&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):n&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,s=>{const i=s.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(s)})}})}let g;function b(t){return t.reduce((t,e)=>t+e.length,0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let i=0;for(let n=0;n<e;n++)s[n]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),s}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var s,i=this.t["$"+t];if(!i)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var n=0;n<i.length;n++)if((s=i[n])===e||s.fn===e){i.splice(n,1);break}return 0===i.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),s=this.t["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(s){i=0;for(var n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const O=R.setTimeout,T=R.clearTimeout;function A(t,e){e.useNativeTimers?(t.setTimeoutFn=O.bind(R),t.clearTimeoutFn=T.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function C(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}let S=class extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}},N=class extends w{constructor(t){super(),this.writable=!1,A(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new S(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}};class B extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(y),i=[];for(let t=0;t<s.length;t++){const n=l(s[t],e);if(i.push(n),"error"===n.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,i=new Array(s);let n=0;t.forEach((t,r)=>{o(t,!1,t=>{i[r]=t,++n===s&&e(i.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const I=x;function U(){}class j extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class L extends w{constructor(t,e,s){super(),this.createRequest=t,A(this,s),this.p=s,this.v=s.method||"GET",this.m=e,this.k=void 0!==s.data?s.data:null,this.A()}A(){var t;const e=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.p.xd;const s=this.O=this.createRequest(e);try{s.open(this.v,this.m,!0);try{if(this.p.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this.p.extraHeaders[t])}}catch(t){}if("POST"===this.v)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.p.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(s.timeout=this.p.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof s.status?s.status:0)},0))},s.send(this.k)}catch(t){return void this.setTimeoutFn(()=>{this.j(t)},0)}"undefined"!=typeof document&&(this.B=L.requestsCount++,L.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(t){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=U,t)try{this.O.abort()}catch(t){}"undefined"!=typeof document&&delete L.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}}function $(){for(let t in L.requests)L.requests.hasOwnProperty(t)&&L.requests[t].abort()}L.requestsCount=0,L.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",$):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",$,!1));const _=function(){const t=D({xdomain:!1});return t&&null!==t.responseType}();function D(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||I))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const q="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class M extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=q?{}:E(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(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const V=R.WebSocket||R.MozWebSocket;const P={websocket:class extends M{createSocket(t,e,s){return q?new V(t,e,s):e?new V(t,e):new V(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const i=[];let n=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(i.push(a);;){if(0===n){if(b(i)<1)break;const t=v(i,1);o=!(128&~t[0]),r=127&t[0],n=r<126?3:126===r?1:2}else if(1===n){if(b(i)<2)break;const t=v(i,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),n=3}else if(2===n){if(b(i)<8)break;const t=v(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),n=3}else{if(b(i)<r)break;const t=v(i,r);c.enqueue(l(o?t:g.decode(t),e)),n=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),n=m();n.readable.pipeTo(t.writable),this.U=n.writable.getWriter();const r=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;this.U.write(s).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends j{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(D,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),i=t.indexOf("]");-1!=s&&-1!=i&&(t=t.substring(0,s)+t.substring(s,i).replace(/:/g,";")+t.substring(i,t.length));let n=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=n[o]||"";return-1!=s&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(s[e]=i)}),s}(0,r.query),r}const z="function"==typeof addEventListener&&"function"==typeof removeEventListener,W=[];z&&addEventListener("offline",()=>{W.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,i;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=K(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=K(e.host).host);if(A(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(s=e.transports)||void 0===s?void 0:s.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(i=e.transportImplementations)&&void 0!==i?i:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=P),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},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,i=s.length;t<i;t++){let i=s[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),z&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},W.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](s)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Y.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),s=!1;Y.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function n(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,n(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Y.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+="string"==typeof(e=i)?function(t){let e=0,s=0;for(let i=0,n=t.length;i<n;i++)e=t.charCodeAt(i),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(i++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.L)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this.G("message",t,e,s),this}send(t,e,s){return this.G("message",t,e,s),this}G(t,e,s,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof s&&(i=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:t,data:e,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}j(t){if(Y.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),z&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=W.indexOf(this.$);-1!==t&&W.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}Y.protocol=4;const J="function"==typeof ArrayBuffer,G=Object.prototype.toString,X="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===G.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===G.call(File);function Q(t){return J&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||X&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],s=t.data,i=t;return i.data=st(s,e),i.attachments=e.length,{packet:i,buffers:e}}function st(t,e,s){if(!t)return t;if(Q(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let i=0;i<t.length;i++)s[i]=st(t[i],e);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return st(t.toJSON(),e,!0);const i={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=st(t[s],e));return i}return t}function it(t,e){return t.data=nt(t.data,e),delete t.attachments,t}function nt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=nt(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=nt(t[s],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===ot.BINARY_EVENT;s||e.type===ot.BINARY_ACK?(e.type=s?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===ot[s.type])throw new Error("unknown packet type "+s.type);if(s.type===ot.BINARY_EVENT||s.type===ot.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(i,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(n);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=r}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(i,e)}else s.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,i))throw new Error("invalid payload");s.data=i}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return ut(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=it(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ut(t){return"[object Object]"===Object.prototype.toString.call(t)}var dt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||ut(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.p=Object.assign({},s),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,i,n;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this.ut(t,s),r.id=t}const o=null===(i=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var s;const i=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const n=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),r=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,i)=>{const n=(t,e)=>t?i(t):s(e);n.withError=!0,e.push(n),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...i)),s.pending=!1,this.ft())),this.et.push(s),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:ot.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const s of e)s.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,A(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const i=e.parser||dt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new Y(this.uri,this.opts);const e=this.engine,s=this;this.ht="opening",this.skipReconnect=!1;const i=lt(e,"open",function(){s.onopen(),t&&t()}),n=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",n);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this.rt&&!s.active&&s.connect():(s=new ft(this,t,e),this.nsps[t]=s),s}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function bt(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let i=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(s&&s.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=s.source,n=s.id,r=s.path,o=gt[n]&&r in gt[n].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(i,e):(gt[n]||(gt[n]=new mt(i,e)),a=gt[n]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(bt,{Manager:mt,Socket:ft,io:bt,connect:bt});
13
+ */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(s=>{e[t[s]]=s});const s={type:"error",data:"parser error"},i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>i&&s instanceof Blob?o?c(s):a(s,c):n&&(s instanceof ArrayBuffer||r(s))?o?c(s):a(new Blob([s]),c):c(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)u["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const d="function"==typeof ArrayBuffer,l=(t,i)=>{if("string"!=typeof t)return{type:"message",data:f(t,i)};const n=t.charAt(0);return"b"===n?{type:"message",data:p(t.substring(1),i)}:e[n]?t.length>1?{type:e[n],data:t.substring(1)}:{type:e[n]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,i,n,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),d=new Uint8Array(h);for(e=0;e<a;e+=4)s=u[t.charCodeAt(e)],i=u[t.charCodeAt(e+1)],n=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|i>>4,d[c++]=(15&i)<<4|n>>2,d[c++]=(3&n)<<6|63&r;return h})(t);return f(s,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){i&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):n&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,s=>{const i=s.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(s)})}})}let g;function b(t){return t.reduce((t,e)=>t+e.length,0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let i=0;for(let n=0;n<e;n++)s[n]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),s}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var s,i=this.t["$"+t];if(!i)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var n=0;n<i.length;n++)if((s=i[n])===e||s.fn===e){i.splice(n,1);break}return 0===i.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),s=this.t["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(s){i=0;for(var n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const O=R.setTimeout,T=R.clearTimeout;function A(t,e){e.useNativeTimers?(t.setTimeoutFn=O.bind(R),t.clearTimeoutFn=T.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function C(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}let S=class extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}},N=class extends w{constructor(t){super(),this.writable=!1,A(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new S(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}};class B extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(y),i=[];for(let t=0;t<s.length;t++){const n=l(s[t],e);if(i.push(n),"error"===n.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,i=new Array(s);let n=0;t.forEach((t,r)=>{o(t,!1,t=>{i[r]=t,++n===s&&e(i.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const I=x;function U(){}class j extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}let L=class t extends w{constructor(t,e,s){super(),this.createRequest=t,A(this,s),this.p=s,this.v=s.method||"GET",this.m=e,this.k=void 0!==s.data?s.data:null,this.A()}A(){var e;const s=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this.p.xd;const i=this.O=this.createRequest(s);try{i.open(this.v,this.m,!0);try{if(this.p.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&i.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(i.timeout=this.p.requestTimeout),i.onreadystatechange=()=>{var t;3===i.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof i.status?i.status:0)},0))},i.send(this.k)}catch(e){return void this.setTimeoutFn(()=>{this.j(e)},0)}"undefined"!=typeof document&&(this.B=t.requestsCount++,t.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(e){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=U,e)try{this.O.abort()}catch(e){}"undefined"!=typeof document&&delete t.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}};function $(){for(let t in L.requests)L.requests.hasOwnProperty(t)&&L.requests[t].abort()}L.requestsCount=0,L.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",$):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",$,!1));const _=function(){const t=D({xdomain:!1});return t&&null!==t.responseType}();function D(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||I))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const q="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class M extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=q?{}:E(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(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const V=R.WebSocket||R.MozWebSocket;const P={websocket:class extends M{createSocket(t,e,s){return q?new V(t,e,s):e?new V(t,e):new V(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const i=[];let n=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(i.push(a);;){if(0===n){if(b(i)<1)break;const t=v(i,1);o=!(128&~t[0]),r=127&t[0],n=r<126?3:126===r?1:2}else if(1===n){if(b(i)<2)break;const t=v(i,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),n=3}else if(2===n){if(b(i)<8)break;const t=v(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),n=3}else{if(b(i)<r)break;const t=v(i,r);c.enqueue(l(o?t:g.decode(t),e)),n=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),n=m();n.readable.pipeTo(t.writable),this.U=n.writable.getWriter();const r=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;this.U.write(s).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends j{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(D,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),i=t.indexOf("]");-1!=s&&-1!=i&&(t=t.substring(0,s)+t.substring(s,i).replace(/:/g,";")+t.substring(i,t.length));let n=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=n[o]||"";return-1!=s&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(s[e]=i)}),s}(0,r.query),r}const z="function"==typeof addEventListener&&"function"==typeof removeEventListener,W=[];z&&addEventListener("offline",()=>{W.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,i;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=K(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=K(e.host).host);if(A(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(s=e.transports)||void 0===s?void 0:s.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(i=e.transportImplementations)&&void 0!==i?i:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=P),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},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,i=s.length;t<i;t++){let i=s[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),z&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},W.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](s)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Y.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),s=!1;Y.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function n(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,n(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Y.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+="string"==typeof(e=i)?function(t){let e=0,s=0;for(let i=0,n=t.length;i<n;i++)e=t.charCodeAt(i),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(i++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.L)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this.G("message",t,e,s),this}send(t,e,s){return this.G("message",t,e,s),this}G(t,e,s,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof s&&(i=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:t,data:e,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}j(t){if(Y.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),z&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=W.indexOf(this.$);-1!==t&&W.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}Y.protocol=4;const J="function"==typeof ArrayBuffer,G=Object.prototype.toString,X="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===G.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===G.call(File);function Q(t){return J&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||X&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],s=t.data,i=t;return i.data=st(s,e),i.attachments=e.length,{packet:i,buffers:e}}function st(t,e,s){if(!t)return t;if(Q(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let i=0;i<t.length;i++)s[i]=st(t[i],e);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return st(t.toJSON(),e,!0);const i={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=st(t[s],e));return i}return t}function it(t,e){return t.data=nt(t.data,e),delete t.attachments,t}function nt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=nt(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=nt(t[s],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===ot.BINARY_EVENT;s||e.type===ot.BINARY_ACK?(e.type=s?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===ot[s.type])throw new Error("unknown packet type "+s.type);if(s.type===ot.BINARY_EVENT||s.type===ot.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(i,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(n);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=r}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(i,e)}else s.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,i))throw new Error("invalid payload");s.data=i}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return ut(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=it(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ut(t){return"[object Object]"===Object.prototype.toString.call(t)}var dt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||ut(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.p=Object.assign({},s),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,i,n;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this.ut(t,s),r.id=t}const o=null===(i=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var s;const i=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const n=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),r=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,i)=>{const n=(t,e)=>t?i(t):s(e);n.withError=!0,e.push(n),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...i)),s.pending=!1,this.ft())),this.et.push(s),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:ot.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const s of e)s.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,A(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const i=e.parser||dt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new Y(this.uri,this.opts);const e=this.engine,s=this;this.ht="opening",this.skipReconnect=!1;const i=lt(e,"open",function(){s.onopen(),t&&t()}),n=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",n);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this.rt&&!s.active&&s.connect():(s=new ft(this,t,e),this.nsps[t]=s),s}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function bt(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let i=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(s&&s.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=s.source,n=s.id,r=s.path,o=gt[n]&&r in gt[n].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(i,e):(gt[n]||(gt[n]=new mt(i,e)),a=gt[n]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(bt,{Manager:mt,Socket:ft,io:bt,connect:bt});
14
14
  /*!
15
15
  * Copyright © 2025–2026 Solomei AI SRL. All rights reserved.
16
16
  *
@@ -18,5 +18,5 @@
18
18
  * See LICENSE.md for the full terms.
19
19
  *
20
20
  */
21
- const vt="chapter-event",wt="story-created",kt="error",Rt="server-response",Et="client-ready",Ot="user-interaction",Tt=4,At={debug:0,info:1,warn:2,error:3,silent:4},Ct=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:s}=this.config,i=void 0===s||""===s?e:[s,...e];console[t](...i)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function St(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=[...e].map(t=>t.toString(16).padStart(2,"0"));return[s.slice(0,4).join(""),s.slice(4,6).join(""),s.slice(6,8).join(""),s.slice(8,10).join(""),s.slice(10,16).join("")].join("-")}var Nt,Bt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story",t.SUGGEST="suggest"}(Nt||(Nt={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Bt||(Bt={}));const xt={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class It{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??xt.minVisibilityRatio;this.config={productSelector:t.productSelector??xt.productSelector,blockSelector:t.blockSelector??xt.blockSelector,maxTrackedElements:t.maxTrackedElements??xt.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void Ct.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),i=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),i=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const s=this.resolveElementId(t),i=this.resolveBlockId(t),n=this.createTrackingKey(s,i),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==n&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,n),this.elementRefs.set(n,t),this.elements.set(n,{id:s,blockId:i,trackingKey:n,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),i=this.blockKeys.get(t),n=s;void 0!==i&&""!==i&&i!==n&&(this.blocks.delete(i),this.blockRefs.delete(i)),this.blockKeys.set(t,n),this.blockRefs.set(n,t),this.blocks.set(n,{id:s,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),s=t.width*t.height;if(s<=0)return 0;const i=window.innerWidth*window.innerHeight,n=i>0?Math.min(s,i):s;return Math.min(1,Math.max(0,e/n))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],s=Date.now();for(const[e,s]of this.elements){const i=this.elementRefs.get(e);i?.isConnected?s.visibilityRatio<=0||t.push({blockId:s.blockId,element:{id:s.id,bounds:s.bounds,isVisible:s.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:s.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,s]of this.blocks){const i=this.blockRefs.get(t);i?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const i=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...i.flatMap(t=>t.blockId??[])])],elements:i.map(t=>t.element)}}}class Ut{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=xt;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{Ct.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{Ct.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:s,reason:i}=e;return"number"==typeof s?{code:s,..."string"==typeof i&&{reason:i}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(Ct.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{Ct.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{Ct.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{Ct.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{Ct.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{Ct.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(Ct.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,Ct.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return Ct.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new It(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),s=new URL("thamyr",e).pathname;return{origin:e.origin,path:s}}connect(t="wss://localhost:4000",e,s){this.socket&&(Ct.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const i=this.socketEndpoint(t);let n;"undefined"!=typeof window&&void 0!==globalThis.location&&(n=globalThis.location.href);const r={...void 0!==n&&""!==n&&{referrer:n},...s};Ct.info("Connecting to Thamyr at",i),this.socket=bt(i.origin,{path:i.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:r}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),Ct.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...xt,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new It(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void Ct.error("Socket is not connected. Cannot send interaction.");if(t===Nt.SUGGEST)return void Ct.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Nt.BACK_FROM_ROUND&&void 0===e.chapterId)return void Ct.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},i={id:St()};this.socket.emit(Ot,{type:s.type,payload:s.payload},i.id)}async suggest(t,e={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(t){const e=t?.suggestions;return{suggestions:Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}}(await this.socket.timeout(e.timeoutMs??4e3).emitWithAck(Ot,{type:Nt.SUGGEST,payload:t}))}catch(t){return Ct.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const jt="https://api.callimacus.ai",Lt="/cart/add.js",$t="[callimacus]";class _t extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function Dt(t){return qt(t,"[data-callimacus-settings]","using {}")??{}}function qt(t,e,s){if(void 0!==t&&""!==t)try{const i=JSON.parse(t);if("object"==typeof i&&null!==i&&!Array.isArray(i))return i;console.warn(`${$t} ${e} must be a JSON object — ${s}`)}catch(t){console.warn(`${$t} ${e} is not valid JSON — ${s}`,t)}}function Mt(t,e){return void 0===t||""===t?e:t}function Vt(t){return`server_${t.code??"error"}`}function Pt(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Ft(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Ht(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Kt(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${$t} invalid data-language "${e}" — formatting with "en"`),e="en"}const s=new Map;const i=function(t,e){let s;try{s=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{s=void 0}const i=void 0!==s&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(s)?s:e;try{return Intl.getCanonicalLocales(i)[0]??i}catch{return i}}(t.rootUrl,t.language);async function n(e,s,n,r={}){const o="string"==typeof s?s:s?.id,{clientId:a}=t;if(void 0===o||""===o)throw new _t("send_failed","The item has no id to look up");if(void 0===a||""===a)throw new _t("send_failed","No client id to look up with");const c=new AbortController,h=setTimeout(()=>{c.abort()},n.timeoutMs??1e4);try{let s;try{s=await fetch(`${new URL("api/v3",t.endpoint).href}/skesis/query/${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"x-sl-access-token":a},body:JSON.stringify({anchorId:o,locale:n.locale??i,...r}),signal:c.signal})}catch(t){throw new _t("lookup_unreachable","Could not reach the catalogue",{cause:t})}if(!s.ok)throw new _t(`server_${s.status}`,`The catalogue refused the lookup (HTTP ${s.status})`);return await s.json().catch(t=>{throw new _t("lookup_unreachable","The catalogue sent an unreadable answer",{cause:t})})}finally{clearTimeout(h)}}const r=t=>(Array.isArray(t)?t:[]).filter(t=>"object"==typeof t?.item).map(t=>void 0===t.score?t.item:{...t.item,score:t.score});return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of Ht(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of Ht(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(i){const n="number"==typeof i?i:i?.amount;if("number"!=typeof n)return"";const r="object"==typeof i?i?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!s.has(t))try{s.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${$t} invalid currency code "${t}" — showing bare amounts`),s.set(t,void 0)}return s.get(t)}(o)?.format(n)??n.toFixed(2)},productUrl(e){const s=e?.fields?.["shopify-handle"];if(void 0===s||""===s)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${s}`},imageUrl(t,{width:e=800,index:s=0}={}){const i=t?.fields?.images?.[s]?.url;return void 0===i||""===i?void 0:`${i.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],s=e.find(t=>t.orderable)??e[0];return void 0===s?.id?void 0:String(s.id).split("/").pop()},async addToCart(e,s=1){let i;try{i=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:s}]})})}catch(t){throw new _t("cart_unreachable","Could not reach the cart",{cause:t})}const n=await i.json().catch(()=>(console.warn(`${$t} cart response was not JSON (HTTP ${i.status})`),{}));if(!i.ok){const{description:t,message:e}=n??{};throw new _t("cart_rejected",t??e??`Could not add to cart (HTTP ${i.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:n})),n},async similar(t,{topK:e,...s}={}){const i=await n("similar",t,s,void 0===e?{}:{topK:e});return r(i?.hits)},async related(t,e={}){const s=await n("related",t,e)??{};return{related:r(s.related),siblingColors:r(s.siblingColors),usedFallback:!0===s.usedFallback}}})}function zt(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const s=e;return s?.type===t&&"function"==typeof s.render})}function Wt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,i={clientId:s.clientId,endpoint:Mt(s.endpoint,jt),language:Mt(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:Mt(s.rootUrl,"/"),cartAddUrl:Mt(s.cartAddUrl,Lt),settings:Dt(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void Pt(t,"design-mode");if(void 0===i.clientId||""===i.clientId)return Pt(t,"error"),void console.warn(`${$t} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${$t} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:n}=i,r=e.roundTimeoutMs??45e3,o=Kt(i),a=new Set;let c,h,u=!1,d=""===s.storyId?void 0:s.storyId,l=!1,p=!1;const f=new Set,y=void 0!==s.uiObserver&&"false"!==s.uiObserver,m=""===s.uiObserver?void 0:s.uiObserver;function g(){return c||(c=e.transport??new Ut,y&&c.configureUiObserver?.({enabled:!0,...void 0!==m&&{productSelector:m}}),c.onConnectionStatus&&(p=!0,c.onConnectionStatus(t=>{if(l=t,t){for(const t of f)t();f.clear()}})),c.onError(t=>{h=`${Vt(t)}: ${t.message??""}`,u||console.warn(`${$t} transport error between rounds — ${h}`)}),c.onServerResponse(e=>{if(e.type!==wt)return;const s=e.story?.id;"string"==typeof s&&""!==s&&s!==d&&(d=s,Ft(t,"callimacus:story",{storyId:s}))}),c.connect(i.endpoint,{Authorization:`Bearer ${n}`},{token:n}),c)}async function b(t){const e=g();return new Promise((s,i)=>{function n(){clearTimeout(o),c(),u()}const o=setTimeout(()=>{n();i(new _t("timeout",`Callimacus did not answer in time${void 0===h?"":` (last transport error: ${h})`}`))},r),c=e.onServerResponse(e=>{if(e.type!==vt)return;const i=e.chapter;i?.status===Tt&&!a.has(i.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:s,data:i}=t;if(void 0!==s&&s!==e.type)return!1;const n=e.data;return!(void 0!==i?.interactionId&&i.interactionId!==n.interactionId||"string"==typeof i?.value&&"string"==typeof n.value&&i.value!==n.value)}(i.inputEvent,t.inputEvent)&&(a.add(i.id),n(),s(i))}),u=e.onError(t=>{n(),i(new _t(Vt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(Nt.CREATE_ROUND,t)}catch(t){n(),i(new _t("send_failed","Could not send the request",{cause:t}))}})}function v(t={}){const e=t.storyId??d;return{language:t.language??i.language,...null!=e&&{storyId:e}}}async function w(e){if(!u){u=!0;try{let s;try{s=e()}catch(t){throw new _t("send_failed",t instanceof Error?t.message:"Could not build the request",{cause:t})}const{inputEvent:i}=s;Pt(t,"loading"),Ft(t,"callimacus:loading",{value:i.data.value,inputEvent:i});const n=await b(s),r=[...n.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:a,rendered:c}=function(t,e,s=!1){const i=document.createDocumentFragment();let n=0;for(const r of t){const t=zt(r.type);if(t)try{const o=t.render(r,e);s&&o instanceof HTMLElement&&void 0===o.dataset.blockId&&(o.dataset.blockId=r.id),o instanceof Node?(i.append(o),n++):null!=o&&console.error(`${$t} renderer for ${r.type} returned a non-Node value — skipped`)}catch(t){console.error(`${$t} renderer for ${r.type} threw`,t)}else console.info(`${$t} no renderer for ${r.type} — skipped`)}return{fragment:i,rendered:n}}(r,o,y);if(0===c)return Pt(t,"empty"),void Ft(t,"callimacus:empty",{chapter:n});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(a),Pt(t,"ready"),Ft(t,"callimacus:ready",{chapter:n,blocks:r,rendered:c})}catch(e){Pt(t,"error"),Ft(t,"callimacus:error",{error:e});const{code:s,message:i}=e instanceof _t?e:{code:"error",message:String(e)};console.error(`${$t} ${s}: ${i} — your markup is untouched`)}finally{u=!1}}}async function k(t){if(""!==t)return w(()=>({inputEvent:{type:"question",data:{value:t}},...v()}))}async function R(t,e={}){return w(()=>function(t,e={}){const{block:s,payload:i,submissionId:n,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==s&&{nodeKey:s},...void 0!==i&&{payload:i},...void 0!==n&&{submissionId:n},...void 0!==r&&{value:r}}},...o}}(t,{...e,...v(e)}))}async function E(t,e={}){return w(()=>function(t,e={}){if(void 0!==t&&t.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===t?{}:{value:t}},...e}}(t,v(e)))}async function O(t){return!(!l&&p)||new Promise(e=>{const s=()=>{clearTimeout(i),e(!0)},i=setTimeout(()=>{f.delete(s),e(!1)},t);f.add(s)})}async function T(t="",e={}){const s={suggestions:[]},i=g(),n=e.timeoutMs??4e3;if(!i.suggest||!await O(n))return s;const{language:r,storyId:o}=v(e);return i.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:n})}const A={ask:k,sendInteraction:R,openLanding:E,suggest:T,ctx:o,get state(){return t.dataset.callimacusState},get storyId(){return d},resetStory(){d=void 0}};t.callimacus=A,Ft(t,"callimacus:mounted",A),function(t,e){const{dataset:s}=t,i=""===s.interaction?void 0:s.interaction,n=""===s.prompt?void 0:s.prompt,{landing:r}=s,o=[void 0===i?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===n?void 0:"data-prompt"].filter(t=>void 0!==t);o.length>1&&console.warn(`${$t} ${o.join(", ")} each open the first round — using ${o[0]}`);if(void 0!==i){const t=""===s.interactionValue?void 0:s.interactionValue,n=qt(s.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(i,{...void 0!==t&&{value:t},...void 0!==n&&{payload:n}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==n&&e.ask(n)}(t,A)}(t,e)}catch(e){Pt(t,"error"),Ft(t,"callimacus:error",{error:e}),console.error(`${$t} mount failed — your markup is untouched`,e)}}}function Yt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Wt(s,e)}function Jt(){document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&Yt(t.target)}),Yt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Jt):Jt()}();
21
+ const vt="chapter-event",wt="story-created",kt="error",Rt="server-response",Et="client-ready",Ot="user-interaction",Tt=4,At={debug:0,info:1,warn:2,error:3,silent:4},Ct=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:s}=this.config,i=void 0===s||""===s?e:[s,...e];console[t](...i)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function St(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=[...e].map(t=>t.toString(16).padStart(2,"0"));return[s.slice(0,4).join(""),s.slice(4,6).join(""),s.slice(6,8).join(""),s.slice(8,10).join(""),s.slice(10,16).join("")].join("-")}var Nt,Bt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story",t.SUGGEST="suggest"}(Nt||(Nt={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Bt||(Bt={}));const xt={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class It{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??xt.minVisibilityRatio;this.config={productSelector:t.productSelector??xt.productSelector,blockSelector:t.blockSelector??xt.blockSelector,maxTrackedElements:t.maxTrackedElements??xt.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void Ct.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),i=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),i=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const s=this.resolveElementId(t),i=this.resolveBlockId(t),n=this.createTrackingKey(s,i),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==n&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,n),this.elementRefs.set(n,t),this.elements.set(n,{id:s,blockId:i,trackingKey:n,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),i=this.blockKeys.get(t),n=s;void 0!==i&&""!==i&&i!==n&&(this.blocks.delete(i),this.blockRefs.delete(i)),this.blockKeys.set(t,n),this.blockRefs.set(n,t),this.blocks.set(n,{id:s,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),s=t.width*t.height;if(s<=0)return 0;const i=window.innerWidth*window.innerHeight,n=i>0?Math.min(s,i):s;return Math.min(1,Math.max(0,e/n))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],s=Date.now();for(const[e,s]of this.elements){const i=this.elementRefs.get(e);i?.isConnected?s.visibilityRatio<=0||t.push({blockId:s.blockId,element:{id:s.id,bounds:s.bounds,isVisible:s.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:s.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,s]of this.blocks){const i=this.blockRefs.get(t);i?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const i=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...i.flatMap(t=>t.blockId??[])])],elements:i.map(t=>t.element)}}}class Ut{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=xt;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{Ct.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{Ct.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:s,reason:i}=e;return"number"==typeof s?{code:s,..."string"==typeof i&&{reason:i}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(Ct.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{Ct.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{Ct.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{Ct.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{Ct.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{Ct.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(Ct.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,Ct.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){Ct.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return Ct.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new It(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),s=new URL("thamyr",e).pathname;return{origin:e.origin,path:s}}connect(t="wss://localhost:4000",e,s){this.socket&&(Ct.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const i=this.socketEndpoint(t);let n;"undefined"!=typeof window&&void 0!==globalThis.location&&(n=globalThis.location.href);const r="undefined"==typeof document?void 0:function(t){const e=t.split("; ").find(t=>t.startsWith("intent_sid="))?.slice(11);return void 0===e||""===e?void 0:e}(document.cookie),o={...void 0!==n&&""!==n&&{referrer:n},...void 0!==r&&{intentSid:r},...s};Ct.info("Connecting to Thamyr at",i),this.socket=bt(i.origin,{path:i.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:o}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),Ct.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...xt,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new It(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void Ct.error("Socket is not connected. Cannot send interaction.");if(t===Nt.SUGGEST)return void Ct.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Nt.BACK_FROM_ROUND&&void 0===e.chapterId)return void Ct.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},i={id:St()};this.socket.emit(Ot,{type:s.type,payload:s.payload},i.id)}async suggest(t,e={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(t){const e=t?.suggestions;return{suggestions:Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}}(await this.socket.timeout(e.timeoutMs??4e3).emitWithAck(Ot,{type:Nt.SUGGEST,payload:t}))}catch(t){return Ct.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const jt="https://api.callimacus.ai",Lt="/cart/add.js",$t="[callimacus]";class _t extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function Dt(t){return qt(t,"[data-callimacus-settings]","using {}")??{}}function qt(t,e,s){if(void 0!==t&&""!==t)try{const i=JSON.parse(t);if("object"==typeof i&&null!==i&&!Array.isArray(i))return i;console.warn(`${$t} ${e} must be a JSON object — ${s}`)}catch(t){console.warn(`${$t} ${e} is not valid JSON — ${s}`,t)}}function Mt(t,e){return void 0===t||""===t?e:t}function Vt(t){return`server_${t.code??"error"}`}function Pt(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Ft(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Ht(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Kt(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${$t} invalid data-language "${e}" — formatting with "en"`),e="en"}const s=new Map;const i=function(t,e){let s;try{s=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{s=void 0}const i=void 0!==s&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(s)?s:e;try{return Intl.getCanonicalLocales(i)[0]??i}catch{return i}}(t.rootUrl,t.language);async function n(e,s,n,r={}){const o="string"==typeof s?s:s?.id,{clientId:a}=t;if(void 0===o||""===o)throw new _t("send_failed","The item has no id to look up");if(void 0===a||""===a)throw new _t("send_failed","No client id to look up with");const c=new AbortController,h=setTimeout(()=>{c.abort()},n.timeoutMs??1e4);try{let s;try{s=await fetch(`${new URL("api/v3",t.endpoint).href}/skesis/query/${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"x-sl-access-token":a},body:JSON.stringify({anchorId:o,locale:n.locale??i,...r}),signal:c.signal})}catch(t){throw new _t("lookup_unreachable","Could not reach the catalogue",{cause:t})}if(!s.ok)throw new _t(`server_${s.status}`,`The catalogue refused the lookup (HTTP ${s.status})`);return await s.json().catch(t=>{throw new _t("lookup_unreachable","The catalogue sent an unreadable answer",{cause:t})})}finally{clearTimeout(h)}}const r=t=>(Array.isArray(t)?t:[]).filter(t=>"object"==typeof t?.item).map(t=>void 0===t.score?t.item:{...t.item,score:t.score});return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of Ht(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of Ht(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(i){const n="number"==typeof i?i:i?.amount;if("number"!=typeof n)return"";const r="object"==typeof i?i?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!s.has(t))try{s.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${$t} invalid currency code "${t}" — showing bare amounts`),s.set(t,void 0)}return s.get(t)}(o)?.format(n)??n.toFixed(2)},productUrl(e){const s=e?.fields?.["shopify-handle"];if(void 0===s||""===s)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${s}`},imageUrl(t,{width:e=800,index:s=0}={}){const i=t?.fields?.images?.[s]?.url;return void 0===i||""===i?void 0:`${i.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],s=e.find(t=>t.orderable)??e[0];return void 0===s?.id?void 0:String(s.id).split("/").pop()},async addToCart(e,s=1){let i;try{i=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:s}]})})}catch(t){throw new _t("cart_unreachable","Could not reach the cart",{cause:t})}const n=await i.json().catch(()=>(console.warn(`${$t} cart response was not JSON (HTTP ${i.status})`),{}));if(!i.ok){const{description:t,message:e}=n??{};throw new _t("cart_rejected",t??e??`Could not add to cart (HTTP ${i.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:n})),n},async similar(t,{topK:e,...s}={}){const i=await n("similar",t,s,void 0===e?{}:{topK:e});return r(i?.hits)},async related(t,e={}){const s=await n("related",t,e)??{};return{related:r(s.related),siblingColors:r(s.siblingColors),usedFallback:!0===s.usedFallback}}})}function zt(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const s=e;return s?.type===t&&"function"==typeof s.render})}function Wt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,i={clientId:s.clientId,endpoint:Mt(s.endpoint,jt),language:Mt(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:Mt(s.rootUrl,"/"),cartAddUrl:Mt(s.cartAddUrl,Lt),settings:Dt(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void Pt(t,"design-mode");if(void 0===i.clientId||""===i.clientId)return Pt(t,"error"),void console.warn(`${$t} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${$t} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:n}=i,r=e.roundTimeoutMs??45e3,o=Kt(i),a=new Set;let c,h,u=!1,d=""===s.storyId?void 0:s.storyId,l=!1,p=!1;const f=new Set,y=void 0!==s.uiObserver&&"false"!==s.uiObserver,m=""===s.uiObserver?void 0:s.uiObserver;function g(){return c||(c=e.transport??new Ut,y&&c.configureUiObserver?.({enabled:!0,...void 0!==m&&{productSelector:m}}),c.onConnectionStatus&&(p=!0,c.onConnectionStatus(t=>{if(l=t,t){for(const t of f)t();f.clear()}})),c.onError(t=>{h=`${Vt(t)}: ${t.message??""}`,u||console.warn(`${$t} transport error between rounds — ${h}`)}),c.onServerResponse(e=>{if(e.type!==wt)return;const s=e.story?.id;"string"==typeof s&&""!==s&&s!==d&&(d=s,Ft(t,"callimacus:story",{storyId:s}))}),c.connect(i.endpoint,{Authorization:`Bearer ${n}`},{token:n}),c)}async function b(t){const e=g();return new Promise((s,i)=>{function n(){clearTimeout(o),c(),u()}const o=setTimeout(()=>{n();i(new _t("timeout",`Callimacus did not answer in time${void 0===h?"":` (last transport error: ${h})`}`))},r),c=e.onServerResponse(e=>{if(e.type!==vt)return;const i=e.chapter;i?.status===Tt&&!a.has(i.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:s,data:i}=t;if(void 0!==s&&s!==e.type)return!1;const n=e.data;return!(void 0!==i?.interactionId&&i.interactionId!==n.interactionId||"string"==typeof i?.value&&"string"==typeof n.value&&i.value!==n.value)}(i.inputEvent,t.inputEvent)&&(a.add(i.id),n(),s(i))}),u=e.onError(t=>{n(),i(new _t(Vt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(Nt.CREATE_ROUND,t)}catch(t){n(),i(new _t("send_failed","Could not send the request",{cause:t}))}})}function v(t={}){const e=t.storyId??d;return{language:t.language??i.language,...null!=e&&{storyId:e}}}async function w(e){if(!u){u=!0;try{let s;try{s=e()}catch(t){throw new _t("send_failed",t instanceof Error?t.message:"Could not build the request",{cause:t})}const{inputEvent:i}=s;Pt(t,"loading"),Ft(t,"callimacus:loading",{value:i.data.value,inputEvent:i});const n=await b(s),r=[...n.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:a,rendered:c}=function(t,e,s=!1){const i=document.createDocumentFragment();let n=0;for(const r of t){const t=zt(r.type);if(t)try{const o=t.render(r,e);s&&o instanceof HTMLElement&&void 0===o.dataset.blockId&&(o.dataset.blockId=r.id),o instanceof Node?(i.append(o),n++):null!=o&&console.error(`${$t} renderer for ${r.type} returned a non-Node value — skipped`)}catch(t){console.error(`${$t} renderer for ${r.type} threw`,t)}else console.info(`${$t} no renderer for ${r.type} — skipped`)}return{fragment:i,rendered:n}}(r,o,y);if(0===c)return Pt(t,"empty"),void Ft(t,"callimacus:empty",{chapter:n});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(a),Pt(t,"ready"),Ft(t,"callimacus:ready",{chapter:n,blocks:r,rendered:c})}catch(e){Pt(t,"error"),Ft(t,"callimacus:error",{error:e});const{code:s,message:i}=e instanceof _t?e:{code:"error",message:String(e)};console.error(`${$t} ${s}: ${i} — your markup is untouched`)}finally{u=!1}}}async function k(t){if(""!==t)return w(()=>({inputEvent:{type:"question",data:{value:t}},...v()}))}async function R(t,e={}){return w(()=>function(t,e={}){const{block:s,payload:i,submissionId:n,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==s&&{nodeKey:s},...void 0!==i&&{payload:i},...void 0!==n&&{submissionId:n},...void 0!==r&&{value:r}}},...o}}(t,{...e,...v(e)}))}async function E(t,e={}){return w(()=>function(t,e={}){if(void 0!==t&&t.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===t?{}:{value:t}},...e}}(t,v(e)))}async function O(t){return!(!l&&p)||new Promise(e=>{const s=()=>{clearTimeout(i),e(!0)},i=setTimeout(()=>{f.delete(s),e(!1)},t);f.add(s)})}async function T(t="",e={}){const s={suggestions:[]},i=g(),n=e.timeoutMs??4e3;if(!i.suggest||!await O(n))return s;const{language:r,storyId:o}=v(e);return i.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:n})}const A={ask:k,sendInteraction:R,openLanding:E,suggest:T,ctx:o,get state(){return t.dataset.callimacusState},get storyId(){return d},resetStory(){d=void 0}};t.callimacus=A,Ft(t,"callimacus:mounted",A),function(t,e){const{dataset:s}=t,i=""===s.interaction?void 0:s.interaction,n=""===s.prompt?void 0:s.prompt,{landing:r}=s,o=[void 0===i?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===n?void 0:"data-prompt"].filter(t=>void 0!==t);o.length>1&&console.warn(`${$t} ${o.join(", ")} each open the first round — using ${o[0]}`);if(void 0!==i){const t=""===s.interactionValue?void 0:s.interactionValue,n=qt(s.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(i,{...void 0!==t&&{value:t},...void 0!==n&&{payload:n}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==n&&e.ask(n)}(t,A)}(t,e)}catch(e){Pt(t,"error"),Ft(t,"callimacus:error",{error:e}),console.error(`${$t} mount failed — your markup is untouched`,e)}}}function Yt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Wt(s,e)}function Jt(){document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&Yt(t.target)}),Yt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Jt):Jt()}();
22
22
  //# sourceMappingURL=callimacus-runtime.min.js.map