@callimacus/thamyr-liquid 4.19.0 → 4.21.0

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,20 @@
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.21.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.20.0...thamyr-core-v4.21.0) (2026-11-03)
7
+
8
+
9
+ ### Features
10
+
11
+ * **core,react,vanilla,shopify,liquid:** onWarning in every wrapper, and a logger switch for the no-code runtimes ([#885](https://github.com/callimacus/thamyr-sdk/issues/885)) ([0508523](https://github.com/callimacus/thamyr-sdk/commit/0508523d79b080c1bd7b5496b9bc6640f3f1a64b))
12
+
13
+ ## [4.20.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.19.0...thamyr-core-v4.20.0) (2026-11-03)
14
+
15
+
16
+ ### Features
17
+
18
+ * **shopify:** the chat's add keeps its reply, offers the option choice, and is one runner with thamyr-react ([#881](https://github.com/callimacus/thamyr-sdk/issues/881)) ([c99096c](https://github.com/callimacus/thamyr-sdk/commit/c99096c294a44a992e7d97f0d4726102df189fb7))
19
+
6
20
  ## [4.19.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.18.0...thamyr-core-v4.19.0) (2026-11-03)
7
21
 
8
22
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.21.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.20.0...thamyr-liquid-v4.21.0) (2026-11-03)
4
+
5
+
6
+ ### Features
7
+
8
+ * **core,react,vanilla,shopify,liquid:** onWarning in every wrapper, and a logger switch for the no-code runtimes ([#885](https://github.com/callimacus/thamyr-sdk/issues/885)) ([0508523](https://github.com/callimacus/thamyr-sdk/commit/0508523d79b080c1bd7b5496b9bc6640f3f1a64b))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @callimacus/thamyr-core bumped from ^4.20.0 to ^4.21.0
16
+
17
+ ## [4.20.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.19.0...thamyr-liquid-v4.20.0) (2026-11-03)
18
+
19
+
20
+ ### Miscellaneous Chores
21
+
22
+ * **thamyr-liquid:** Synchronize thamyr versions
23
+
24
+
25
+ ### Dependencies
26
+
27
+ * The following workspace dependencies were updated
28
+ * dependencies
29
+ * @callimacus/thamyr-core bumped from ^4.19.0 to ^4.20.0
30
+
3
31
  ## [4.19.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.18.0...thamyr-liquid-v4.19.0) (2026-11-03)
4
32
 
5
33
 
package/README.md CHANGED
@@ -168,6 +168,17 @@ story and announces it. The old story is left as it was.
168
168
  it across visits. Both can throw (private windows, blocked storage), hence the
169
169
  `try`: without them the experience still works, one story per page.
170
170
 
171
+ ## Seeing the SDK's warnings
172
+
173
+ The SDK's logger is off, so visitors' consoles stay quiet. Open a page with
174
+ `?callimacus_debug` in its URL, or run `localStorage.setItem('callimacus:debug', '1')`
175
+ in the console and reload, and the browser bundle turns the logger on at `warn`
176
+ when it starts. A block a round did not show because one of its contents failed
177
+ then logs `Block "saga" was not shown: its content "guide" failed (shortfall).`
178
+ The reason stays server-side: `callimacus thamyr probe` shows it.
179
+ `localStorage.removeItem('callimacus:debug')` turns it off again. Nothing in the
180
+ theme changes.
181
+
171
182
  ## Bundler usage
172
183
 
173
184
  The ESM entry exports the same runtime without the auto-mount side effect:
@@ -178,6 +189,9 @@ import {mountAll} from '@callimacus/thamyr-liquid';
178
189
  mountAll(document);
179
190
  ```
180
191
 
192
+ It leaves the logger alone: call `enableLoggerIfRequested()` from
193
+ `@callimacus/thamyr-core` before `mountAll` for the switch above.
194
+
181
195
  ## License
182
196
 
183
197
  Proprietary — licensed for use by Callimacus customers only. See
@@ -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"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>n&&s instanceof Blob?o?c(s):a(s,c):i&&(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,n)=>{if("string"!=typeof t)return{type:"message",data:f(t,n)};const i=t.charAt(0);return"b"===i?{type:"message",data:p(t.substring(1),n)}:e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,n,i,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)],n=u[t.charCodeAt(e+1)],i=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|n>>4,d[c++]=(15&n)<<4|i>>2,d[c++]=(3&i)<<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){n&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):i&&(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 n=s.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,n)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(n))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),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 n=0;for(let i=0;i<e;i++)s[i]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),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,n=this.t["$"+t];if(!n)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var i=0;i<n.length;i++)if((s=n[i])===e||s.fn===e){n.splice(i,1);break}return 0===n.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],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(s){n=0;for(var i=(s=s.slice(0)).length;n<i;++n)s[n].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 S(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class C extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}let 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 C(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),n=[];for(let t=0;t<s.length;t++){const i=l(s[t],e);if(n.push(i),"error"===i.type)break}return n})(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,n=new Array(s);let i=0;t.forEach((t,r)=>{o(t,!1,t=>{n[r]=t,++i===s&&e(n.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]=S()),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],n=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}n&&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]=S()),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 n=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(0===i){if(b(n)<1)break;const t=v(n,1);o=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(b(n)<2)break;const t=v(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(b(n)<8)break;const t=v(n,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),i=3}else{if(b(n)<r)break;const t=v(n,r);c.enqueue(l(o?t:g.decode(t),e)),i=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=m();i.readable.pipeTo(t.writable),this.U=i.writable.getWriter();const r=()=>{n.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],n=e===t.length-1;this.U.write(s).then(()=>{n&&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("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let i=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=i[o]||"";return-1!=s&&-1!=n&&(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,n){e&&(s[e]=n)}),s}(0,r.query),r}const W="function"==typeof addEventListener&&"function"==typeof removeEventListener,z=[];W&&addEventListener("offline",()=>{z.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,n;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!==(n=e.transportImplementations)&&void 0!==n?n: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,n=s.length;t<n;t++){let n=s[t].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}(this.opts.query)),W&&(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"})},z.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 n=()=>{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 i(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",n),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",n),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 n=this.writeBuffer[s].data;if(n&&(t+="string"==typeof(e=n)?function(t){let e=0,s=0;for(let n=0,i=t.length;n<i;n++)e=t.charCodeAt(n),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(n++,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,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),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(),W&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=z.indexOf(this.$);-1!==t&&z.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,n=t;return n.data=st(s,e),n.attachments=e.length,{packet:n,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 n=0;n<t.length;n++)s[n]=st(t[n],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 n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=st(t[s],e));return n}return t}function nt(t,e){return t.data=it(t.data,e),delete t.attachments,t}function it(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]=it(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=it(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 n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(n,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(i);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 n=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(n,e)}else s.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=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(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}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=nt(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),n=e.buffers;return n.unshift(s),n}},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,n,i;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===(n=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i.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 n=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const i=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"))},n),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,n)=>{const i=(t,e)=>t?n(t):s(e);i.withError=!0,e.push(i),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,...n)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...n)),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(...n){s||(s=!0,e.packet({type:ot.ACK,id:t,data:n}))}}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 n=e.parser||dt;this.encoder=new n.Encoder,this.decoder=new n.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 n=lt(e,"open",function(){s.onopen(),t&&t()}),i=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",i);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(n),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 n=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),n=K(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,i=s.id,r=s.path,o=gt[i]&&r in gt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(n,e):(gt[i]||(gt[i]=new mt(n,e)),a=gt[i]),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"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>n&&s instanceof Blob?o?c(s):a(s,c):i&&(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,n)=>{if("string"!=typeof t)return{type:"message",data:f(t,n)};const i=t.charAt(0);return"b"===i?{type:"message",data:p(t.substring(1),n)}:e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,n,i,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)],n=u[t.charCodeAt(e+1)],i=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|n>>4,d[c++]=(15&n)<<4|i>>2,d[c++]=(3&i)<<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){n&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):i&&(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 n=s.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,n)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(n))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),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 n=0;for(let i=0;i<e;i++)s[i]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),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,n=this.t["$"+t];if(!n)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var i=0;i<n.length;i++)if((s=n[i])===e||s.fn===e){n.splice(i,1);break}return 0===n.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],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(s){n=0;for(var i=(s=s.slice(0)).length;n<i;++n)s[n].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 S(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}let C=class extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}};class N 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 C(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),n=[];for(let t=0;t<s.length;t++){const i=l(s[t],e);if(n.push(i),"error"===i.type)break}return n})(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,n=new Array(s);let i=0;t.forEach((t,r)=>{o(t,!1,t=>{n[r]=t,++i===s&&e(n.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]=S()),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 L 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 j=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 n=this.O=this.createRequest(s);try{n.open(this.v,this.m,!0);try{if(this.p.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(n.timeout=this.p.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof n.status?n.status:0)},0))},n.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 j.requests)j.requests.hasOwnProperty(t)&&j.requests[t].abort()}j.requestsCount=0,j.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],n=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}n&&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]=S()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const P=R.WebSocket||R.MozWebSocket;const V={websocket:class extends M{createSocket(t,e,s){return q?new P(t,e,s):e?new P(t,e):new P(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 n=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(0===i){if(b(n)<1)break;const t=v(n,1);o=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(b(n)<2)break;const t=v(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(b(n)<8)break;const t=v(n,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),i=3}else{if(b(n)<r)break;const t=v(n,r);c.enqueue(l(o?t:g.decode(t),e)),i=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=m();i.readable.pipeTo(t.writable),this.U=i.writable.getWriter();const r=()=>{n.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],n=e===t.length-1;this.U.write(s).then(()=>{n&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends L{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new j(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("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let i=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=i[o]||"";return-1!=s&&-1!=n&&(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,n){e&&(s[e]=n)}),s}(0,r.query),r}const W="function"==typeof addEventListener&&"function"==typeof removeEventListener,z=[];W&&addEventListener("offline",()=>{z.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,n;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!==(n=e.transportImplementations)&&void 0!==n?n: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=V),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,n=s.length;t<n;t++){let n=s[t].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}(this.opts.query)),W&&(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"})},z.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 n=()=>{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 i(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",n),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",n),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 n=this.writeBuffer[s].data;if(n&&(t+="string"==typeof(e=n)?function(t){let e=0,s=0;for(let n=0,i=t.length;n<i;n++)e=t.charCodeAt(n),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(n++,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,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),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(),W&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=z.indexOf(this.$);-1!==t&&z.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,n=t;return n.data=st(s,e),n.attachments=e.length,{packet:n,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 n=0;n<t.length;n++)s[n]=st(t[n],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 n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=st(t[s],e));return n}return t}function nt(t,e){return t.data=it(t.data,e),delete t.attachments,t}function it(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]=it(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=it(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 n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(n,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(i);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 n=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(n,e)}else s.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=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(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}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=nt(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),n=e.buffers;return n.unshift(s),n}},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,n,i;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===(n=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i.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 n=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const i=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"))},n),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,n)=>{const i=(t,e)=>t?n(t):s(e);i.withError=!0,e.push(i),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,...n)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...n)),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(...n){s||(s=!0,e.packet({type:ot.ACK,id:t,data:n}))}}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 n=e.parser||dt;this.encoder=new n.Encoder,this.decoder=new n.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 n=lt(e,"open",function(){s.onopen(),t&&t()}),i=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",i);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(n),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 n=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),n=K(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,i=s.id,r=s.path,o=gt[i]&&r in gt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(n,e):(gt[i]||(gt[i]=new mt(n,e)),a=gt[i]),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},St=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,n=void 0===s||""===s?e:[s,...e];console[t](...n)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){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 St.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),n=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),n=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,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),n=this.resolveBlockId(t),i=this.createTrackingKey(s,n),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==i&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,i),this.elementRefs.set(i,t),this.elements.set(i,{id:s,blockId:n,trackingKey:i,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),n=this.blockKeys.get(t),i=s;void 0!==n&&""!==n&&n!==i&&(this.blocks.delete(n),this.blockRefs.delete(n)),this.blockKeys.set(t,i),this.blockRefs.set(i,t),this.blocks.set(i,{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 n=window.innerWidth*window.innerHeight,i=n>0?Math.min(s,n):s;return Math.min(1,Math.max(0,e/i))}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 n=this.elementRefs.get(e);n?.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 n=this.blockRefs.get(t);n?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const n=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...n.flatMap(t=>t.blockId??[])])],elements:n.map(t=>t.element)}}}class Ut{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=xt;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{St.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{St.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:n}=e;return"number"==typeof s?{code:s,..."string"==typeof n&&{reason:n}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(St.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{St.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{St.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{St.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{St.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{St.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{"chapter-event"===t.type&&this.notifyWarningListeners(function(t,e){return(t.warnings??[]).filter(s=>{const n=`${t.id}:${s.block}:${s.content}`;return!e.has(n)&&(e.add(n),!0)})}(t.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){St.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&&(St.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,St.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){St.error("Error in error listener:",t)}})}notifyWarningListeners(t){for(const e of t)0===this.warningListeners.size&&St.warn(`Block "${e.block}" was not shown: its content "${e.content}" failed (${e.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(t=>{try{t(e)}catch(t){St.error("Error in warning 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 St.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&&(St.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const n=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=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!==i&&""!==i&&{referrer:i},...void 0!==r&&{intentSid:r},...s};St.info("Connecting to Thamyr at",n),this.socket=bt(n.origin,{path:n.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),St.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 St.error("Socket is not connected. Cannot send interaction.");if(t===Nt.SUGGEST)return void St.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Nt.BACK_FROM_ROUND&&void 0===e.chapterId)return void St.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},n={id:Ct()};this.socket.emit(Ot,{type:s.type,payload:s.payload},n.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 St.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)}}onWarning(t){return this.warningListeners.add(t),()=>{this.warningListeners.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 n=JSON.parse(t);if("object"==typeof n&&null!==n&&!Array.isArray(n))return n;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 n=function(t,e){let s;try{s=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{s=void 0}const n=void 0!==s&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(s)?s:e;try{return Intl.getCanonicalLocales(n)[0]??n}catch{return n}}(t.rootUrl,t.language);async function i(e,s,i,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()},i.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:i.locale??n,...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(n){const i="number"==typeof n?n:n?.amount;if("number"!=typeof i)return"";const r="object"==typeof n?n?.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(i)??i.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 n=t?.fields?.images?.[s]?.url;return void 0===n||""===n?void 0:`${n.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 n;try{n=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 i=await n.json().catch(()=>(console.warn(`${$t} cart response was not JSON (HTTP ${n.status})`),{}));if(!n.ok){const{description:t,message:e}=i??{};throw new _t("cart_rejected",t??e??`Could not add to cart (HTTP ${n.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i})),i},async similar(t,{topK:e,...s}={}){const n=await i("similar",t,s,void 0===e?{}:{topK:e});return r(n?.hits)},async related(t,e={}){const s=await i("related",t,e)??{};return{related:r(s.related),siblingColors:r(s.siblingColors),usedFallback:!0===s.usedFallback}}})}function Wt(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 zt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,n={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===n.clientId||""===n.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:i}=n,r=e.roundTimeoutMs??45e3,o=Kt(n),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(n.endpoint,{Authorization:`Bearer ${i}`},{token:i}),c)}async function b(t){const e=g();return new Promise((s,n)=>{function i(){clearTimeout(o),c(),u()}const o=setTimeout(()=>{i();n(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 n=e.chapter;n?.status===Tt&&!a.has(n.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:s,data:n}=t;if(void 0!==s&&s!==e.type)return!1;const i=e.data;return!(void 0!==n?.interactionId&&n.interactionId!==i.interactionId||"string"==typeof n?.value&&"string"==typeof i.value&&n.value!==i.value)}(n.inputEvent,t.inputEvent)&&(a.add(n.id),i(),s(n))}),u=e.onError(t=>{i(),n(new _t(Vt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(Nt.CREATE_ROUND,t)}catch(t){i(),n(new _t("send_failed","Could not send the request",{cause:t}))}})}function v(t={}){const e=t.storyId??d;return{language:t.language??n.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:n}=s;Pt(t,"loading"),Ft(t,"callimacus:loading",{value:n.data.value,inputEvent:n});const i=await b(s),r=[...i.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:a,rendered:c}=function(t,e,s=!1){const n=document.createDocumentFragment();let i=0;for(const r of t){const t=Wt(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?(n.append(o),i++):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:n,rendered:i}}(r,o,y);if(0===c)return Pt(t,"empty"),void Ft(t,"callimacus:empty",{chapter:i});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(a),Pt(t,"ready"),Ft(t,"callimacus:ready",{chapter:i,blocks:r,rendered:c})}catch(e){Pt(t,"error"),Ft(t,"callimacus:error",{error:e});const{code:s,message:n}=e instanceof _t?e:{code:"error",message:String(e)};console.error(`${$t} ${s}: ${n} — 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:n,submissionId:i,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==s&&{nodeKey:s},...void 0!==n&&{payload:n},...void 0!==i&&{submissionId:i},...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(n),e(!0)},n=setTimeout(()=>{f.delete(s),e(!1)},t);f.add(s)})}async function T(t="",e={}){const s={suggestions:[]},n=g(),i=e.timeoutMs??4e3;if(!n.suggest||!await O(i))return s;const{language:r,storyId:o}=v(e);return n.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:i})}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,n=""===s.interaction?void 0:s.interaction,i=""===s.prompt?void 0:s.prompt,{landing:r}=s,o=[void 0===n?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===i?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!==n){const t=""===s.interactionValue?void 0:s.interactionValue,i=qt(s.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(n,{...void 0!==t&&{value:t},...void 0!==i&&{payload:i}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==i&&e.ask(i)}(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]"))zt(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},St=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,n=void 0===s||""===s?e:[s,...e];console[t](...n)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){let t,e="";try{e=globalThis.location.search}catch{}try{t=localStorage}catch{}(function(t,e){if(new URLSearchParams(t).has("callimacus_debug"))return!0;try{return null!==(e?.getItem("callimacus:debug")??null)}catch{return!1}})(e,t)&&St.configure({enabled:!0,level:"warn"})}function Nt(){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 Bt,xt;!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"}(Bt||(Bt={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(xt||(xt={}));const It={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class Ut{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??It.minVisibilityRatio;this.config={productSelector:t.productSelector??It.productSelector,blockSelector:t.blockSelector??It.blockSelector,maxTrackedElements:t.maxTrackedElements??It.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 St.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),n=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),n=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,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),n=this.resolveBlockId(t),i=this.createTrackingKey(s,n),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==i&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,i),this.elementRefs.set(i,t),this.elements.set(i,{id:s,blockId:n,trackingKey:i,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),n=this.blockKeys.get(t),i=s;void 0!==n&&""!==n&&n!==i&&(this.blocks.delete(n),this.blockRefs.delete(n)),this.blockKeys.set(t,i),this.blockRefs.set(i,t),this.blocks.set(i,{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 n=window.innerWidth*window.innerHeight,i=n>0?Math.min(s,n):s;return Math.min(1,Math.max(0,e/i))}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 n=this.elementRefs.get(e);n?.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 n=this.blockRefs.get(t);n?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const n=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...n.flatMap(t=>t.blockId??[])])],elements:n.map(t=>t.element)}}}class Lt{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=It;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{St.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{St.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:n}=e;return"number"==typeof s?{code:s,..."string"==typeof n&&{reason:n}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(St.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{St.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{St.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{St.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{St.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{St.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{"chapter-event"===t.type&&this.notifyWarningListeners(function(t,e){return(t.warnings??[]).filter(s=>{const n=`${t.id}:${s.block}:${s.content}`;return!e.has(n)&&(e.add(n),!0)})}(t.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){St.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&&(St.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,St.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){St.error("Error in error listener:",t)}})}notifyWarningListeners(t){for(const e of t)0===this.warningListeners.size&&St.warn(`Block "${e.block}" was not shown: its content "${e.content}" failed (${e.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(t=>{try{t(e)}catch(t){St.error("Error in warning 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 St.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new Ut(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&&(St.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const n=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=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!==i&&""!==i&&{referrer:i},...void 0!==r&&{intentSid:r},...s};St.info("Connecting to Thamyr at",n),this.socket=bt(n.origin,{path:n.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),St.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...It,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 Ut(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void St.error("Socket is not connected. Cannot send interaction.");if(t===Bt.SUGGEST)return void St.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Bt.BACK_FROM_ROUND&&void 0===e.chapterId)return void St.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},n={id:Nt()};this.socket.emit(Ot,{type:s.type,payload:s.payload},n.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:Bt.SUGGEST,payload:t}))}catch(t){return St.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)}}onWarning(t){return this.warningListeners.add(t),()=>{this.warningListeners.delete(t)}}}const jt="https://api.callimacus.ai",$t="/cart/add.js",_t="[callimacus]";class Dt extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function qt(t){return Mt(t,"[data-callimacus-settings]","using {}")??{}}function Mt(t,e,s){if(void 0!==t&&""!==t)try{const n=JSON.parse(t);if("object"==typeof n&&null!==n&&!Array.isArray(n))return n;console.warn(`${_t} ${e} must be a JSON object — ${s}`)}catch(t){console.warn(`${_t} ${e} is not valid JSON — ${s}`,t)}}function Pt(t,e){return void 0===t||""===t?e:t}function Vt(t){return`server_${t.code??"error"}`}function Ft(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Ht(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Kt(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Wt(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 n=function(t,e){let s;try{s=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{s=void 0}const n=void 0!==s&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(s)?s:e;try{return Intl.getCanonicalLocales(n)[0]??n}catch{return n}}(t.rootUrl,t.language);async function i(e,s,i,r={}){const o="string"==typeof s?s:s?.id,{clientId:a}=t;if(void 0===o||""===o)throw new Dt("send_failed","The item has no id to look up");if(void 0===a||""===a)throw new Dt("send_failed","No client id to look up with");const c=new AbortController,h=setTimeout(()=>{c.abort()},i.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:i.locale??n,...r}),signal:c.signal})}catch(t){throw new Dt("lookup_unreachable","Could not reach the catalogue",{cause:t})}if(!s.ok)throw new Dt(`server_${s.status}`,`The catalogue refused the lookup (HTTP ${s.status})`);return await s.json().catch(t=>{throw new Dt("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 Kt(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 Kt(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(n){const i="number"==typeof n?n:n?.amount;if("number"!=typeof i)return"";const r="object"==typeof n?n?.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(i)??i.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 n=t?.fields?.images?.[s]?.url;return void 0===n||""===n?void 0:`${n.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 n;try{n=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 Dt("cart_unreachable","Could not reach the cart",{cause:t})}const i=await n.json().catch(()=>(console.warn(`${_t} cart response was not JSON (HTTP ${n.status})`),{}));if(!n.ok){const{description:t,message:e}=i??{};throw new Dt("cart_rejected",t??e??`Could not add to cart (HTTP ${n.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i})),i},async similar(t,{topK:e,...s}={}){const n=await i("similar",t,s,void 0===e?{}:{topK:e});return r(n?.hits)},async related(t,e={}){const s=await i("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 Yt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,n={clientId:s.clientId,endpoint:Pt(s.endpoint,jt),language:Pt(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:Pt(s.rootUrl,"/"),cartAddUrl:Pt(s.cartAddUrl,$t),settings:qt(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void Ft(t,"design-mode");if(void 0===n.clientId||""===n.clientId)return Ft(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:i}=n,r=e.roundTimeoutMs??45e3,o=Wt(n),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 Lt,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,Ht(t,"callimacus:story",{storyId:s}))}),c.connect(n.endpoint,{Authorization:`Bearer ${i}`},{token:i}),c)}async function b(t){const e=g();return new Promise((s,n)=>{function i(){clearTimeout(o),c(),u()}const o=setTimeout(()=>{i();n(new Dt("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 n=e.chapter;n?.status===Tt&&!a.has(n.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:s,data:n}=t;if(void 0!==s&&s!==e.type)return!1;const i=e.data;return!(void 0!==n?.interactionId&&n.interactionId!==i.interactionId||"string"==typeof n?.value&&"string"==typeof i.value&&n.value!==i.value)}(n.inputEvent,t.inputEvent)&&(a.add(n.id),i(),s(n))}),u=e.onError(t=>{i(),n(new Dt(Vt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(Bt.CREATE_ROUND,t)}catch(t){i(),n(new Dt("send_failed","Could not send the request",{cause:t}))}})}function v(t={}){const e=t.storyId??d;return{language:t.language??n.language,...null!=e&&{storyId:e}}}async function w(e){if(!u){u=!0;try{let s;try{s=e()}catch(t){throw new Dt("send_failed",t instanceof Error?t.message:"Could not build the request",{cause:t})}const{inputEvent:n}=s;Ft(t,"loading"),Ht(t,"callimacus:loading",{value:n.data.value,inputEvent:n});const i=await b(s),r=[...i.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:a,rendered:c}=function(t,e,s=!1){const n=document.createDocumentFragment();let i=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?(n.append(o),i++):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:n,rendered:i}}(r,o,y);if(0===c)return Ft(t,"empty"),void Ht(t,"callimacus:empty",{chapter:i});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(a),Ft(t,"ready"),Ht(t,"callimacus:ready",{chapter:i,blocks:r,rendered:c})}catch(e){Ft(t,"error"),Ht(t,"callimacus:error",{error:e});const{code:s,message:n}=e instanceof Dt?e:{code:"error",message:String(e)};console.error(`${_t} ${s}: ${n} — 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:n,submissionId:i,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==s&&{nodeKey:s},...void 0!==n&&{payload:n},...void 0!==i&&{submissionId:i},...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(n),e(!0)},n=setTimeout(()=>{f.delete(s),e(!1)},t);f.add(s)})}async function T(t="",e={}){const s={suggestions:[]},n=g(),i=e.timeoutMs??4e3;if(!n.suggest||!await O(i))return s;const{language:r,storyId:o}=v(e);return n.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:i})}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,Ht(t,"callimacus:mounted",A),function(t,e){const{dataset:s}=t,n=""===s.interaction?void 0:s.interaction,i=""===s.prompt?void 0:s.prompt,{landing:r}=s,o=[void 0===n?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===i?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!==n){const t=""===s.interactionValue?void 0:s.interactionValue,i=Mt(s.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(n,{...void 0!==t&&{value:t},...void 0!==i&&{payload:i}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==i&&e.ask(i)}(t,A)}(t,e)}catch(e){Ft(t,"error"),Ht(t,"callimacus:error",{error:e}),console.error(`${_t} mount failed — your markup is untouched`,e)}}}function Jt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Yt(s,e)}function Gt(){Ct(),document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&Jt(t.target)}),Jt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Gt):Gt()}();
22
22
  //# sourceMappingURL=callimacus-runtime.min.js.map