@callimacus/thamyr-shopify 4.13.0 → 4.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.core.md +14 -0
- package/CHANGELOG.md +28 -0
- package/dist/browser/callimacus.min.js +2 -2
- package/dist/browser/callimacus.min.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +2 -2
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.13.2](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.1...thamyr-core-v4.13.2) (2026-10-28)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
* **core:** the socket handshake carries the visitor's intent session id, so rounds get session intent on any API host ([#859](https://github.com/callimacus/thamyr-sdk/issues/859)) ([8270ac2](https://github.com/callimacus/thamyr-sdk/commit/8270ac2a90caacc53e7c89698ccc11ca3b5c81f2))
|
|
12
|
+
|
|
13
|
+
## [4.13.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.13.0...thamyr-core-v4.13.1) (2026-10-27)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
### Bug Fixes
|
|
17
|
+
|
|
18
|
+
* **shopify:** the bag keeps one key, cart calls run one at a time, checkout goes only to https ([#857](https://github.com/callimacus/thamyr-sdk/issues/857)) ([dde6d17](https://github.com/callimacus/thamyr-sdk/commit/dde6d1790ab124f7bd83e23ab08adad7236644f4))
|
|
19
|
+
|
|
6
20
|
## [4.13.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.12.0...thamyr-core-v4.13.0) (2026-10-27)
|
|
7
21
|
|
|
8
22
|
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [4.13.2](https://github.com/callimacus/thamyr-sdk/compare/thamyr-shopify-v4.13.1...thamyr-shopify-v4.13.2) (2026-10-28)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Miscellaneous Chores
|
|
7
|
+
|
|
8
|
+
* **thamyr-shopify:** Synchronize thamyr versions
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Dependencies
|
|
12
|
+
|
|
13
|
+
* The following workspace dependencies were updated
|
|
14
|
+
* devDependencies
|
|
15
|
+
* @callimacus/thamyr-core bumped from ^4.13.1 to ^4.13.2
|
|
16
|
+
|
|
17
|
+
## [4.13.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-shopify-v4.13.0...thamyr-shopify-v4.13.1) (2026-10-27)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
### Miscellaneous Chores
|
|
21
|
+
|
|
22
|
+
* **thamyr-shopify:** Synchronize thamyr versions
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
### Dependencies
|
|
26
|
+
|
|
27
|
+
* The following workspace dependencies were updated
|
|
28
|
+
* devDependencies
|
|
29
|
+
* @callimacus/thamyr-core bumped from ^4.13.0 to ^4.13.1
|
|
30
|
+
|
|
3
31
|
## [4.13.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-shopify-v4.12.0...thamyr-shopify-v4.13.0) (2026-10-27)
|
|
4
32
|
|
|
5
33
|
|
|
@@ -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 Ge=Object.create(null);Ge.open="0",Ge.close="1",Ge.ping="2",Ge.pong="3",Ge.message="4",Ge.upgrade="5",Ge.noop="6";const Xe=Object.create(null);Object.keys(Ge).forEach(t=>{Xe[Ge[t]]=t});const Ze={type:"error",data:"parser error"},Qe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tn="function"==typeof ArrayBuffer,en=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,nn=({type:t,data:e},n,o)=>Qe&&e instanceof Blob?n?o(e):on(e,o):tn&&(e instanceof ArrayBuffer||en(e))?n?o(e):on(new Blob([e]),o):o(Ge[t]+(e||"")),on=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function rn(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let sn;const an="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)an["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const cn="function"==typeof ArrayBuffer,dn=(t,e)=>{if("string"!=typeof t)return{type:"message",data:un(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:ln(t.substring(1),e)}:Xe[n]?t.length>1?{type:Xe[n],data:t.substring(1)}:{type:Xe[n]}:Ze},ln=(t,e)=>{if(cn){const n=(t=>{let e,n,o,r,i,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);const d=new ArrayBuffer(s),l=new Uint8Array(d);for(e=0;e<a;e+=4)n=an[t.charCodeAt(e)],o=an[t.charCodeAt(e+1)],r=an[t.charCodeAt(e+2)],i=an[t.charCodeAt(e+3)],l[c++]=n<<2|o>>4,l[c++]=(15&o)<<4|r>>2,l[c++]=(3&r)<<6|63&i;return d})(t);return un(n,e)}return{base64:!0,data:t}},un=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,hn=String.fromCharCode(30);function pn(){return new TransformStream({transform(t,e){!function(t,e){Qe&&t.data instanceof Blob?t.data.arrayBuffer().then(rn).then(e):tn&&(t.data instanceof ArrayBuffer||en(t.data))?e(rn(t.data)):nn(t,!1,t=>{sn||(sn=new TextEncoder),e(sn.encode(t))})}(t,n=>{const o=n.length;let r;if(o<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,o);else if(o<65536){r=new Uint8Array(3);const t=new DataView(r.buffer);t.setUint8(0,126),t.setUint16(1,o)}else{r=new Uint8Array(9);const t=new DataView(r.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(o))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(n)})}})}let fn;function mn(t){return t.reduce((t,e)=>t+e.length,0)}function gn(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let o=0;for(let r=0;r<e;r++)n[r]=t[0][o++],o===t[0].length&&(t.shift(),o=0);return t.length&&o<t[0].length&&(t[0]=t[0].slice(o)),n}function yn(t){if(t)return function(t){for(var e in yn.prototype)t[e]=yn.prototype[e];return t}(t)}yn.prototype.on=yn.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},yn.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},yn.prototype.off=yn.prototype.removeListener=yn.prototype.removeAllListeners=yn.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var n,o=this.t["$"+t];if(!o)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var r=0;r<o.length;r++)if((n=o[r])===e||n.fn===e){o.splice(r,1);break}return 0===o.length&&delete this.t["$"+t],this},yn.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),n=this.t["$"+t],o=1;o<arguments.length;o++)e[o-1]=arguments[o];if(n){o=0;for(var r=(n=n.slice(0)).length;o<r;++o)n[o].apply(this,e)}return this},yn.prototype.emitReserved=yn.prototype.emit,yn.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},yn.prototype.hasListeners=function(t){return!!this.listeners(t).length};const bn="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),vn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function wn(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const kn=vn.setTimeout,Sn=vn.clearTimeout;function An(t,e){e.useNativeTimers?(t.setTimeoutFn=kn.bind(vn),t.clearTimeoutFn=Sn.bind(vn)):(t.setTimeoutFn=vn.setTimeout.bind(vn),t.clearTimeoutFn=vn.clearTimeout.bind(vn))}function xn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class _n extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}let Cn=class extends yn{constructor(t){super(),this.writable=!1,An(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new _n(t,e,n)),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=dn(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 n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}};class En extends Cn{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 n=t.split(hn),o=[];for(let t=0;t<n.length;t++){const r=dn(n[t],e);if(o.push(r),"error"===r.type)break}return o})(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 n=t.length,o=new Array(n);let r=0;t.forEach((t,i)=>{nn(t,!1,t=>{o[i]=t,++r===n&&e(o.join(hn))})})})(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]=xn()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Rn=!1;try{Rn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Tn=Rn;function On(){}class qn extends En{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.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 $n extends yn{constructor(t,e,n){super(),this.createRequest=t,An(this,n),this.p=n,this.v=n.method||"GET",this.m=e,this.k=void 0!==n.data?n.data:null,this.A()}A(){var t;const e=wn(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.p.xd;const n=this.O=this.createRequest(e);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(t){}if("POST"===this.v)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.p.cookieJar)||void 0===t||t.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(t){return void this.setTimeoutFn(()=>{this.j(t)},0)}"undefined"!=typeof document&&(this.B=$n.requestsCount++,$n.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=On,t)try{this.O.abort()}catch(t){}"undefined"!=typeof document&&delete $n.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 Nn(){for(let t in $n.requests)$n.requests.hasOwnProperty(t)&&$n.requests[t].abort()}$n.requestsCount=0,$n.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Nn):"function"==typeof addEventListener&&addEventListener("onpagehide"in vn?"pagehide":"unload",Nn,!1));const Ln=function(){const t=Bn({xdomain:!1});return t&&null!==t.responseType}();function Bn(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Tn))return new XMLHttpRequest}catch(t){}if(!e)try{return new(vn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const In="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Mn extends Cn{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=In?{}:wn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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 n=t[e],o=e===t.length-1;nn(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}o&&bn(()=>{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]=xn()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const jn=vn.WebSocket||vn.MozWebSocket;const Un={websocket:class extends Mn{createSocket(t,e,n){return In?new jn(t,e,n):e?new jn(t,e):new jn(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Cn{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){fn||(fn=new TextDecoder);const n=[];let o=0,r=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===o){if(mn(n)<1)break;const t=gn(n,1);i=!(128&~t[0]),r=127&t[0],o=r<126?3:126===r?1:2}else if(1===o){if(mn(n)<2)break;const t=gn(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),o=3}else if(2===o){if(mn(n)<8)break;const t=gn(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),i=e.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Ze);break}r=i*Math.pow(2,32)+e.getUint32(4),o=3}else{if(mn(n)<r)break;const t=gn(n,r);a.enqueue(dn(i?t:fn.decode(t),e)),o=0}if(0===r||r>t){a.enqueue(Ze);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),o=pn();o.readable.pipeTo(t.writable),this.U=o.writable.getWriter();const r=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this.U.write(i).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],o=e===t.length-1;this.U.write(n).then(()=>{o&&bn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends qn{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Ln&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new $n(Bn,this.uri(),t)}}},Fn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Dn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Pn(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),o=t.indexOf("]");-1!=n&&-1!=o&&(t=t.substring(0,n)+t.substring(n,o).replace(/:/g,";")+t.substring(o,t.length));let r=Fn.exec(t||""),i={},s=14;for(;s--;)i[Dn[s]]=r[s]||"";return-1!=n&&-1!=o&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,o){e&&(n[e]=o)}),n}(0,i.query),i}const Wn="function"==typeof addEventListener&&"function"==typeof removeEventListener,zn=[];Wn&&addEventListener("offline",()=>{zn.forEach(t=>t())},!1);class Vn extends yn{constructor(t,e={}){var n,o;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 n=Pn(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Pn(e.host).host);if(An(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===(n=e.transports)||void 0===n?void 0:n.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(o=e.transportImplementations)&&void 0!==o?o: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=Un),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={},n=t.split("&");for(let t=0,o=n.length;t<o;t++){let o=n[t].split("=");e[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return e}(this.opts.query)),Wn&&(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"})},zn.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 n=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](n)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Vn.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),n=!1;Vn.priorWebsocketSuccess=!1;const o=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Vn.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(d(),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 r(){n||(n=!0,d(),e.close(),e=null)}const i=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&r()}const d=()=>{e.removeListener("open",o),e.removeListener("error",i),e.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};e.once("open",o),e.once("error",i),e.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Vn.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 n=0;n<this.writeBuffer.length;n++){const o=this.writeBuffer[n].data;if(o&&(t+="string"==typeof(e=o)?function(t){let e=0,n=0;for(let o=0,r=t.length;o<r;o++)e=t.charCodeAt(o),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(o++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))),n>0&&t>this.L)return this.writeBuffer.slice(0,n);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,bn(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this.G("message",t,e,n),this}send(t,e,n){return this.G("message",t,e,n),this}G(t,e,n,o){if("function"==typeof e&&(o=e,e=void 0),"function"==typeof n&&(o=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{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?n():t()}):this.upgrading?n():t()),this}j(t){if(Vn.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(),Wn&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=zn.indexOf(this.$);-1!==t&&zn.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 n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}Vn.protocol=4;const Hn="function"==typeof ArrayBuffer,Kn=Object.prototype.toString,Jn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Kn.call(Blob),Yn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Kn.call(File);function Gn(t){return Hn&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||Jn&&t instanceof Blob||Yn&&t instanceof File}function Xn(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(Xn(t[e]))return!0;return!1}if(Gn(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Xn(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Xn(t[e]))return!0;return!1}function Zn(t){const e=[],n=t.data,o=t;return o.data=Qn(n,e),o.attachments=e.length,{packet:o,buffers:e}}function Qn(t,e,n){if(!t)return t;if(Gn(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let o=0;o<t.length;o++)n[o]=Qn(t[o],e);return n}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!n)return Qn(t.toJSON(),e,!0);const o={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(o[n]=Qn(t[n],e));return o}return t}function to(t,e){return t.data=eo(t.data,e),delete t.attachments,t}function eo(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 n=0;n<t.length;n++)t[n]=eo(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=eo(t[n],e));return t}const no=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var oo;!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"}(oo||(oo={}));class ro extends yn{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 n=e.type===oo.BINARY_EVENT;n||e.type===oo.BINARY_ACK?(e.type=n?oo.EVENT:oo.ACK,this.reconstructor=new io(e)):super.emitReserved("decoded",e)}else{if(!Gn(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 n={type:Number(t.charAt(0))};if(void 0===oo[n.type])throw new Error("unknown packet type "+n.type);if(n.type===oo.BINARY_EVENT||n.type===oo.BINARY_ACK){const o=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const r=t.substring(o,e);if(r!=Number(r)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const i=Number(r);if(!so(i)||i<1)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===t.charAt(e+1)){const o=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(o,e)}else n.nsp="/";const o=t.charAt(e+1);if(""!==o&&Number(o)==o){const o=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(o,e+1))}if(t.charAt(++e)){const o=this.tryParse(t.substr(e));if(!ro.isPayloadValid(n.type,o))throw new Error("invalid payload");n.data=o}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case oo.CONNECT:return ao(e);case oo.DISCONNECT:return void 0===e;case oo.CONNECT_ERROR:return"string"==typeof e||ao(e);case oo.EVENT:case oo.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===no.indexOf(e[0]));case oo.ACK:case oo.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class io{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=to(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const so=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ao(t){return"[object Object]"===Object.prototype.toString.call(t)}var co=Object.freeze({__proto__:null,protocol:5,get PacketType(){return oo},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==oo.EVENT&&t.type!==oo.ACK||!Xn(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===oo.EVENT?oo.BINARY_EVENT:oo.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==oo.BINARY_EVENT&&t.type!==oo.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=Zn(t),n=this.encodeAsString(e.packet),o=e.buffers;return o.unshift(n),o}},Decoder:ro,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||so(e))&&function(t,e){switch(t){case oo.CONNECT:return void 0===e||ao(e);case oo.DISCONNECT:return void 0===e;case oo.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===no.indexOf(e[0]));case oo.ACK:return Array.isArray(e);case oo.CONNECT_ERROR:return"string"==typeof e||ao(e);default:return!1}}(t.type,t.data);var e}});function lo(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const uo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ho extends yn{constructor(t,e,n){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,n&&n.auth&&(this.auth=n.auth),this.p=Object.assign({},n),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lo(t,"open",this.onopen.bind(this)),lo(t,"packet",this.onpacket.bind(this)),lo(t,"error",this.onerror.bind(this)),lo(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 n,o,r;if(uo.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 i={type:oo.EVENT,data:e,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this.ut(t,n),i.id=t}const s=null===(o=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===o?void 0:o.writable,a=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r.st());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}ut(t,e){var n;const o=null!==(n=this.flags.timeout)&&void 0!==n?n:this.p.ackTimeout;if(void 0===o)return void(this.acks[t]=e);const r=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"))},o),i=(...t)=>{this.io.clearTimeoutFn(r),e.apply(this,t)};i.withError=!0,this.acks[t]=i}emitWithAck(t,...e){return new Promise((n,o)=>{const r=(t,e)=>t?o(t):n(e);r.withError=!0,e.push(r),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...o)=>(this.et[0],null!==t?n.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...o)),n.pending=!1,this.ft())),this.et.push(n),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:oo.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 oo.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 oo.EVENT:case oo.BINARY_EVENT:this.onevent(t);break;case oo.ACK:case oo.BINARY_ACK:this.onack(t);break;case oo.DISCONNECT:this.ondisconnect();break;case oo.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 n of e)n.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 n=!1;return function(...o){n||(n=!0,e.packet({type:oo.ACK,id:t,data:o}))}}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:oo.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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n of e)n.apply(this,t.data)}}}function po(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}po.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},po.prototype.reset=function(){this.attempts=0},po.prototype.setMin=function(t){this.ms=t},po.prototype.setMax=function(t){this.max=t},po.prototype.setJitter=function(t){this.jitter=t};class fo extends yn{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,An(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!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new po({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const o=e.parser||co;this.encoder=new o.Encoder,this.decoder=new o.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 Vn(this.uri,this.opts);const e=this.engine,n=this;this.ht="opening",this.skipReconnect=!1;const o=lo(e,"open",function(){n.onopen(),t&&t()}),r=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},i=lo(e,"error",r);if(!1!==this.Bt){const t=this.Bt,n=this.setTimeoutFn(()=>{o(),r(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(o),this.subs.push(i),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lo(t,"ping",this.onping.bind(this)),lo(t,"data",this.ondata.bind(this)),lo(t,"error",this.onerror.bind(this)),lo(t,"close",this.onclose.bind(this)),lo(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){bn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this.rt&&!n.active&&n.connect():(n=new ho(this,t,e),this.nsps[t]=n),n}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 n=0;n<e.length;n++)this.engine.write(e[n],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 n;this.cleanup(),null===(n=this.engine)||void 0===n||n.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 n=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&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const mo={};function go(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let o=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),o=Pn(t)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";const r=-1!==o.host.indexOf(":")?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+r+":"+o.port+e,o.href=o.protocol+"://"+r+(n&&n.port===o.port?"":":"+o.port),o}(t,(e=e||{}).path||"/socket.io"),o=n.source,r=n.id,i=n.path,s=mo[r]&&i in mo[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new fo(o,e):(mo[r]||(mo[r]=new fo(o,e)),a=mo[r]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(go,{Manager:fo,Socket:ho,io:go,connect:go});
|
|
13
|
+
*/const Ge=Object.create(null);Ge.open="0",Ge.close="1",Ge.ping="2",Ge.pong="3",Ge.message="4",Ge.upgrade="5",Ge.noop="6";const Xe=Object.create(null);Object.keys(Ge).forEach(t=>{Xe[Ge[t]]=t});const Ze={type:"error",data:"parser error"},Qe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tn="function"==typeof ArrayBuffer,en=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,nn=({type:t,data:e},n,o)=>Qe&&e instanceof Blob?n?o(e):on(e,o):tn&&(e instanceof ArrayBuffer||en(e))?n?o(e):on(new Blob([e]),o):o(Ge[t]+(e||"")),on=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function rn(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let sn;const an="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)an["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const cn="function"==typeof ArrayBuffer,dn=(t,e)=>{if("string"!=typeof t)return{type:"message",data:un(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:ln(t.substring(1),e)}:Xe[n]?t.length>1?{type:Xe[n],data:t.substring(1)}:{type:Xe[n]}:Ze},ln=(t,e)=>{if(cn){const n=(t=>{let e,n,o,r,i,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);const d=new ArrayBuffer(s),l=new Uint8Array(d);for(e=0;e<a;e+=4)n=an[t.charCodeAt(e)],o=an[t.charCodeAt(e+1)],r=an[t.charCodeAt(e+2)],i=an[t.charCodeAt(e+3)],l[c++]=n<<2|o>>4,l[c++]=(15&o)<<4|r>>2,l[c++]=(3&r)<<6|63&i;return d})(t);return un(n,e)}return{base64:!0,data:t}},un=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,hn=String.fromCharCode(30);function pn(){return new TransformStream({transform(t,e){!function(t,e){Qe&&t.data instanceof Blob?t.data.arrayBuffer().then(rn).then(e):tn&&(t.data instanceof ArrayBuffer||en(t.data))?e(rn(t.data)):nn(t,!1,t=>{sn||(sn=new TextEncoder),e(sn.encode(t))})}(t,n=>{const o=n.length;let r;if(o<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,o);else if(o<65536){r=new Uint8Array(3);const t=new DataView(r.buffer);t.setUint8(0,126),t.setUint16(1,o)}else{r=new Uint8Array(9);const t=new DataView(r.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(o))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(n)})}})}let fn;function mn(t){return t.reduce((t,e)=>t+e.length,0)}function gn(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let o=0;for(let r=0;r<e;r++)n[r]=t[0][o++],o===t[0].length&&(t.shift(),o=0);return t.length&&o<t[0].length&&(t[0]=t[0].slice(o)),n}function yn(t){if(t)return function(t){for(var e in yn.prototype)t[e]=yn.prototype[e];return t}(t)}yn.prototype.on=yn.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},yn.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},yn.prototype.off=yn.prototype.removeListener=yn.prototype.removeAllListeners=yn.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var n,o=this.t["$"+t];if(!o)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var r=0;r<o.length;r++)if((n=o[r])===e||n.fn===e){o.splice(r,1);break}return 0===o.length&&delete this.t["$"+t],this},yn.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),n=this.t["$"+t],o=1;o<arguments.length;o++)e[o-1]=arguments[o];if(n){o=0;for(var r=(n=n.slice(0)).length;o<r;++o)n[o].apply(this,e)}return this},yn.prototype.emitReserved=yn.prototype.emit,yn.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},yn.prototype.hasListeners=function(t){return!!this.listeners(t).length};const bn="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),vn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function wn(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const kn=vn.setTimeout,Sn=vn.clearTimeout;function An(t,e){e.useNativeTimers?(t.setTimeoutFn=kn.bind(vn),t.clearTimeoutFn=Sn.bind(vn)):(t.setTimeoutFn=vn.setTimeout.bind(vn),t.clearTimeoutFn=vn.clearTimeout.bind(vn))}function xn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class _n extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}let Cn=class extends yn{constructor(t){super(),this.writable=!1,An(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new _n(t,e,n)),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=dn(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 n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}};class En extends Cn{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 n=t.split(hn),o=[];for(let t=0;t<n.length;t++){const r=dn(n[t],e);if(o.push(r),"error"===r.type)break}return o})(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 n=t.length,o=new Array(n);let r=0;t.forEach((t,i)=>{nn(t,!1,t=>{o[i]=t,++r===n&&e(o.join(hn))})})})(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]=xn()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Rn=!1;try{Rn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Tn=Rn;function On(){}class qn extends En{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.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 $n=class t extends yn{constructor(t,e,n){super(),this.createRequest=t,An(this,n),this.p=n,this.v=n.method||"GET",this.m=e,this.k=void 0!==n.data?n.data:null,this.A()}A(){var e;const n=wn(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.p.xd;const o=this.O=this.createRequest(n);try{o.open(this.v,this.m,!0);try{if(this.p.extraHeaders){o.setDisableHeaderCheck&&o.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&o.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{o.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{o.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(o),"withCredentials"in o&&(o.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(o.timeout=this.p.requestTimeout),o.onreadystatechange=()=>{var t;3===o.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(o.getResponseHeader("set-cookie"))),4===o.readyState&&(200===o.status||1223===o.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof o.status?o.status:0)},0))},o.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=On,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 Nn(){for(let t in $n.requests)$n.requests.hasOwnProperty(t)&&$n.requests[t].abort()}$n.requestsCount=0,$n.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Nn):"function"==typeof addEventListener&&addEventListener("onpagehide"in vn?"pagehide":"unload",Nn,!1));const Ln=function(){const t=Bn({xdomain:!1});return t&&null!==t.responseType}();function Bn(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Tn))return new XMLHttpRequest}catch(t){}if(!e)try{return new(vn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const In="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Mn extends Cn{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=In?{}:wn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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 n=t[e],o=e===t.length-1;nn(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}o&&bn(()=>{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]=xn()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const jn=vn.WebSocket||vn.MozWebSocket;const Un={websocket:class extends Mn{createSocket(t,e,n){return In?new jn(t,e,n):e?new jn(t,e):new jn(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Cn{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){fn||(fn=new TextDecoder);const n=[];let o=0,r=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===o){if(mn(n)<1)break;const t=gn(n,1);i=!(128&~t[0]),r=127&t[0],o=r<126?3:126===r?1:2}else if(1===o){if(mn(n)<2)break;const t=gn(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),o=3}else if(2===o){if(mn(n)<8)break;const t=gn(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),i=e.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Ze);break}r=i*Math.pow(2,32)+e.getUint32(4),o=3}else{if(mn(n)<r)break;const t=gn(n,r);a.enqueue(dn(i?t:fn.decode(t),e)),o=0}if(0===r||r>t){a.enqueue(Ze);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),o=pn();o.readable.pipeTo(t.writable),this.U=o.writable.getWriter();const r=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this.U.write(i).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],o=e===t.length-1;this.U.write(n).then(()=>{o&&bn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends qn{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Ln&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new $n(Bn,this.uri(),t)}}},Fn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Dn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Pn(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),o=t.indexOf("]");-1!=n&&-1!=o&&(t=t.substring(0,n)+t.substring(n,o).replace(/:/g,";")+t.substring(o,t.length));let r=Fn.exec(t||""),i={},s=14;for(;s--;)i[Dn[s]]=r[s]||"";return-1!=n&&-1!=o&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,o){e&&(n[e]=o)}),n}(0,i.query),i}const Wn="function"==typeof addEventListener&&"function"==typeof removeEventListener,zn=[];Wn&&addEventListener("offline",()=>{zn.forEach(t=>t())},!1);class Vn extends yn{constructor(t,e={}){var n,o;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 n=Pn(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Pn(e.host).host);if(An(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===(n=e.transports)||void 0===n?void 0:n.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(o=e.transportImplementations)&&void 0!==o?o: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=Un),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={},n=t.split("&");for(let t=0,o=n.length;t<o;t++){let o=n[t].split("=");e[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return e}(this.opts.query)),Wn&&(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"})},zn.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 n=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](n)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Vn.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),n=!1;Vn.priorWebsocketSuccess=!1;const o=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Vn.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(d(),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 r(){n||(n=!0,d(),e.close(),e=null)}const i=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&r()}const d=()=>{e.removeListener("open",o),e.removeListener("error",i),e.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};e.once("open",o),e.once("error",i),e.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Vn.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 n=0;n<this.writeBuffer.length;n++){const o=this.writeBuffer[n].data;if(o&&(t+="string"==typeof(e=o)?function(t){let e=0,n=0;for(let o=0,r=t.length;o<r;o++)e=t.charCodeAt(o),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(o++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))),n>0&&t>this.L)return this.writeBuffer.slice(0,n);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,bn(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this.G("message",t,e,n),this}send(t,e,n){return this.G("message",t,e,n),this}G(t,e,n,o){if("function"==typeof e&&(o=e,e=void 0),"function"==typeof n&&(o=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{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?n():t()}):this.upgrading?n():t()),this}j(t){if(Vn.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(),Wn&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=zn.indexOf(this.$);-1!==t&&zn.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 n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}Vn.protocol=4;const Hn="function"==typeof ArrayBuffer,Kn=Object.prototype.toString,Jn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Kn.call(Blob),Yn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Kn.call(File);function Gn(t){return Hn&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||Jn&&t instanceof Blob||Yn&&t instanceof File}function Xn(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(Xn(t[e]))return!0;return!1}if(Gn(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Xn(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Xn(t[e]))return!0;return!1}function Zn(t){const e=[],n=t.data,o=t;return o.data=Qn(n,e),o.attachments=e.length,{packet:o,buffers:e}}function Qn(t,e,n){if(!t)return t;if(Gn(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let o=0;o<t.length;o++)n[o]=Qn(t[o],e);return n}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!n)return Qn(t.toJSON(),e,!0);const o={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(o[n]=Qn(t[n],e));return o}return t}function to(t,e){return t.data=eo(t.data,e),delete t.attachments,t}function eo(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 n=0;n<t.length;n++)t[n]=eo(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=eo(t[n],e));return t}const no=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var oo;!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"}(oo||(oo={}));class ro extends yn{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 n=e.type===oo.BINARY_EVENT;n||e.type===oo.BINARY_ACK?(e.type=n?oo.EVENT:oo.ACK,this.reconstructor=new io(e)):super.emitReserved("decoded",e)}else{if(!Gn(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 n={type:Number(t.charAt(0))};if(void 0===oo[n.type])throw new Error("unknown packet type "+n.type);if(n.type===oo.BINARY_EVENT||n.type===oo.BINARY_ACK){const o=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const r=t.substring(o,e);if(r!=Number(r)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const i=Number(r);if(!so(i)||i<1)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===t.charAt(e+1)){const o=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(o,e)}else n.nsp="/";const o=t.charAt(e+1);if(""!==o&&Number(o)==o){const o=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(o,e+1))}if(t.charAt(++e)){const o=this.tryParse(t.substr(e));if(!ro.isPayloadValid(n.type,o))throw new Error("invalid payload");n.data=o}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case oo.CONNECT:return ao(e);case oo.DISCONNECT:return void 0===e;case oo.CONNECT_ERROR:return"string"==typeof e||ao(e);case oo.EVENT:case oo.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===no.indexOf(e[0]));case oo.ACK:case oo.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class io{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=to(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const so=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ao(t){return"[object Object]"===Object.prototype.toString.call(t)}var co=Object.freeze({__proto__:null,protocol:5,get PacketType(){return oo},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==oo.EVENT&&t.type!==oo.ACK||!Xn(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===oo.EVENT?oo.BINARY_EVENT:oo.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==oo.BINARY_EVENT&&t.type!==oo.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=Zn(t),n=this.encodeAsString(e.packet),o=e.buffers;return o.unshift(n),o}},Decoder:ro,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||so(e))&&function(t,e){switch(t){case oo.CONNECT:return void 0===e||ao(e);case oo.DISCONNECT:return void 0===e;case oo.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===no.indexOf(e[0]));case oo.ACK:return Array.isArray(e);case oo.CONNECT_ERROR:return"string"==typeof e||ao(e);default:return!1}}(t.type,t.data);var e}});function lo(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const uo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ho extends yn{constructor(t,e,n){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,n&&n.auth&&(this.auth=n.auth),this.p=Object.assign({},n),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lo(t,"open",this.onopen.bind(this)),lo(t,"packet",this.onpacket.bind(this)),lo(t,"error",this.onerror.bind(this)),lo(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 n,o,r;if(uo.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 i={type:oo.EVENT,data:e,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this.ut(t,n),i.id=t}const s=null===(o=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===o?void 0:o.writable,a=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r.st());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}ut(t,e){var n;const o=null!==(n=this.flags.timeout)&&void 0!==n?n:this.p.ackTimeout;if(void 0===o)return void(this.acks[t]=e);const r=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"))},o),i=(...t)=>{this.io.clearTimeoutFn(r),e.apply(this,t)};i.withError=!0,this.acks[t]=i}emitWithAck(t,...e){return new Promise((n,o)=>{const r=(t,e)=>t?o(t):n(e);r.withError=!0,e.push(r),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...o)=>(this.et[0],null!==t?n.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...o)),n.pending=!1,this.ft())),this.et.push(n),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:oo.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 oo.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 oo.EVENT:case oo.BINARY_EVENT:this.onevent(t);break;case oo.ACK:case oo.BINARY_ACK:this.onack(t);break;case oo.DISCONNECT:this.ondisconnect();break;case oo.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 n of e)n.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 n=!1;return function(...o){n||(n=!0,e.packet({type:oo.ACK,id:t,data:o}))}}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:oo.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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n of e)n.apply(this,t.data)}}}function po(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}po.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},po.prototype.reset=function(){this.attempts=0},po.prototype.setMin=function(t){this.ms=t},po.prototype.setMax=function(t){this.max=t},po.prototype.setJitter=function(t){this.jitter=t};class fo extends yn{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,An(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!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new po({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const o=e.parser||co;this.encoder=new o.Encoder,this.decoder=new o.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 Vn(this.uri,this.opts);const e=this.engine,n=this;this.ht="opening",this.skipReconnect=!1;const o=lo(e,"open",function(){n.onopen(),t&&t()}),r=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},i=lo(e,"error",r);if(!1!==this.Bt){const t=this.Bt,n=this.setTimeoutFn(()=>{o(),r(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(o),this.subs.push(i),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lo(t,"ping",this.onping.bind(this)),lo(t,"data",this.ondata.bind(this)),lo(t,"error",this.onerror.bind(this)),lo(t,"close",this.onclose.bind(this)),lo(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){bn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this.rt&&!n.active&&n.connect():(n=new ho(this,t,e),this.nsps[t]=n),n}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 n=0;n<e.length;n++)this.engine.write(e[n],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 n;this.cleanup(),null===(n=this.engine)||void 0===n||n.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 n=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&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const mo={};function go(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let o=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),o=Pn(t)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";const r=-1!==o.host.indexOf(":")?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+r+":"+o.port+e,o.href=o.protocol+"://"+r+(n&&n.port===o.port?"":":"+o.port),o}(t,(e=e||{}).path||"/socket.io"),o=n.source,r=n.id,i=n.path,s=mo[r]&&i in mo[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new fo(o,e):(mo[r]||(mo[r]=new fo(o,e)),a=mo[r]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(go,{Manager:fo,Socket:ho,io:go,connect:go});
|
|
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 yo="chapter-event",bo="story-created",vo="error",wo="server-response",ko="client-ready",So="user-interaction",Ao={debug:0,info:1,warn:2,error:3,silent:4},xo=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&&Ao[t]>=Ao[this.config.level]))return;const{prefix:n}=this.config,o=void 0===n||""===n?e:[n,...e];console[t](...o)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function _o(){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 n=[...e].map(t=>t.toString(16).padStart(2,"0"));return[n.slice(0,4).join(""),n.slice(4,6).join(""),n.slice(6,8).join(""),n.slice(8,10).join(""),n.slice(10,16).join("")].join("-")}var Co,Eo;!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"}(Co||(Co={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Eo||(Eo={}));const Ro={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class To{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??Ro.minVisibilityRatio;this.config={productSelector:t.productSelector??Ro.productSelector,blockSelector:t.blockSelector??Ro.blockSelector,maxTrackedElements:t.maxTrackedElements??Ro.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 xo.warn("UI Observer: invalid selector, skipping rescan:",t)}const n=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),o=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:o>=this.config.minVisibilityRatio,visibilityRatio:o,observedAt:n})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),o=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:o>=this.config.minVisibilityRatio,visibilityRatio:o,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).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 n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).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 n=this.resolveElementId(t),o=this.resolveBlockId(t),r=this.createTrackingKey(n,o),i=this.elementKeys.get(t);void 0!==i&&""!==i&&i!==r&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(t,r),this.elementRefs.set(r,t),this.elements.set(r,{id:n,blockId:o,trackingKey:r,...e})}syncTrackedBlock(t,e){const n=this.resolveTrackedBlockId(t),o=this.blockKeys.get(t),r=n;void 0!==o&&""!==o&&o!==r&&(this.blocks.delete(o),this.blockRefs.delete(o)),this.blockKeys.set(t,r),this.blockRefs.set(r,t),this.blocks.set(r,{id:n,...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)),n=t.width*t.height;if(n<=0)return 0;const o=window.innerWidth*window.innerHeight,r=o>0?Math.min(n,o):n;return Math.min(1,Math.max(0,e/r))}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=[],n=Date.now();for(const[e,n]of this.elements){const o=this.elementRefs.get(e);o?.isConnected?n.visibilityRatio<=0||t.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,n]of this.blocks){const o=this.blockRefs.get(t);o?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||e.push(n.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const o=t.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...o.flatMap(t=>t.blockId??[])])],elements:o.map(t=>t.element)}}}class Oo{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=Ro;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{xo.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(ko)}),this.socket.on("disconnect",()=>{xo.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:n,reason:o}=e;return"number"==typeof n?{code:n,..."string"==typeof o&&{reason:o}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(xo.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(vo,t=>{xo.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{xo.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{xo.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{xo.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{xo.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(wo,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){xo.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){xo.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&&(xo.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,xo.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){xo.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return xo.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new To(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),n=new URL("thamyr",e).pathname;return{origin:e.origin,path:n}}connect(t="wss://localhost:4000",e,n){this.socket&&(xo.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const o=this.socketEndpoint(t);let r;"undefined"!=typeof window&&void 0!==globalThis.location&&(r=globalThis.location.href);const i={...void 0!==r&&""!==r&&{referrer:r},...n};xo.info("Connecting to Thamyr at",o),this.socket=go(o.origin,{path:o.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:i}),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),xo.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Ro,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 To(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void xo.error("Socket is not connected. Cannot send interaction.");if(t===Co.SUGGEST)return void xo.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Co.BACK_FROM_ROUND&&void 0===e.chapterId)return void xo.error("BACK_FROM_ROUND requires chapterId.");const n={type:t,payload:this.enrichPayloadWithUiContext(e)},o={id:_o()};this.socket.emit(So,{type:n.type,payload:n.payload},o.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(So,{type:Co.SUGGEST,payload:t}))}catch(t){return xo.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const qo=["hero","answer","picks","topic","cross","next","other"],$o=["hero","answer","picks","topic","cross","next"],No=new Map([["custom:editorialHero","hero"],["custom:storefrontReply","answer"],["custom:pageAnswer","answer"],["demosthenesResponse","answer"],["custom:demosthenesResponse","answer"],["custom:storefrontPicks","picks"],["custom:collectionGrid","picks"],["custom:problemGuide","topic"],["custom:materialStory","topic"],["custom:sizeCare","topic"],["custom:compareSet","topic"],["custom:storyCards","topic"],["custom:completeSet","cross"],["custom:followUps","next"]]);function Lo(t){return"object"==typeof t&&null!==t&&"string"==typeof t.type&&"function"==typeof t.render}function Bo(t){const e=globalThis.callimacusRenderers;if(Array.isArray(e))for(let n=e.length-1;n>=0;n--){const o=e[n];if(Lo(o)&&o.type===t)return o}}function Io(t,n){const o=new Map(t.map(t=>[t.type,t])),r=function(t){return{type:"*",render(e,n){const o=n.text(e);if(""===o)return;const r=s("div",`cal-fallback-note ${t.pageWidth}`),i=s("div",`cal-fallback-note__body ${t.rte}`);return d(i,o),r.append(i),r},update(t,e,n){const o=n.text(e),r=t instanceof Element?t.querySelector(".cal-fallback-note__body"):void 0;return!(""===o||!r||(r.replaceChildren(),d(r,o),0))}}}(n),i=new Set;return t=>{const n=Bo(t)??o.get(t)??Bo("*")??o.get("*");return n||(No.has(t)?void(i.has(t)||(i.add(t),e.warn(`no renderer for ${t}, skipped`))):r)}}function Mo(t,n,o){try{const r=t.render(n,o);return r instanceof Node?r:void(null!=r&&e.error(`renderer for ${n.type} returned something that is not a Node, skipped`))}catch(t){return e.error(`renderer for ${n.type} threw in render()`,t),!1}}function jo(t,e,n){const o=s("article","cal-chapter");o.dataset.chapterIndex=String(e.index),void 0!==e.id&&(o.dataset.chapterId=e.id);const r=`CallimacusChapter-${t}`,i=s("header",`cal-chapter__head ${n.pageWidth}`),c=s("h2","cal-chapter__heading"),d=s("button","cal-chapter__toggle");d.type="button",d.setAttribute("aria-expanded","true"),d.setAttribute("aria-controls",r),d.append(s("span","cal-chapter__question",e.question)),void 0!==e.about&&d.append(s("span","cal-chapter__about",`About: ${e.about}`));const l=s("span","cal-chapter__thumbs");l.setAttribute("aria-hidden","true"),d.append(l,function(t,e,n){const o=document.createElementNS(a,"svg");o.setAttribute("viewBox",t),o.setAttribute("fill","none"),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false"),o.setAttribute("class",n);const r=document.createElementNS(a,"path");return r.setAttribute("d",e),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","1.4"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),o.append(r),o}("0 0 16 16","M4 6l4 4 4-4","cal-chapter__chevron")),c.append(d),i.append(c);const u=s("div","cal-chapter__body");u.id=r;const h=new Map;for(const t of qo){const e=s("div","cal-slot");e.dataset.slot=t,h.set(t,e),u.append(e)}return o.append(i,u),{key:t,id:e.id,question:e.question,about:e.about,sent:e.sent??e.question,index:e.index,status:e.status??0,blocks:e.blocks??[],nodes:new Map,slots:h,el:o,body:u,toggle:d,thumbs:l,timing:void 0}}function Uo(t,e){const n=t.slots.get(e);if(!n)throw new Error(`chapter has no ${e} slot`);return n}function Fo(t,e){t.el.dataset.state=e,t.el.setAttribute("aria-busy",String("streaming"===e))}function Do(t){let e;for(const n of t)(!e||n.index>e.index)&&(e=n);return e}function Po(t){return t.blocks.map((t,e)=>({block:t,position:e})).sort((t,e)=>{const n=(t.block.priority??0)-(e.block.priority??0);return 0===n?t.position-e.position:n}).map(({block:t})=>t)}function Wo(t,e=""){return"string"==typeof t&&""!==t.trim()?t.trim():e}function zo(t,n){let o=t.language;try{Intl.NumberFormat.supportedLocalesOf(o)}catch{e.warn(`invalid language "${o}", formatting prices with "en"`),o="en"}const r=new Map;const i=t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl;return{settings:t,text(t){for(const e of A(t)){if(m(e))return e.trim();if(u(e)&&m(e.text))return e.text.trim()}return""},hits:t=>v(Array.isArray(t)?t:[t]),picks(t){for(const e of A(t)){if(!Array.isArray(e))continue;const t=v(e);if(t.length>0)return t}return[]},money(n){const i="number"==typeof n?n:n?.amount;if(void 0===i||""===i)return"";const s=Number(i);if(!Number.isFinite(s))return"";const a="object"==typeof n?n.currency:void 0,c=function(t){if(!r.has(t))try{r.set(t,new Intl.NumberFormat(o,{style:"currency",currency:t}))}catch{e.warn(`invalid currency "${t}", showing bare amounts`),r.set(t,void 0)}return r.get(t)}(void 0===a||""===a?t.currency:a);return c?c.format(s):s.toFixed(2)},url(t){const e=void 0===t?"":function(t){if(!h(t)){const e=u(t.meta)?t.meta.url:void 0;return"string"==typeof e&&/^\/(?!\/)/u.test(e)&&!/[\s\\]/u.test(e)?e:""}const e=encodeURIComponent(t.fields["shopify-handle"]);switch(p(t)){case"product":return`/products/${e}`;case"collection":return`/collections/${e}`;case"article":{const n=g(t.fields["shopify-blogHandle"]);return""===n?"":`/blogs/${encodeURIComponent(n)}/${e}`}default:return""}}(t);return""===e?"":`${i}${e}`},imageUrl(t,{width:e=800,index:n=0}={}){const o=t?.fields.images;if(!Array.isArray(o)||0===o.length)return"";const r=o[n]?.url??o[0]?.url;return"string"!=typeof r||""===r?"":`${r.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields.variantTree?.variants;if(!Array.isArray(e)||0===e.length)return"";const n=e.find(t=>!0===t?.orderable)??e[0];return void 0===n?.id?"":String(n.id).split("/").pop()??""},addToCart:n.addToCart,ask:n.ask,remember:n.remember}}function Vo(){return globalThis.Shopify}function Ho(){try{const t=Vo()?.customerPrivacy?.preferencesProcessingAllowed?.();return void 0===t?"unknown":!0===t?"allowed":"refused"}catch{return"unknown"}}function Ko(t){return o("sessionStorage",t)??("allowed"===Ho()?o("localStorage",t):void 0)}function Jo(t){const n=Ko(t);if(void 0!==n&&""!==n)try{return JSON.parse(n)}catch{return void e.warn(`ignoring unreadable "${t}"`)}}function Yo(t,e){const n=r("sessionStorage",t,e);return"allowed"!==Ho()||r("localStorage",t,e)||i("localStorage",t),n}function Go(t){i("localStorage",t),i("sessionStorage",t)}function Xo(t){const e=Ho();if("unknown"!==e)for(const n of t){if("allowed"===e){const t=o("sessionStorage",n);void 0!==t&&r("localStorage",n,t);continue}const t=o("localStorage",n);void 0!==t&&(void 0===o("sessionStorage",n)&&r("sessionStorage",n,t),i("localStorage",n))}}const Zo="callimacus.memory",Qo=6,tr=12,er=12,nr=new TextEncoder;function or(t){return Array.isArray(t)?t.filter(t=>u(t)):[]}function rr(t){return"number"==typeof t&&Number.isFinite(t)?t:0}function ir(){const t=Jo(Zo),e=u(t)?t:{};return{questions:or(e.questions).filter(t=>"string"==typeof t.q).map(t=>({q:t.q,at:rr(t.at)})),viewed:or(e.viewed).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,title:"string"==typeof t.title?t.title:"",at:rr(t.at)})),added:or(e.added).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,at:rr(t.at)}))}}function sr(t){return"string"==typeof t?t:u(t)&&"string"==typeof t.handle?t.handle:""}function ar(t,n){const o=ir(),r=Date.now();switch(t){case"questions":case"question":{const t="string"==typeof n?n.trim():"";if(""===t)return;o.questions=[{q:t,at:r},...o.questions.filter(e=>e.q!==t)].slice(0,12);break}case"viewed":{const t=sr(n);if(""===t)return;const e=u(n)&&"string"==typeof n.title?n.title:"";o.viewed=[{handle:t,title:e,at:r},...o.viewed.filter(e=>e.handle!==t)].slice(0,12);break}case"added":{const t=sr(n);if(""===t)return;o.added=[{handle:t,at:r},...o.added.filter(e=>e.handle!==t)].slice(0,12);break}default:return void e.warn(`remember() does not know "${t}"`)}Yo(Zo,JSON.stringify(o))}function cr(t,e){const n=t=>t.slice(0,200),o=t=>t.length<=200,r={questions:t.questions.map(t=>t.q).filter(t=>t!==e).slice(0,Qo).map(t=>n(t)),viewed:t.viewed.filter(t=>o(t.handle)).slice(0,tr).map(({handle:t,title:e})=>""===e?{handle:t}:{handle:t,title:n(e)}),added:t.added.map(t=>t.handle).filter(t=>o(t)).slice(0,er)};for(;nr.encode(JSON.stringify(r)).length>4096;){let t="viewed";for(const e of["added","questions"])r[e].length>r[t].length&&(t=e);r[t].pop()}return r}function dr(t){return s("div",`cal-skeleton__bone cal-skeleton__bone--${t}`)}function lr(t,e){const n=s("ul",e.grid(t));for(let o=0;o<t;o++){const t=s("li",e.gridItem),o=s("div","cal-skeleton__card");o.append(dr("media"),dr("title"),dr("price")),t.append(o),n.append(t)}return n}function ur(){const t=s("div","cal-skeleton__lines");return t.append(dr("line"),dr("line"),dr("line")),t}function hr(t,e,n){const o=s("div","cal-skeleton");o.dataset.skeleton=t,o.setAttribute("aria-hidden","true");const r=s("div","cal-skeleton__inner"),i="hero"===t&&0===e,a=s("div",i?"cal-skeleton__content":`cal-skeleton__content${"hero"!==t||i?"":" cal-skeleton__content--row"} ${n.pageWidth}`);return a.append(...function(t,e,n){switch(t){case"hero":return e?[dr("hero")]:[dr("lead"),ur()];case"answer":return[ur()];case"picks":return[lr(4,n)];case"topic":return[dr("topic")];case"cross":return[lr(3,n)];case"next":{const t=s("div","cal-skeleton__chips");return t.append(dr("chip"),dr("chip"),dr("chip")),[t]}case"other":return[]}}(t,i,n)),r.append(a),o.append(r),o}const pr="callimacus.thread",fr="callimacus.storyId",mr=15e5;function gr(t){return Array.isArray(t)?t.filter(t=>u(t)&&"string"==typeof t.id&&""!==t.id):[]}function yr(t){const e=t.inputEvent;return u(e)&&u(e.data)?y(e.data.value):""}function br(t){const e=t.lastIndexOf(" (about the ");if(-1===e||!t.endsWith(")"))return{question:t,about:void 0};const n=t.slice(e+12,-1);return""===n?{question:t,about:void 0}:{question:t.slice(0,e),about:n}}function vr(t){const e=Number(t);return Number.isFinite(e)?e:0}function wr(){return Ko(fr)}function kr(t){void 0===t?Go(fr):Yo(fr,t)}function Sr(){const t=Jo(pr);return Array.isArray(t)?t.filter(t=>u(t)&&"string"==typeof t.question).map(t=>t).map(t=>{const e=t.question;return{id:""===y(t.id)?void 0:y(t.id),question:e,about:""===y(t.about)?void 0:y(t.about),sent:""===y(t.sent)?e:y(t.sent),index:vr(t.index),status:vr(t.status),blocks:gr(t.blocks)}}).sort((t,e)=>t.index-e.index).slice(-12):[]}function Ar(t){return Math.round(performance.now()-t.t0)}const xr=4e3,_r=[pr,fr,Zo],Cr="data-callimacus-on",Er=new Set([401,403]),Rr=new Set(["invalid_token","origin_not_allowed","paused"]);function Tr(t){return"function"==typeof globalThis.matchMedia?globalThis.matchMedia(t):{matches:!1}}function Or(t){const{kit:n}=t,o=t.roundTimeoutMs??45e3,r=t.createTransport??(()=>new Oo),i=function(){let t={};try{const e=JSON.parse(document.querySelector("#callimacus-config")?.textContent??"{}");t=u(e)?e:{}}catch(t){e.error("#callimacus-config is not valid JSON",t)}const n=globalThis.Shopify,o=u(t.product)&&""!==Wo(t.product.handle)?Object.freeze({handle:Wo(t.product.handle),title:Wo(t.product.title),id:"number"==typeof t.product.id||"string"==typeof t.product.id?t.product.id:void 0}):void 0,r=Wo(t.storeName,"this store");return Object.freeze({language:Wo(t.language,"en"),rootUrl:Wo(t.rootUrl,"/"),cartAddUrl:Wo(t.cartAddUrl,"/cart/add"),currency:Wo(t.currency,"USD"),designMode:!0===t.designMode||Boolean(n?.designMode),template:Wo(t.template),product:o,storeName:r,assistantLabel:Wo(t.assistantLabel,`Ask ${r}`),starters:Object.freeze(Array.isArray(t.starters)?t.starters.map(t=>Wo(t)).filter(t=>""!==t):[])})}(),a=function(t){return{connecting:"Connecting…",asking:"Thinking…",streaming:"Composing your answer…",done:"Answer ready.",queued:t=>`Queued: “${t}”. I’ll ask that next.`,queueFull:"Still answering. Ask again in a moment.",dequeued:"Removed from the queue.",timeout:"This is taking longer than usual. Try asking again.",failed:"Something went wrong. Please try again.",reconnecting:"Reconnecting…",unavailable:`${t.assistantLabel} is unavailable right now. Please try again later.`,trimmed:"Earlier answers were trimmed from this conversation.",designMode:`${t.assistantLabel} answers on the live store, not in the theme editor.`,interrupted:"This answer stopped before it was finished.",unanswered:`${t.storeName} could not answer that just now.`}}(i),c=document.documentElement,d=new AbortController,{signal:h}=d,p=[],f=Tr("(prefers-reduced-motion: reduce)"),m=Tr("(pointer: coarse)"),g={ui:"idle",storyId:void 0,isConnected:!1,isOff:!1,thread:[],round:void 0,queue:[],about:i.product?.title,hydrateMode:void 0,refreshTimer:void 0,lastAsk:void 0,statusTimer:void 0,nextKey:0},b=[],v=Io(t.renderers,n.classes);function w(){d.abort();for(const t of p)t.disconnect();clearTimeout(g.refreshTimer),clearTimeout(g.statusTimer),clearTimeout(g.round?.timer)}function k(t,e){document.dispatchEvent(new CustomEvent(t,{detail:e}))}function S(t){g.ui!==t&&(g.ui=t,c.dataset.callimacusState=t,k("callimacus:state",{state:t}))}function A(t,{clearAfter:e=0}={}){clearTimeout(g.statusTimer);for(const e of document.querySelectorAll("[data-callimacus-status]"))e.textContent=t;e>0&&(g.statusTimer=setTimeout(()=>{A("")},e))}function C(t){g.storyId=""===t?void 0:t,kr(g.storyId)}const E=zo(i,{addToCart:async function(t,e=1){const o=String(t).split("/").pop()??"";if(!/^\d+$/u.test(o))throw new Error("This product cannot be added right now.");const r=await n.addToCart(o,e,i);return"string"==typeof r.handle&&""!==r.handle&&ar("added",r.handle),r},ask:t=>"refused"!==V(t,{type:"relatedQuestion"}),remember:ar});const R={stage:void 0,thread:void 0,earlier:void 0,trimmed:void 0,dock:document.querySelector("[data-callimacus-dock]")??void 0};function T(){return R.stage?.dataset.stageKind??"page"}function O(){let t=document.querySelector("[data-callimacus-stage]")??void 0;t||(t=s("div","cal-stage"),t.dataset.callimacusStage="",t.dataset.stageKind="page",t.dataset.callimacusUi="",(document.querySelector("#MainContent")??document.body).prepend(t));let e=t.querySelector("[data-callimacus-thread]")??void 0;e||(e=s("div","cal-thread"),e.dataset.callimacusThread="",t.append(e)),e.classList.add("cal-thread");const o=s("button",`cal-thread__earlier ${n.classes.pageWidth}`);o.type="button",o.hidden=!0,o.addEventListener("click",()=>{$(!1)},{signal:h});const r=s("p",`cal-thread__trimmed ${n.classes.pageWidth}`,a.trimmed);return r.hidden=!0,e.after(o,r),Object.assign(R,{stage:t,thread:e,earlier:o,trimmed:r}),{stage:t,thread:e}}function q(){return R.thread??O().thread}function $(t){R.thread&&(R.thread.toggleAttribute("data-compact",t),N())}function N(){if(!R.earlier||!R.thread||!R.trimmed)return;const t=g.thread.length-1,e=Object.hasOwn(R.thread.dataset,"compact"),n=e&&t>0;R.earlier.hidden=!n,n&&(R.earlier.textContent=`Show ${t} earlier question${1===t?"":"s"}`),R.trimmed.hidden=e||0===g.thread.length||g.thread.some(t=>0===t.index)}function L(){const t=new Set([...g.thread].sort((t,e)=>e.index-t.index).slice(12));for(const e of t)e.el.remove();g.thread=g.thread.filter(e=>!t.has(e))}function B(t){g.nextKey+=1;const e=jo(g.nextKey,t,n.classes);return e.toggle.addEventListener("click",()=>{M(e,Object.hasOwn(e.el.dataset,"collapsed"))},{signal:h}),e}function I(t){for(const e of $o){const o=Uo(t,e);o.querySelector(":scope > .cal-block, :scope > .cal-skeleton")||o.append(hr(e,t.index,n.classes))}}function M(t,e,{shouldAnimate:n=!0}={}){e!==!Object.hasOwn(t.el.dataset,"collapsed")&&(e||t.thumbs.replaceChildren(...function(t){const e=new Set,n=[],o=Po(t).flatMap(t=>E.picks(t));for(const t of o){if(4===n.length)break;const o=t.fields["shopify-handle"],r=E.imageUrl(t,{width:160});if(""===r||e.has(o))continue;e.add(o);const i=s("img","cal-chapter__thumb");i.src=r,i.alt="",i.loading="lazy",i.decoding="async",i.width=40,i.height=50,n.push(i)}return n}(t)),t.el.toggleAttribute("data-collapsed",!e),t.toggle.setAttribute("aria-expanded",String(e)),t.body.inert=!e,e&&n&&!f.matches&&(t.el.dataset.animating="",setTimeout(()=>{delete t.el.dataset.animating},360)))}function j(t){const e=t.el,n=()=>{t.el.style.setProperty("--cal-header-height",`${function(){if("function"!=typeof document.elementsFromPoint)return 0;const t=document.documentElement.clientWidth;let e=0;for(const n of[.25,.5,.75])for(const o of document.elementsFromPoint(Math.round(t*n),1)){const t=l(o)?.getBoundingClientRect();t&&t.top<=1&&t.bottom>e&&t.bottom<globalThis.innerHeight/2&&(e=t.bottom)}return Math.round(e)}()}px`),e.scrollIntoView?.({behavior:f.matches?"auto":"smooth",block:"start"})};"function"==typeof requestAnimationFrame?requestAnimationFrame(n):n()}function U(t,e){const o=t.body.querySelector(":scope > .cal-chapter__note");if(!e)return void o?.remove();if(o)return;const r=s("div",`cal-chapter__note ${n.classes.pageWidth}`);r.append(s("p","",t.blocks.length>0?a.interrupted:a.unanswered));const i=s("button","cal-chapter__retry","Ask again");i.type="button",i.addEventListener("click",()=>{V(t.question,{type:"question",about:t.about})},{signal:h}),r.append(i),t.body.append(r)}function F(t,e,n,o){const r=Uo(t,No.get(e.type)??"other"),i=s("div","cal-block");i.dataset.blockId=e.id,i.dataset.blockType=e.type,i.dataset.order=String(o.order),i.append(n),r.querySelector(":scope > .cal-skeleton")?.remove();const a=[...r.children].find(t=>Number(t.dataset.order)>o.order);if(a?a.before(i):r.append(i),o.shouldAnimate&&!f.matches){const t=60*o.stagger;i.style.setProperty("--cal-stagger",`${t}ms`),i.dataset.arriving="",setTimeout(()=>{delete i.dataset.arriving,i.style.removeProperty("--cal-stagger")},240+t+60)}var c;return c=t.timing,"pending"===c?.outcome&&void 0===c.firstBlockMs&&(c.firstBlockMs=Ar(c),performance.mark(`callimacus:chapter-${c.chapter}:first-block`)),k("callimacus:block",{chapterId:t.id,blockId:e.id,type:e.type,node:n}),i}function D(t,n,o,r){const i=v(n.type);if(!i||!x(n))return!1;const s=JSON.stringify(n.data);let a=t.nodes.get(n.id);if(a?.wrap&&(a.wrap.dataset.order=String(r.order)),!0===a?.isBroken)return!1;if(void 0===a?.node){if(a?.signature===s&&!r.hasBecomeDone)return!1;const e=Mo(i,n,o);return a={signature:s,node:!1===e?void 0:e,wrap:void 0,isBroken:!1===e},t.nodes.set(n.id,a),a.node?(a.wrap=F(t,n,a.node,r),!0):!1}if(s===a.signature&&!r.hasBecomeDone)return!1;if(a.signature=s,function(t,n,o,r){if("function"!=typeof t.update)return!1;try{return t.update(n,o,r)}catch(t){return e.error(`renderer for ${o.type} threw in update()`,t),!1}}(i,a.node,n,o))return!1;const c=Mo(i,n,o);return!1===c?a.isBroken=!0:c&&a.wrap&&(a.wrap.replaceChildren(c),a.node=c),!1}function P(t,{hasBecomeDone:e=!1,shouldAnimate:n=!0}={}){const o=function(t){const e=4===t.status,n=Object.freeze({id:t.id,index:t.index,isFirst:0===t.index,question:t.question,done:e,blocks:Object.freeze([...t.blocks])});return Object.freeze({...E,chapter:n,final:e})}(t);let r=0;for(const[i,s]of Po(t).entries())D(t,s,o,{order:i,stagger:r,hasBecomeDone:e,shouldAnimate:n})&&(r+=1)}const W=function(t){let n,o=!1,r=!1,i=0;const s=[];function a(n,r=t.session.current()){o=!1,r.then(e=>{if(!t.isOff()){if(!e)return s.length=0,void t.onRefused();n.connect(e.endpoint,{Authorization:`Bearer ${e.token}`},{token:e.token}),o=!0;for(const t of s.splice(0))t(n)}}).catch(n=>{e.warn("no storefront session",n),s.length=0,t.onError({code:503,reason:"retries_exhausted",message:"no storefront session"})})}function c(){if(n)return r&&(r=!1,a(n)),n;const e=t.createTransport();return e.onServerResponse(t.onResponse),e.onError(t.onError),e.onConnectionStatus(t.onStatus),n=e,a(e),e}return{connect:c,send:function(t,e){const n=c();o?n.sendUserInteraction(t,e):s.push(n=>{n.sendUserInteraction(t,e)})},markFailed(){r=!0},didRenew:function(){const o=Date.now();return!(!n||o-i<6e4||(i=o,e.info("the storefront token expired; asking the store for a fresh one"),a(n,t.session.renew()),0))}}}({session:t.session,createTransport:r,onResponse:function(t){const n=t;n.type===bo?function(t){if(!u(t)||"string"!=typeof t.id||""===t.id)return;t.id!==g.storyId&&C(t.id);const e=(Array.isArray(t.chapters)?t.chapters:[]).filter(t=>u(t)&&"string"==typeof t.id&&""!==t.id&&!0!==t.deleted).map(t=>t);e.length>0?function(t){const e="restore"===g.hydrateMode;let n=!1;for(const o of t.slice(-12)){const r=t.indexOf(o),i=g.thread.find(t=>t.id===o.id)??G(o);if(i){e&&rt(i,r),X(i,o,g.round?.rec===i);continue}const s=yr(o);if(!e||""===s)continue;const{question:a,about:c}=br(s);nt({id:o.id,question:a,about:c,sent:s,index:r,status:"number"==typeof o.status?o.status:0,blocks:gr(o.blocks)}),n=!0}if(n){const e=new Set(t.map(t=>t.id));let n=t.length;for(const t of g.thread)e.has(t.id)||rt(t,n++);mt(),ot(),et()}e&&(g.hydrateMode="refresh")}(e):"restore"===g.hydrateMode&&(g.hydrateMode="refresh")}(n.story):n.type===yo?function(t){if(!u(t)||"string"!=typeof t.id||""===t.id||!0===t.deleted)return;const n=g.thread.find(e=>e.id===t.id)??G(t);n?X(n,t,!0):e.debug("chapter-event for a chapter this page does not show",t.id)}(n.chapter):e.debug("ignored server response",n.type)},onError:function(t){const{code:n}=t;if(e.warn("server error",n,t.message??"",t.reason??""),"token_expired"===t.reason&&W.didRenew())return;if(function(t){return Er.has(t.code)&&(!g.isConnected||Rr.has(t.reason??""))}(t))return void z(t);const{round:r}=g;if(404===n&&(C(void 0),at({shouldFailPending:!0}),r&&!r.isRetried&&void 0===r.rec.id))return r.isRetried=!0,e.info("story not found, asking again as a new story"),clearTimeout(r.timer),r.timer=setTimeout(()=>{Y(r)},o),void J(r);const i=!g.isConnected;if(i&&"retries_exhausted"!==t.reason&&!(n>=400&&n<500))return void(r&&A(a.reconnecting));i&&W.markFailed();r?(A(i?a.unavailable:a.failed),Z(r.rec,"error")):i&&(S("error"),A(a.unavailable))},onStatus:function(t){g.isConnected=t;const{round:e}=g;if(!t||!e||void 0!==e.rec.timing?.firstEventMs)return;S("asking"),A(a.asking)},isOff:()=>g.isOff,onRefused(){const{status:t,reason:e}=Yt()??{status:401,reason:"invalid_token"};z({code:t,reason:e})}});function z(t){const n="paused"===t.reason;if(e.warn(`the store refused this storefront (${String(t.code)} ${t.reason??""}); the theme's own search is back`),g.isOff=!0,Jt({status:t.code,reason:t.reason}),at(),g.queue=[],ut(),g.round&&Z(g.round.rec,"error"),S("error"),n){for(const t of document.querySelectorAll('[data-callimacus-form] input[name="q"], [data-callimacus-form] [type="submit"], [data-callimacus-open], button[data-callimacus-ask]'))t.disabled=!0;A(a.unavailable)}else c.removeAttribute(Cr),A("");k("callimacus:off",{code:t.code,reason:t.reason})}function V(t,{type:e="question",about:n}={}){const o=y(t),r=function(t){if(""===t||g.isOff)return"";if(i.designMode)return a.designMode;const e=Date.now();return g.lastAsk?.text===t&&e-g.lastAsk.at<600?"":(g.lastAsk={text:t,at:e},g.round&&g.queue.length>=3?a.queueFull:void 0)}(o);if(void 0!==r)return""!==r&&A(r,{clearAfter:r===a.unavailable?0:xr}),"refused";const s={display:o,about:n,type:e,sent:void 0===n?o:`${o} (about the ${n})`,visit:cr(ir(),o)};return ar("questions",o),k("callimacus:ask",{question:o,type:e,queued:Boolean(g.round)}),g.round?(g.queue.push(s),ut(),A(a.queued(o),{clearAfter:xr}),"queued"):(H(s),"sent")}function H(t){const e=B({question:t.display,about:t.about,sent:t.sent,index:K()});for(const t of g.thread)M(t,!1);g.thread.push(e),q().prepend(e.el),L(),Fo(e,"streaming"),I(e),mt(),lt(),N();const n={rec:e,type:t.type,visit:t.visit,timer:void 0,isRetried:!1};var r,i;g.round=n,e.timing=(r=e.index,i=e.question,performance.mark(`callimacus:chapter-${r}:sent`),{chapter:r,question:i,chapterId:void 0,sentAt:(new Date).toISOString(),firstEventMs:void 0,firstBlockMs:void 0,doneMs:void 0,outcome:"pending",t0:performance.now()}),b.push(e.timing),S(g.isConnected?"asking":"connecting"),A(g.isConnected?a.asking:a.connecting),n.timer=setTimeout(()=>{Y(n)},o),j(e),et(),k("callimacus:chapter",Q(e)),J(n)}function K(){let t=0;for(const e of g.thread)t=Math.max(t,e.index+1);return t}function J(t){try{W.connect()}catch(n){return e.error("could not start the Callimacus client",n),void(g.round===t&&(A(a.unavailable),Z(t.rec,"error")))}if(g.round===t)try{!function(t){const e={visit:t.visit},n={...void 0!==g.storyId&&{storyId:g.storyId},language:i.language,inputEvent:{type:t.type,data:{value:t.rec.sent}},context:e};W.send(Co.CREATE_ROUND,n)}(t)}catch(n){e.error("could not send the question",n),A(a.failed),Z(t.rec,"error")}}function Y(t){g.round===t&&(e.warn(`no complete answer within ${o/1e3} s for “${t.rec.question}”`),A(a.timeout),Z(t.rec,"timeout"))}function G(t){const e=yr(t),n=""===e?void 0===g.round?.rec.id?g.round?.rec:void 0:g.thread.findLast(t=>void 0===t.id&&t.sent===e);if(n&&"string"==typeof t.id)return n.id=t.id,n.el.dataset.chapterId=t.id,n}function X(t,e,n){const o=4===t.status;var r,i;t.blocks=function(t,e){const n=[...t];for(const t of e){const e=n.findIndex(e=>e.id===t.id);-1===e?n.push(t):n[e]=t}return n}(t.blocks,gr(e.blocks)),t.status="number"==typeof e.status?e.status:t.status,g.round?.rec===t&&void 0===t.timing?.firstEventMs&&(r=t.timing,i=t.id,r&&void 0===r.firstEventMs&&(r.firstEventMs=Ar(r),r.chapterId=i),S("streaming"),A(a.streaming));const s=!o&&4===t.status;P(t,{hasBecomeDone:s,shouldAnimate:n}),s&&Z(t,"done")}function Z(t,n){const o="done"!==n;Fo(t,o?"error":"done"),function(t){for(const e of t.body.querySelectorAll(":scope > .cal-slot > .cal-skeleton")){if(Object.hasOwn(e.dataset,"leaving"))continue;e.dataset.leaving="";const t=()=>{e.remove()};e.addEventListener("transitionend",t,{once:!0}),setTimeout(t,400)}}(t),U(t,o&&!g.isOff),function(t,n,o){if("pending"!==t?.outcome)return;t.outcome=o,t.chapterId=n,t.doneMs=Ar(t),performance.mark(`callimacus:chapter-${t.chapter}:${o}`);const{t0:r,...i}=t;e.debug("timing",i)}(t.timing,t.id,n),et(),k("callimacus:chapter",Q(t));const r=g.round?.rec===t?g.round:void 0;r&&(clearTimeout(r.timer),g.round=void 0,o?S("error"):(S("idle"),A(a.done,{clearAfter:xr})),function(){if(void 0!==g.round||g.isOff)return;const t=g.queue.shift();if(!t)return;ut(),H(t)}())}function Q(t){return{id:t.id,index:t.index,question:t.question,state:t.el.dataset.state}}function tt(t){return{id:t.id,question:t.question,about:t.about,sent:t.sent,index:t.index,status:t.status,blocks:t.blocks}}function et(){!function(t){if(0===t.length)return;const e=[...t].sort((t,e)=>t.index-e.index).slice(-12);let n=JSON.stringify(e);if(n.length>mr){for(const t of e)t.blocks=_(t.blocks);n=JSON.stringify(e)}for(;e.length>0;){if(n.length<=mr&&Yo(pr,n))return;e.shift(),n=JSON.stringify(e)}Go(pr)}(g.thread.map(t=>tt(t))),kr(g.storyId)}function nt(t){const e=B(t);g.thread.push(e);const n=4===e.status,o=!n&&void 0!==e.id&&void 0!==g.storyId;return Fo(e,n?"done":o?"streaming":"error"),o&&I(e),P(e,{shouldAnimate:!1}),n||o||U(e,!0),e}function ot(){L();const t=Do(g.thread),e="home"===T();for(const n of g.thread)M(n,e&&n===t||g.round?.rec===n,{shouldAnimate:!1});!function(){const t=[...g.thread].sort((t,e)=>e.index-t.index);q().append(...t.map(t=>t.el))}(),$(!e),lt()}function rt(t,e){t.index=e,t.el.dataset.chapterIndex=String(e)}function it(){return g.thread.filter(t=>void 0!==t.id&&4!==t.status&&g.round?.rec!==t&&"streaming"===t.el.dataset.state)}function st(t=0){clearTimeout(g.refreshTimer);const{storyId:n}=g;if(!(void 0===n||g.isOff||t>0&&"restore"!==g.hydrateMode&&0===it().length))if(t>=6)at({shouldFailPending:!0});else{try{W.send(Co.GET_STORY,{storyId:n})}catch(t){e.error("could not start the Callimacus client",t)}g.refreshTimer=setTimeout(()=>{st(t+1)},3e3)}}function at({shouldFailPending:t=!1}={}){if(clearTimeout(g.refreshTimer),g.hydrateMode=void 0,t)for(const t of it())Z(t,"error")}const ct=t=>R.dock?.querySelector(t)??void 0,dt={input:ct('input[name="q"]'),chips:ct("[data-callimacus-dock-chips]"),count:ct("[data-callimacus-thread-count]"),countLabel:ct("[data-callimacus-thread-count-label]"),next:ct("[data-callimacus-next]"),nextLabel:ct("[data-callimacus-next-label]"),about:ct("[data-callimacus-about]"),aboutLabel:ct("[data-callimacus-about-label]")};function lt(){if(!dt.count)return;const t=g.thread.length;dt.count.hidden=0===t;const e=`${t} question${1===t?"":"s"}`;dt.countLabel&&(dt.countLabel.textContent=String(t)),dt.count.title=e,dt.count.setAttribute("aria-label",`${e} in this conversation. Show the conversation`)}function ut(){if(!dt.next)return;const[t]=g.queue;if(dt.next.hidden=void 0===t,void 0!==t){const e=g.queue.length>1?` (+${g.queue.length-1})`:"";dt.nextLabel&&(dt.nextLabel.textContent=`Next: ${t.display}${e}`),dt.next.setAttribute("aria-label",`Next question: ${t.display}. Remove it from the queue`)}dt.chips&&(dt.chips.hidden=[...dt.chips.children].every(t=>t instanceof HTMLElement&&!0===t.hidden))}function ht(){const t=g.about;dt.about&&(dt.about.hidden=void 0===t),void 0!==t&&dt.aboutLabel&&(dt.aboutLabel.textContent=`About: ${t}`),dt.input&&(dt.input.placeholder=void 0===t?dt.input.dataset.placeholder??dt.input.placeholder:"Ask anything about it")}function pt(){dt.input&&(dt.input.focus(),yt())}function ft(){$(!1);const t=Do(g.thread);t&&(M(t,!0),j(t))}function mt(){const t=document.querySelector("[data-callimacus-welcome]");t&&(t.hidden=!0)}function gt(t){const e=s("section","cal-welcome__group");return e.append(s("h2","cal-welcome__title",t)),e}function yt(){if(!i.designMode&&!g.isOff)try{W.connect()}catch(t){e.error("could not start the Callimacus client",t)}}function bt(){return!g.isOff&&c.hasAttribute(Cr)}function vt(t){const e=t.target instanceof Element?t.target.closest("[data-callimacus-form]"):void 0;if(!e||!bt())return;t.preventDefault();const n=e.querySelector('input[name="q"]'),o=n?.value.trim()??"";n&&""!==o?("refused"!==V(o,{type:"question",about:g.about})&&(n.value=""),m.matches&&n.blur()):n?.focus()}function wt(t){if(!(bt()&&t.target instanceof Element))return;const e=t.target.closest("[data-callimacus-ask]");if(e){const n=e.dataset.callimacusAsk?.trim()??"";return void(""!==n&&(t.preventDefault(),V(n,{type:"relatedQuestion"})))}t.target.closest("[data-callimacus-open]")&&(t.preventDefault(),pt())}function kt(t){var e;bt()&&("/"!==t.key||t.metaKey||t.ctrlKey||t.altKey||(e=t.target)instanceof Element&&null!==e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')?"Escape"===t.key&&t.target instanceof HTMLElement&&t.target.matches('[data-callimacus-form] input[name="q"]')&&t.target.blur():(t.preventDefault(),pt()))}const St={ask:t=>"refused"!==V(t,{type:"question"}),get thread(){return[...g.thread].sort((t,e)=>t.index-e.index).map(t=>tt(t))},ctx:E,timings:b,get state(){return g.ui},get storyId(){return g.storyId},reset:function(){at(),clearTimeout(g.round?.timer),g.round=void 0,g.queue=[];for(const t of g.thread)t.el.remove();g.thread=[],C(void 0),Go(pr),ut(),lt(),$(!1),S("idle"),A("")}};c.dataset.callimacusState=g.ui;const At=globalThis;if(At.callimacus=St,At.callimacusTheme={card:n.card,cards:n.cards},void 0!==Yt()||!c.hasAttribute(Cr))return c.removeAttribute(Cr),g.isOff=!0,S("error"),k("callimacus:ready",{designMode:i.designMode,off:!0}),{page:St,destroy:w};if(n.install?.(),function(t,e){Xo(t),document.addEventListener("visitorConsentCollected",()=>{Xo(t)},{signal:e})}(_r,h),g.storyId=wr(),document.addEventListener("submit",vt,{signal:h}),document.addEventListener("click",wt,{signal:h}),document.addEventListener("keydown",kt,{signal:h}),document.addEventListener("focusin",t=>{t.target instanceof Element&&t.target.matches('[data-callimacus-form] input[name="q"]')&&yt()},{signal:h}),dt.count?.addEventListener("click",ft,{signal:h}),dt.next?.addEventListener("click",()=>{g.queue.shift(),ut(),A(a.dequeued,{clearAfter:xr}),dt.input?.focus()},{signal:h}),R.dock?.querySelector("[data-callimacus-about-remove]")?.addEventListener("click",()=>{g.about=void 0,ht(),dt.input?.focus()},{signal:h}),function(){const{dock:t}=R;if(!t||"function"!=typeof ResizeObserver)return;const e=new ResizeObserver(()=>{c.style.setProperty("--cal-dock-space",`${Math.ceil(t.offsetHeight)}px`)});e.observe(t),p.push(e)}(),globalThis.addEventListener("pagehide",()=>{(void 0!==g.round||it().length>0)&&et()},{signal:h}),globalThis.addEventListener("pageshow",t=>{t.persisted&&function(){const t=t=>t.id??`${t.index}:${t.sent}`,e=new Set(g.thread.map(e=>t(e))),n=Sr().filter(n=>!e.has(t(n))),o=wr();if(void 0!==o&&o!==g.storyId&&(g.storyId=o),0!==n.length){for(const t of n)nt(t);mt(),ot(),N()}}()},{signal:h}),ht(),lt(),ut(),i.designMode)return k("callimacus:ready",{designMode:!0,off:!1}),{page:St,destroy:w};i.product&&ar("viewed",{handle:i.product.handle,title:i.product.title});const{stage:xt}=O();!function(){for(const t of Sr())nt(t);return 0!==g.thread.length&&(ot(),!0)}()?void 0!==g.storyId&&(g.hydrateMode="restore",st()):it().length>0&&(g.hydrateMode="refresh",st()),"home"===T()&&function(){const t=document.querySelector("[data-callimacus-welcome]");if(!t)return;const e=ir(),o=e.questions.slice(0,4),r=e.viewed.slice(0,4);t.querySelector(":scope > .cal-welcome__body")?.remove();const i=s("div","cal-welcome__body");if(0===g.thread.length&&o.length>0){const t=gt("Pick up where you left off"),e=s("div","cal-welcome__chips");for(const[t,{q:r}]of o.entries()){const o=s("button",`cal-chip ${0===t?n.classes.buttonPrimary:n.classes.buttonSecondary}`,r);o.type="button",o.dataset.callimacusAsk=r,e.append(o)}t.append(e),i.append(t)}const a=0===g.thread.length&&r.length>0?n.cards(r.map(t=>({handle:t.handle,title:t.title})),E):void 0;if(a){const t=gt("Recently viewed"),e=s("div","cal-welcome__cards");e.append(a),t.append(e),i.append(t)}t.hidden=0===i.childNodes.length,t.hidden||t.append(i)}();const _t=y(xt.dataset.askOnLoad);return""!==_t&&Do(g.thread)?.question!==_t&&V(_t,{type:"question"}),k("callimacus:ready",{designMode:!1,off:!1}),{page:St,destroy:w}}const qr="callimacus.pending";function $r(){return document.querySelector("#callimacus-config")??void 0}async function Nr(){const t=document.documentElement,n=function(){try{const t=JSON.parse($r()?.textContent??"{}");return u(t)?t:{}}catch{return{}}}(),r=function(t){return{cards:"own"===t.cards?"own":"auto",proxyBase:""===y(t.proxyBase)?"/apps/callimacus":y(t.proxyBase),searchTerms:y(t.searchTerms),template:y(t.template),starters:Array.isArray(t.starters)?t.starters.map(t=>y(t)).filter(t=>""!==t):[],designMode:!0===t.designMode,assistantLabel:""===y(t.assistantLabel)?"Ask":y(t.assistantLabel)}}(n),s=globalThis.Shopify?.theme?.id,a="number"==typeof s||"string"==typeof s?String(s):"",c=ne(r.proxyBase,a),d=()=>void 0!==Yt()||!t.hasAttribute(Cr),l=d()?void 0:async function(){const t=Vo();if(void 0!==t?.customerPrivacy||"function"!=typeof t?.loadFeatures)return;const{loadFeatures:n}=t;await new Promise(t=>{const o=setTimeout(t,1e3),r=()=>{clearTimeout(o),t()};try{n([{name:"consent-tracking-api",version:"0.2"}],r)}catch(t){e.warn("Shopify's privacy API did not load",t),r()}})}(),h=d()?void 0:await c.known(),p=h?.entrance&&{...h.entrance,starters:r.starters.length>0?r.starters:h.entrance.starters.slice(0,4)};let f;p&&0===r.starters.length&&p.starters.length>0&&function(t,e){const n=$r();n&&(n.textContent=JSON.stringify({...t,...e}))}(n,{starters:p.starters}),t.dataset.callimacusTemplate=r.template,d()||(f=await Ye({page:"product"!==r.template||r.designMode?"other":"product",stored:h?.look,post:async t=>async function(t,n,o){const r=await fetch(`${t}/look?theme_id=${encodeURIComponent(n)}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({tokens:o})});if(!r.ok)return void e.warn(`the store did not keep the look (${r.status})`);const i=await r.json();if(!u(i))return;const s=Zt(i.look);return s&&{stored:!0===i.stored,look:s}}(r.proxyBase,a,t),keep(t){c.keepLook(t)}}));const m=zt(r.assistantLabel),g=Vt({template:r.template,searchTerms:r.searchTerms,assistantLabel:r.assistantLabel,entrance:p}),b=Mt(r.cards);await l;const{page:v}=Or({kit:b,renderers:yt(b),session:c});Object.assign(v,{style:f,embed:{header:m,stage:g,...b.stats}});const w=o("sessionStorage",qr);i("sessionStorage",qr),void 0!==w&&""!==w.trim()&&v.ask(w)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Nr()},{once:!0}):Nr()}();
|
|
21
|
+
const yo="chapter-event",bo="story-created",vo="error",wo="server-response",ko="client-ready",So="user-interaction",Ao={debug:0,info:1,warn:2,error:3,silent:4},xo=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&&Ao[t]>=Ao[this.config.level]))return;const{prefix:n}=this.config,o=void 0===n||""===n?e:[n,...e];console[t](...o)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function _o(){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 n=[...e].map(t=>t.toString(16).padStart(2,"0"));return[n.slice(0,4).join(""),n.slice(4,6).join(""),n.slice(6,8).join(""),n.slice(8,10).join(""),n.slice(10,16).join("")].join("-")}var Co,Eo;!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"}(Co||(Co={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Eo||(Eo={}));const Ro={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class To{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??Ro.minVisibilityRatio;this.config={productSelector:t.productSelector??Ro.productSelector,blockSelector:t.blockSelector??Ro.blockSelector,maxTrackedElements:t.maxTrackedElements??Ro.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 xo.warn("UI Observer: invalid selector, skipping rescan:",t)}const n=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),o=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:o>=this.config.minVisibilityRatio,visibilityRatio:o,observedAt:n})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),o=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:o>=this.config.minVisibilityRatio,visibilityRatio:o,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).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 n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).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 n=this.resolveElementId(t),o=this.resolveBlockId(t),r=this.createTrackingKey(n,o),i=this.elementKeys.get(t);void 0!==i&&""!==i&&i!==r&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(t,r),this.elementRefs.set(r,t),this.elements.set(r,{id:n,blockId:o,trackingKey:r,...e})}syncTrackedBlock(t,e){const n=this.resolveTrackedBlockId(t),o=this.blockKeys.get(t),r=n;void 0!==o&&""!==o&&o!==r&&(this.blocks.delete(o),this.blockRefs.delete(o)),this.blockKeys.set(t,r),this.blockRefs.set(r,t),this.blocks.set(r,{id:n,...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)),n=t.width*t.height;if(n<=0)return 0;const o=window.innerWidth*window.innerHeight,r=o>0?Math.min(n,o):n;return Math.min(1,Math.max(0,e/r))}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=[],n=Date.now();for(const[e,n]of this.elements){const o=this.elementRefs.get(e);o?.isConnected?n.visibilityRatio<=0||t.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,n]of this.blocks){const o=this.blockRefs.get(t);o?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||e.push(n.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const o=t.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...o.flatMap(t=>t.blockId??[])])],elements:o.map(t=>t.element)}}}class Oo{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=Ro;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{xo.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(ko)}),this.socket.on("disconnect",()=>{xo.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:n,reason:o}=e;return"number"==typeof n?{code:n,..."string"==typeof o&&{reason:o}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(xo.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(vo,t=>{xo.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{xo.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{xo.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{xo.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{xo.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(wo,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){xo.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){xo.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&&(xo.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,xo.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){xo.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return xo.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new To(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),n=new URL("thamyr",e).pathname;return{origin:e.origin,path:n}}connect(t="wss://localhost:4000",e,n){this.socket&&(xo.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const o=this.socketEndpoint(t);let r;"undefined"!=typeof window&&void 0!==globalThis.location&&(r=globalThis.location.href);const i="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),s={...void 0!==r&&""!==r&&{referrer:r},...void 0!==i&&{intentSid:i},...n};xo.info("Connecting to Thamyr at",o),this.socket=go(o.origin,{path:o.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:s}),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),xo.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Ro,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 To(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void xo.error("Socket is not connected. Cannot send interaction.");if(t===Co.SUGGEST)return void xo.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Co.BACK_FROM_ROUND&&void 0===e.chapterId)return void xo.error("BACK_FROM_ROUND requires chapterId.");const n={type:t,payload:this.enrichPayloadWithUiContext(e)},o={id:_o()};this.socket.emit(So,{type:n.type,payload:n.payload},o.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(So,{type:Co.SUGGEST,payload:t}))}catch(t){return xo.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const qo=["hero","answer","picks","topic","cross","next","other"],$o=["hero","answer","picks","topic","cross","next"],No=new Map([["custom:editorialHero","hero"],["custom:storefrontReply","answer"],["custom:pageAnswer","answer"],["demosthenesResponse","answer"],["custom:demosthenesResponse","answer"],["custom:storefrontPicks","picks"],["custom:collectionGrid","picks"],["custom:problemGuide","topic"],["custom:materialStory","topic"],["custom:sizeCare","topic"],["custom:compareSet","topic"],["custom:storyCards","topic"],["custom:completeSet","cross"],["custom:followUps","next"]]);function Lo(t){return"object"==typeof t&&null!==t&&"string"==typeof t.type&&"function"==typeof t.render}function Bo(t){const e=globalThis.callimacusRenderers;if(Array.isArray(e))for(let n=e.length-1;n>=0;n--){const o=e[n];if(Lo(o)&&o.type===t)return o}}function Io(t,n){const o=new Map(t.map(t=>[t.type,t])),r=function(t){return{type:"*",render(e,n){const o=n.text(e);if(""===o)return;const r=s("div",`cal-fallback-note ${t.pageWidth}`),i=s("div",`cal-fallback-note__body ${t.rte}`);return d(i,o),r.append(i),r},update(t,e,n){const o=n.text(e),r=t instanceof Element?t.querySelector(".cal-fallback-note__body"):void 0;return!(""===o||!r||(r.replaceChildren(),d(r,o),0))}}}(n),i=new Set;return t=>{const n=Bo(t)??o.get(t)??Bo("*")??o.get("*");return n||(No.has(t)?void(i.has(t)||(i.add(t),e.warn(`no renderer for ${t}, skipped`))):r)}}function Mo(t,n,o){try{const r=t.render(n,o);return r instanceof Node?r:void(null!=r&&e.error(`renderer for ${n.type} returned something that is not a Node, skipped`))}catch(t){return e.error(`renderer for ${n.type} threw in render()`,t),!1}}function jo(t,e,n){const o=s("article","cal-chapter");o.dataset.chapterIndex=String(e.index),void 0!==e.id&&(o.dataset.chapterId=e.id);const r=`CallimacusChapter-${t}`,i=s("header",`cal-chapter__head ${n.pageWidth}`),c=s("h2","cal-chapter__heading"),d=s("button","cal-chapter__toggle");d.type="button",d.setAttribute("aria-expanded","true"),d.setAttribute("aria-controls",r),d.append(s("span","cal-chapter__question",e.question)),void 0!==e.about&&d.append(s("span","cal-chapter__about",`About: ${e.about}`));const l=s("span","cal-chapter__thumbs");l.setAttribute("aria-hidden","true"),d.append(l,function(t,e,n){const o=document.createElementNS(a,"svg");o.setAttribute("viewBox",t),o.setAttribute("fill","none"),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false"),o.setAttribute("class",n);const r=document.createElementNS(a,"path");return r.setAttribute("d",e),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","1.4"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),o.append(r),o}("0 0 16 16","M4 6l4 4 4-4","cal-chapter__chevron")),c.append(d),i.append(c);const u=s("div","cal-chapter__body");u.id=r;const h=new Map;for(const t of qo){const e=s("div","cal-slot");e.dataset.slot=t,h.set(t,e),u.append(e)}return o.append(i,u),{key:t,id:e.id,question:e.question,about:e.about,sent:e.sent??e.question,index:e.index,status:e.status??0,blocks:e.blocks??[],nodes:new Map,slots:h,el:o,body:u,toggle:d,thumbs:l,timing:void 0}}function Uo(t,e){const n=t.slots.get(e);if(!n)throw new Error(`chapter has no ${e} slot`);return n}function Fo(t,e){t.el.dataset.state=e,t.el.setAttribute("aria-busy",String("streaming"===e))}function Do(t){let e;for(const n of t)(!e||n.index>e.index)&&(e=n);return e}function Po(t){return t.blocks.map((t,e)=>({block:t,position:e})).sort((t,e)=>{const n=(t.block.priority??0)-(e.block.priority??0);return 0===n?t.position-e.position:n}).map(({block:t})=>t)}function Wo(t,e=""){return"string"==typeof t&&""!==t.trim()?t.trim():e}function zo(t,n){let o=t.language;try{Intl.NumberFormat.supportedLocalesOf(o)}catch{e.warn(`invalid language "${o}", formatting prices with "en"`),o="en"}const r=new Map;const i=t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl;return{settings:t,text(t){for(const e of A(t)){if(m(e))return e.trim();if(u(e)&&m(e.text))return e.text.trim()}return""},hits:t=>v(Array.isArray(t)?t:[t]),picks(t){for(const e of A(t)){if(!Array.isArray(e))continue;const t=v(e);if(t.length>0)return t}return[]},money(n){const i="number"==typeof n?n:n?.amount;if(void 0===i||""===i)return"";const s=Number(i);if(!Number.isFinite(s))return"";const a="object"==typeof n?n.currency:void 0,c=function(t){if(!r.has(t))try{r.set(t,new Intl.NumberFormat(o,{style:"currency",currency:t}))}catch{e.warn(`invalid currency "${t}", showing bare amounts`),r.set(t,void 0)}return r.get(t)}(void 0===a||""===a?t.currency:a);return c?c.format(s):s.toFixed(2)},url(t){const e=void 0===t?"":function(t){if(!h(t)){const e=u(t.meta)?t.meta.url:void 0;return"string"==typeof e&&/^\/(?!\/)/u.test(e)&&!/[\s\\]/u.test(e)?e:""}const e=encodeURIComponent(t.fields["shopify-handle"]);switch(p(t)){case"product":return`/products/${e}`;case"collection":return`/collections/${e}`;case"article":{const n=g(t.fields["shopify-blogHandle"]);return""===n?"":`/blogs/${encodeURIComponent(n)}/${e}`}default:return""}}(t);return""===e?"":`${i}${e}`},imageUrl(t,{width:e=800,index:n=0}={}){const o=t?.fields.images;if(!Array.isArray(o)||0===o.length)return"";const r=o[n]?.url??o[0]?.url;return"string"!=typeof r||""===r?"":`${r.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields.variantTree?.variants;if(!Array.isArray(e)||0===e.length)return"";const n=e.find(t=>!0===t?.orderable)??e[0];return void 0===n?.id?"":String(n.id).split("/").pop()??""},addToCart:n.addToCart,ask:n.ask,remember:n.remember}}function Vo(){return globalThis.Shopify}function Ho(){try{const t=Vo()?.customerPrivacy?.preferencesProcessingAllowed?.();return void 0===t?"unknown":!0===t?"allowed":"refused"}catch{return"unknown"}}function Ko(t){return o("sessionStorage",t)??("allowed"===Ho()?o("localStorage",t):void 0)}function Jo(t){const n=Ko(t);if(void 0!==n&&""!==n)try{return JSON.parse(n)}catch{return void e.warn(`ignoring unreadable "${t}"`)}}function Yo(t,e){const n=r("sessionStorage",t,e);return"allowed"!==Ho()||r("localStorage",t,e)||i("localStorage",t),n}function Go(t){i("localStorage",t),i("sessionStorage",t)}function Xo(t){const e=Ho();if("unknown"!==e)for(const n of t){if("allowed"===e){const t=o("sessionStorage",n);void 0!==t&&r("localStorage",n,t);continue}const t=o("localStorage",n);void 0!==t&&(void 0===o("sessionStorage",n)&&r("sessionStorage",n,t),i("localStorage",n))}}const Zo="callimacus.memory",Qo=6,tr=12,er=12,nr=new TextEncoder;function or(t){return Array.isArray(t)?t.filter(t=>u(t)):[]}function rr(t){return"number"==typeof t&&Number.isFinite(t)?t:0}function ir(){const t=Jo(Zo),e=u(t)?t:{};return{questions:or(e.questions).filter(t=>"string"==typeof t.q).map(t=>({q:t.q,at:rr(t.at)})),viewed:or(e.viewed).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,title:"string"==typeof t.title?t.title:"",at:rr(t.at)})),added:or(e.added).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,at:rr(t.at)}))}}function sr(t){return"string"==typeof t?t:u(t)&&"string"==typeof t.handle?t.handle:""}function ar(t,n){const o=ir(),r=Date.now();switch(t){case"questions":case"question":{const t="string"==typeof n?n.trim():"";if(""===t)return;o.questions=[{q:t,at:r},...o.questions.filter(e=>e.q!==t)].slice(0,12);break}case"viewed":{const t=sr(n);if(""===t)return;const e=u(n)&&"string"==typeof n.title?n.title:"";o.viewed=[{handle:t,title:e,at:r},...o.viewed.filter(e=>e.handle!==t)].slice(0,12);break}case"added":{const t=sr(n);if(""===t)return;o.added=[{handle:t,at:r},...o.added.filter(e=>e.handle!==t)].slice(0,12);break}default:return void e.warn(`remember() does not know "${t}"`)}Yo(Zo,JSON.stringify(o))}function cr(t,e){const n=t=>t.slice(0,200),o=t=>t.length<=200,r={questions:t.questions.map(t=>t.q).filter(t=>t!==e).slice(0,Qo).map(t=>n(t)),viewed:t.viewed.filter(t=>o(t.handle)).slice(0,tr).map(({handle:t,title:e})=>""===e?{handle:t}:{handle:t,title:n(e)}),added:t.added.map(t=>t.handle).filter(t=>o(t)).slice(0,er)};for(;nr.encode(JSON.stringify(r)).length>4096;){let t="viewed";for(const e of["added","questions"])r[e].length>r[t].length&&(t=e);r[t].pop()}return r}function dr(t){return s("div",`cal-skeleton__bone cal-skeleton__bone--${t}`)}function lr(t,e){const n=s("ul",e.grid(t));for(let o=0;o<t;o++){const t=s("li",e.gridItem),o=s("div","cal-skeleton__card");o.append(dr("media"),dr("title"),dr("price")),t.append(o),n.append(t)}return n}function ur(){const t=s("div","cal-skeleton__lines");return t.append(dr("line"),dr("line"),dr("line")),t}function hr(t,e,n){const o=s("div","cal-skeleton");o.dataset.skeleton=t,o.setAttribute("aria-hidden","true");const r=s("div","cal-skeleton__inner"),i="hero"===t&&0===e,a=s("div",i?"cal-skeleton__content":`cal-skeleton__content${"hero"!==t||i?"":" cal-skeleton__content--row"} ${n.pageWidth}`);return a.append(...function(t,e,n){switch(t){case"hero":return e?[dr("hero")]:[dr("lead"),ur()];case"answer":return[ur()];case"picks":return[lr(4,n)];case"topic":return[dr("topic")];case"cross":return[lr(3,n)];case"next":{const t=s("div","cal-skeleton__chips");return t.append(dr("chip"),dr("chip"),dr("chip")),[t]}case"other":return[]}}(t,i,n)),r.append(a),o.append(r),o}const pr="callimacus.thread",fr="callimacus.storyId",mr=15e5;function gr(t){return Array.isArray(t)?t.filter(t=>u(t)&&"string"==typeof t.id&&""!==t.id):[]}function yr(t){const e=t.inputEvent;return u(e)&&u(e.data)?y(e.data.value):""}function br(t){const e=t.lastIndexOf(" (about the ");if(-1===e||!t.endsWith(")"))return{question:t,about:void 0};const n=t.slice(e+12,-1);return""===n?{question:t,about:void 0}:{question:t.slice(0,e),about:n}}function vr(t){const e=Number(t);return Number.isFinite(e)?e:0}function wr(){return Ko(fr)}function kr(t){void 0===t?Go(fr):Yo(fr,t)}function Sr(){const t=Jo(pr);return Array.isArray(t)?t.filter(t=>u(t)&&"string"==typeof t.question).map(t=>t).map(t=>{const e=t.question;return{id:""===y(t.id)?void 0:y(t.id),question:e,about:""===y(t.about)?void 0:y(t.about),sent:""===y(t.sent)?e:y(t.sent),index:vr(t.index),status:vr(t.status),blocks:gr(t.blocks)}}).sort((t,e)=>t.index-e.index).slice(-12):[]}function Ar(t){return Math.round(performance.now()-t.t0)}const xr=4e3,_r=[pr,fr,Zo],Cr="data-callimacus-on",Er=new Set([401,403]),Rr=new Set(["invalid_token","origin_not_allowed","paused"]);function Tr(t){return"function"==typeof globalThis.matchMedia?globalThis.matchMedia(t):{matches:!1}}function Or(t){const{kit:n}=t,o=t.roundTimeoutMs??45e3,r=t.createTransport??(()=>new Oo),i=function(){let t={};try{const e=JSON.parse(document.querySelector("#callimacus-config")?.textContent??"{}");t=u(e)?e:{}}catch(t){e.error("#callimacus-config is not valid JSON",t)}const n=globalThis.Shopify,o=u(t.product)&&""!==Wo(t.product.handle)?Object.freeze({handle:Wo(t.product.handle),title:Wo(t.product.title),id:"number"==typeof t.product.id||"string"==typeof t.product.id?t.product.id:void 0}):void 0,r=Wo(t.storeName,"this store");return Object.freeze({language:Wo(t.language,"en"),rootUrl:Wo(t.rootUrl,"/"),cartAddUrl:Wo(t.cartAddUrl,"/cart/add"),currency:Wo(t.currency,"USD"),designMode:!0===t.designMode||Boolean(n?.designMode),template:Wo(t.template),product:o,storeName:r,assistantLabel:Wo(t.assistantLabel,`Ask ${r}`),starters:Object.freeze(Array.isArray(t.starters)?t.starters.map(t=>Wo(t)).filter(t=>""!==t):[])})}(),a=function(t){return{connecting:"Connecting…",asking:"Thinking…",streaming:"Composing your answer…",done:"Answer ready.",queued:t=>`Queued: “${t}”. I’ll ask that next.`,queueFull:"Still answering. Ask again in a moment.",dequeued:"Removed from the queue.",timeout:"This is taking longer than usual. Try asking again.",failed:"Something went wrong. Please try again.",reconnecting:"Reconnecting…",unavailable:`${t.assistantLabel} is unavailable right now. Please try again later.`,trimmed:"Earlier answers were trimmed from this conversation.",designMode:`${t.assistantLabel} answers on the live store, not in the theme editor.`,interrupted:"This answer stopped before it was finished.",unanswered:`${t.storeName} could not answer that just now.`}}(i),c=document.documentElement,d=new AbortController,{signal:h}=d,p=[],f=Tr("(prefers-reduced-motion: reduce)"),m=Tr("(pointer: coarse)"),g={ui:"idle",storyId:void 0,isConnected:!1,isOff:!1,thread:[],round:void 0,queue:[],about:i.product?.title,hydrateMode:void 0,refreshTimer:void 0,lastAsk:void 0,statusTimer:void 0,nextKey:0},b=[],v=Io(t.renderers,n.classes);function w(){d.abort();for(const t of p)t.disconnect();clearTimeout(g.refreshTimer),clearTimeout(g.statusTimer),clearTimeout(g.round?.timer)}function k(t,e){document.dispatchEvent(new CustomEvent(t,{detail:e}))}function S(t){g.ui!==t&&(g.ui=t,c.dataset.callimacusState=t,k("callimacus:state",{state:t}))}function A(t,{clearAfter:e=0}={}){clearTimeout(g.statusTimer);for(const e of document.querySelectorAll("[data-callimacus-status]"))e.textContent=t;e>0&&(g.statusTimer=setTimeout(()=>{A("")},e))}function C(t){g.storyId=""===t?void 0:t,kr(g.storyId)}const E=zo(i,{addToCart:async function(t,e=1){const o=String(t).split("/").pop()??"";if(!/^\d+$/u.test(o))throw new Error("This product cannot be added right now.");const r=await n.addToCart(o,e,i);return"string"==typeof r.handle&&""!==r.handle&&ar("added",r.handle),r},ask:t=>"refused"!==V(t,{type:"relatedQuestion"}),remember:ar});const R={stage:void 0,thread:void 0,earlier:void 0,trimmed:void 0,dock:document.querySelector("[data-callimacus-dock]")??void 0};function T(){return R.stage?.dataset.stageKind??"page"}function O(){let t=document.querySelector("[data-callimacus-stage]")??void 0;t||(t=s("div","cal-stage"),t.dataset.callimacusStage="",t.dataset.stageKind="page",t.dataset.callimacusUi="",(document.querySelector("#MainContent")??document.body).prepend(t));let e=t.querySelector("[data-callimacus-thread]")??void 0;e||(e=s("div","cal-thread"),e.dataset.callimacusThread="",t.append(e)),e.classList.add("cal-thread");const o=s("button",`cal-thread__earlier ${n.classes.pageWidth}`);o.type="button",o.hidden=!0,o.addEventListener("click",()=>{$(!1)},{signal:h});const r=s("p",`cal-thread__trimmed ${n.classes.pageWidth}`,a.trimmed);return r.hidden=!0,e.after(o,r),Object.assign(R,{stage:t,thread:e,earlier:o,trimmed:r}),{stage:t,thread:e}}function q(){return R.thread??O().thread}function $(t){R.thread&&(R.thread.toggleAttribute("data-compact",t),N())}function N(){if(!R.earlier||!R.thread||!R.trimmed)return;const t=g.thread.length-1,e=Object.hasOwn(R.thread.dataset,"compact"),n=e&&t>0;R.earlier.hidden=!n,n&&(R.earlier.textContent=`Show ${t} earlier question${1===t?"":"s"}`),R.trimmed.hidden=e||0===g.thread.length||g.thread.some(t=>0===t.index)}function L(){const t=new Set([...g.thread].sort((t,e)=>e.index-t.index).slice(12));for(const e of t)e.el.remove();g.thread=g.thread.filter(e=>!t.has(e))}function B(t){g.nextKey+=1;const e=jo(g.nextKey,t,n.classes);return e.toggle.addEventListener("click",()=>{M(e,Object.hasOwn(e.el.dataset,"collapsed"))},{signal:h}),e}function I(t){for(const e of $o){const o=Uo(t,e);o.querySelector(":scope > .cal-block, :scope > .cal-skeleton")||o.append(hr(e,t.index,n.classes))}}function M(t,e,{shouldAnimate:n=!0}={}){e!==!Object.hasOwn(t.el.dataset,"collapsed")&&(e||t.thumbs.replaceChildren(...function(t){const e=new Set,n=[],o=Po(t).flatMap(t=>E.picks(t));for(const t of o){if(4===n.length)break;const o=t.fields["shopify-handle"],r=E.imageUrl(t,{width:160});if(""===r||e.has(o))continue;e.add(o);const i=s("img","cal-chapter__thumb");i.src=r,i.alt="",i.loading="lazy",i.decoding="async",i.width=40,i.height=50,n.push(i)}return n}(t)),t.el.toggleAttribute("data-collapsed",!e),t.toggle.setAttribute("aria-expanded",String(e)),t.body.inert=!e,e&&n&&!f.matches&&(t.el.dataset.animating="",setTimeout(()=>{delete t.el.dataset.animating},360)))}function j(t){const e=t.el,n=()=>{t.el.style.setProperty("--cal-header-height",`${function(){if("function"!=typeof document.elementsFromPoint)return 0;const t=document.documentElement.clientWidth;let e=0;for(const n of[.25,.5,.75])for(const o of document.elementsFromPoint(Math.round(t*n),1)){const t=l(o)?.getBoundingClientRect();t&&t.top<=1&&t.bottom>e&&t.bottom<globalThis.innerHeight/2&&(e=t.bottom)}return Math.round(e)}()}px`),e.scrollIntoView?.({behavior:f.matches?"auto":"smooth",block:"start"})};"function"==typeof requestAnimationFrame?requestAnimationFrame(n):n()}function U(t,e){const o=t.body.querySelector(":scope > .cal-chapter__note");if(!e)return void o?.remove();if(o)return;const r=s("div",`cal-chapter__note ${n.classes.pageWidth}`);r.append(s("p","",t.blocks.length>0?a.interrupted:a.unanswered));const i=s("button","cal-chapter__retry","Ask again");i.type="button",i.addEventListener("click",()=>{V(t.question,{type:"question",about:t.about})},{signal:h}),r.append(i),t.body.append(r)}function F(t,e,n,o){const r=Uo(t,No.get(e.type)??"other"),i=s("div","cal-block");i.dataset.blockId=e.id,i.dataset.blockType=e.type,i.dataset.order=String(o.order),i.append(n),r.querySelector(":scope > .cal-skeleton")?.remove();const a=[...r.children].find(t=>Number(t.dataset.order)>o.order);if(a?a.before(i):r.append(i),o.shouldAnimate&&!f.matches){const t=60*o.stagger;i.style.setProperty("--cal-stagger",`${t}ms`),i.dataset.arriving="",setTimeout(()=>{delete i.dataset.arriving,i.style.removeProperty("--cal-stagger")},240+t+60)}var c;return c=t.timing,"pending"===c?.outcome&&void 0===c.firstBlockMs&&(c.firstBlockMs=Ar(c),performance.mark(`callimacus:chapter-${c.chapter}:first-block`)),k("callimacus:block",{chapterId:t.id,blockId:e.id,type:e.type,node:n}),i}function D(t,n,o,r){const i=v(n.type);if(!i||!x(n))return!1;const s=JSON.stringify(n.data);let a=t.nodes.get(n.id);if(a?.wrap&&(a.wrap.dataset.order=String(r.order)),!0===a?.isBroken)return!1;if(void 0===a?.node){if(a?.signature===s&&!r.hasBecomeDone)return!1;const e=Mo(i,n,o);return a={signature:s,node:!1===e?void 0:e,wrap:void 0,isBroken:!1===e},t.nodes.set(n.id,a),a.node?(a.wrap=F(t,n,a.node,r),!0):!1}if(s===a.signature&&!r.hasBecomeDone)return!1;if(a.signature=s,function(t,n,o,r){if("function"!=typeof t.update)return!1;try{return t.update(n,o,r)}catch(t){return e.error(`renderer for ${o.type} threw in update()`,t),!1}}(i,a.node,n,o))return!1;const c=Mo(i,n,o);return!1===c?a.isBroken=!0:c&&a.wrap&&(a.wrap.replaceChildren(c),a.node=c),!1}function P(t,{hasBecomeDone:e=!1,shouldAnimate:n=!0}={}){const o=function(t){const e=4===t.status,n=Object.freeze({id:t.id,index:t.index,isFirst:0===t.index,question:t.question,done:e,blocks:Object.freeze([...t.blocks])});return Object.freeze({...E,chapter:n,final:e})}(t);let r=0;for(const[i,s]of Po(t).entries())D(t,s,o,{order:i,stagger:r,hasBecomeDone:e,shouldAnimate:n})&&(r+=1)}const W=function(t){let n,o=!1,r=!1,i=0;const s=[];function a(n,r=t.session.current()){o=!1,r.then(e=>{if(!t.isOff()){if(!e)return s.length=0,void t.onRefused();n.connect(e.endpoint,{Authorization:`Bearer ${e.token}`},{token:e.token}),o=!0;for(const t of s.splice(0))t(n)}}).catch(n=>{e.warn("no storefront session",n),s.length=0,t.onError({code:503,reason:"retries_exhausted",message:"no storefront session"})})}function c(){if(n)return r&&(r=!1,a(n)),n;const e=t.createTransport();return e.onServerResponse(t.onResponse),e.onError(t.onError),e.onConnectionStatus(t.onStatus),n=e,a(e),e}return{connect:c,send:function(t,e){const n=c();o?n.sendUserInteraction(t,e):s.push(n=>{n.sendUserInteraction(t,e)})},markFailed(){r=!0},didRenew:function(){const o=Date.now();return!(!n||o-i<6e4||(i=o,e.info("the storefront token expired; asking the store for a fresh one"),a(n,t.session.renew()),0))}}}({session:t.session,createTransport:r,onResponse:function(t){const n=t;n.type===bo?function(t){if(!u(t)||"string"!=typeof t.id||""===t.id)return;t.id!==g.storyId&&C(t.id);const e=(Array.isArray(t.chapters)?t.chapters:[]).filter(t=>u(t)&&"string"==typeof t.id&&""!==t.id&&!0!==t.deleted).map(t=>t);e.length>0?function(t){const e="restore"===g.hydrateMode;let n=!1;for(const o of t.slice(-12)){const r=t.indexOf(o),i=g.thread.find(t=>t.id===o.id)??G(o);if(i){e&&rt(i,r),X(i,o,g.round?.rec===i);continue}const s=yr(o);if(!e||""===s)continue;const{question:a,about:c}=br(s);nt({id:o.id,question:a,about:c,sent:s,index:r,status:"number"==typeof o.status?o.status:0,blocks:gr(o.blocks)}),n=!0}if(n){const e=new Set(t.map(t=>t.id));let n=t.length;for(const t of g.thread)e.has(t.id)||rt(t,n++);mt(),ot(),et()}e&&(g.hydrateMode="refresh")}(e):"restore"===g.hydrateMode&&(g.hydrateMode="refresh")}(n.story):n.type===yo?function(t){if(!u(t)||"string"!=typeof t.id||""===t.id||!0===t.deleted)return;const n=g.thread.find(e=>e.id===t.id)??G(t);n?X(n,t,!0):e.debug("chapter-event for a chapter this page does not show",t.id)}(n.chapter):e.debug("ignored server response",n.type)},onError:function(t){const{code:n}=t;if(e.warn("server error",n,t.message??"",t.reason??""),"token_expired"===t.reason&&W.didRenew())return;if(function(t){return Er.has(t.code)&&(!g.isConnected||Rr.has(t.reason??""))}(t))return void z(t);const{round:r}=g;if(404===n&&(C(void 0),at({shouldFailPending:!0}),r&&!r.isRetried&&void 0===r.rec.id))return r.isRetried=!0,e.info("story not found, asking again as a new story"),clearTimeout(r.timer),r.timer=setTimeout(()=>{Y(r)},o),void J(r);const i=!g.isConnected;if(i&&"retries_exhausted"!==t.reason&&!(n>=400&&n<500))return void(r&&A(a.reconnecting));i&&W.markFailed();r?(A(i?a.unavailable:a.failed),Z(r.rec,"error")):i&&(S("error"),A(a.unavailable))},onStatus:function(t){g.isConnected=t;const{round:e}=g;if(!t||!e||void 0!==e.rec.timing?.firstEventMs)return;S("asking"),A(a.asking)},isOff:()=>g.isOff,onRefused(){const{status:t,reason:e}=Yt()??{status:401,reason:"invalid_token"};z({code:t,reason:e})}});function z(t){const n="paused"===t.reason;if(e.warn(`the store refused this storefront (${String(t.code)} ${t.reason??""}); the theme's own search is back`),g.isOff=!0,Jt({status:t.code,reason:t.reason}),at(),g.queue=[],ut(),g.round&&Z(g.round.rec,"error"),S("error"),n){for(const t of document.querySelectorAll('[data-callimacus-form] input[name="q"], [data-callimacus-form] [type="submit"], [data-callimacus-open], button[data-callimacus-ask]'))t.disabled=!0;A(a.unavailable)}else c.removeAttribute(Cr),A("");k("callimacus:off",{code:t.code,reason:t.reason})}function V(t,{type:e="question",about:n}={}){const o=y(t),r=function(t){if(""===t||g.isOff)return"";if(i.designMode)return a.designMode;const e=Date.now();return g.lastAsk?.text===t&&e-g.lastAsk.at<600?"":(g.lastAsk={text:t,at:e},g.round&&g.queue.length>=3?a.queueFull:void 0)}(o);if(void 0!==r)return""!==r&&A(r,{clearAfter:r===a.unavailable?0:xr}),"refused";const s={display:o,about:n,type:e,sent:void 0===n?o:`${o} (about the ${n})`,visit:cr(ir(),o)};return ar("questions",o),k("callimacus:ask",{question:o,type:e,queued:Boolean(g.round)}),g.round?(g.queue.push(s),ut(),A(a.queued(o),{clearAfter:xr}),"queued"):(H(s),"sent")}function H(t){const e=B({question:t.display,about:t.about,sent:t.sent,index:K()});for(const t of g.thread)M(t,!1);g.thread.push(e),q().prepend(e.el),L(),Fo(e,"streaming"),I(e),mt(),lt(),N();const n={rec:e,type:t.type,visit:t.visit,timer:void 0,isRetried:!1};var r,i;g.round=n,e.timing=(r=e.index,i=e.question,performance.mark(`callimacus:chapter-${r}:sent`),{chapter:r,question:i,chapterId:void 0,sentAt:(new Date).toISOString(),firstEventMs:void 0,firstBlockMs:void 0,doneMs:void 0,outcome:"pending",t0:performance.now()}),b.push(e.timing),S(g.isConnected?"asking":"connecting"),A(g.isConnected?a.asking:a.connecting),n.timer=setTimeout(()=>{Y(n)},o),j(e),et(),k("callimacus:chapter",Q(e)),J(n)}function K(){let t=0;for(const e of g.thread)t=Math.max(t,e.index+1);return t}function J(t){try{W.connect()}catch(n){return e.error("could not start the Callimacus client",n),void(g.round===t&&(A(a.unavailable),Z(t.rec,"error")))}if(g.round===t)try{!function(t){const e={visit:t.visit},n={...void 0!==g.storyId&&{storyId:g.storyId},language:i.language,inputEvent:{type:t.type,data:{value:t.rec.sent}},context:e};W.send(Co.CREATE_ROUND,n)}(t)}catch(n){e.error("could not send the question",n),A(a.failed),Z(t.rec,"error")}}function Y(t){g.round===t&&(e.warn(`no complete answer within ${o/1e3} s for “${t.rec.question}”`),A(a.timeout),Z(t.rec,"timeout"))}function G(t){const e=yr(t),n=""===e?void 0===g.round?.rec.id?g.round?.rec:void 0:g.thread.findLast(t=>void 0===t.id&&t.sent===e);if(n&&"string"==typeof t.id)return n.id=t.id,n.el.dataset.chapterId=t.id,n}function X(t,e,n){const o=4===t.status;var r,i;t.blocks=function(t,e){const n=[...t];for(const t of e){const e=n.findIndex(e=>e.id===t.id);-1===e?n.push(t):n[e]=t}return n}(t.blocks,gr(e.blocks)),t.status="number"==typeof e.status?e.status:t.status,g.round?.rec===t&&void 0===t.timing?.firstEventMs&&(r=t.timing,i=t.id,r&&void 0===r.firstEventMs&&(r.firstEventMs=Ar(r),r.chapterId=i),S("streaming"),A(a.streaming));const s=!o&&4===t.status;P(t,{hasBecomeDone:s,shouldAnimate:n}),s&&Z(t,"done")}function Z(t,n){const o="done"!==n;Fo(t,o?"error":"done"),function(t){for(const e of t.body.querySelectorAll(":scope > .cal-slot > .cal-skeleton")){if(Object.hasOwn(e.dataset,"leaving"))continue;e.dataset.leaving="";const t=()=>{e.remove()};e.addEventListener("transitionend",t,{once:!0}),setTimeout(t,400)}}(t),U(t,o&&!g.isOff),function(t,n,o){if("pending"!==t?.outcome)return;t.outcome=o,t.chapterId=n,t.doneMs=Ar(t),performance.mark(`callimacus:chapter-${t.chapter}:${o}`);const{t0:r,...i}=t;e.debug("timing",i)}(t.timing,t.id,n),et(),k("callimacus:chapter",Q(t));const r=g.round?.rec===t?g.round:void 0;r&&(clearTimeout(r.timer),g.round=void 0,o?S("error"):(S("idle"),A(a.done,{clearAfter:xr})),function(){if(void 0!==g.round||g.isOff)return;const t=g.queue.shift();if(!t)return;ut(),H(t)}())}function Q(t){return{id:t.id,index:t.index,question:t.question,state:t.el.dataset.state}}function tt(t){return{id:t.id,question:t.question,about:t.about,sent:t.sent,index:t.index,status:t.status,blocks:t.blocks}}function et(){!function(t){if(0===t.length)return;const e=[...t].sort((t,e)=>t.index-e.index).slice(-12);let n=JSON.stringify(e);if(n.length>mr){for(const t of e)t.blocks=_(t.blocks);n=JSON.stringify(e)}for(;e.length>0;){if(n.length<=mr&&Yo(pr,n))return;e.shift(),n=JSON.stringify(e)}Go(pr)}(g.thread.map(t=>tt(t))),kr(g.storyId)}function nt(t){const e=B(t);g.thread.push(e);const n=4===e.status,o=!n&&void 0!==e.id&&void 0!==g.storyId;return Fo(e,n?"done":o?"streaming":"error"),o&&I(e),P(e,{shouldAnimate:!1}),n||o||U(e,!0),e}function ot(){L();const t=Do(g.thread),e="home"===T();for(const n of g.thread)M(n,e&&n===t||g.round?.rec===n,{shouldAnimate:!1});!function(){const t=[...g.thread].sort((t,e)=>e.index-t.index);q().append(...t.map(t=>t.el))}(),$(!e),lt()}function rt(t,e){t.index=e,t.el.dataset.chapterIndex=String(e)}function it(){return g.thread.filter(t=>void 0!==t.id&&4!==t.status&&g.round?.rec!==t&&"streaming"===t.el.dataset.state)}function st(t=0){clearTimeout(g.refreshTimer);const{storyId:n}=g;if(!(void 0===n||g.isOff||t>0&&"restore"!==g.hydrateMode&&0===it().length))if(t>=6)at({shouldFailPending:!0});else{try{W.send(Co.GET_STORY,{storyId:n})}catch(t){e.error("could not start the Callimacus client",t)}g.refreshTimer=setTimeout(()=>{st(t+1)},3e3)}}function at({shouldFailPending:t=!1}={}){if(clearTimeout(g.refreshTimer),g.hydrateMode=void 0,t)for(const t of it())Z(t,"error")}const ct=t=>R.dock?.querySelector(t)??void 0,dt={input:ct('input[name="q"]'),chips:ct("[data-callimacus-dock-chips]"),count:ct("[data-callimacus-thread-count]"),countLabel:ct("[data-callimacus-thread-count-label]"),next:ct("[data-callimacus-next]"),nextLabel:ct("[data-callimacus-next-label]"),about:ct("[data-callimacus-about]"),aboutLabel:ct("[data-callimacus-about-label]")};function lt(){if(!dt.count)return;const t=g.thread.length;dt.count.hidden=0===t;const e=`${t} question${1===t?"":"s"}`;dt.countLabel&&(dt.countLabel.textContent=String(t)),dt.count.title=e,dt.count.setAttribute("aria-label",`${e} in this conversation. Show the conversation`)}function ut(){if(!dt.next)return;const[t]=g.queue;if(dt.next.hidden=void 0===t,void 0!==t){const e=g.queue.length>1?` (+${g.queue.length-1})`:"";dt.nextLabel&&(dt.nextLabel.textContent=`Next: ${t.display}${e}`),dt.next.setAttribute("aria-label",`Next question: ${t.display}. Remove it from the queue`)}dt.chips&&(dt.chips.hidden=[...dt.chips.children].every(t=>t instanceof HTMLElement&&!0===t.hidden))}function ht(){const t=g.about;dt.about&&(dt.about.hidden=void 0===t),void 0!==t&&dt.aboutLabel&&(dt.aboutLabel.textContent=`About: ${t}`),dt.input&&(dt.input.placeholder=void 0===t?dt.input.dataset.placeholder??dt.input.placeholder:"Ask anything about it")}function pt(){dt.input&&(dt.input.focus(),yt())}function ft(){$(!1);const t=Do(g.thread);t&&(M(t,!0),j(t))}function mt(){const t=document.querySelector("[data-callimacus-welcome]");t&&(t.hidden=!0)}function gt(t){const e=s("section","cal-welcome__group");return e.append(s("h2","cal-welcome__title",t)),e}function yt(){if(!i.designMode&&!g.isOff)try{W.connect()}catch(t){e.error("could not start the Callimacus client",t)}}function bt(){return!g.isOff&&c.hasAttribute(Cr)}function vt(t){const e=t.target instanceof Element?t.target.closest("[data-callimacus-form]"):void 0;if(!e||!bt())return;t.preventDefault();const n=e.querySelector('input[name="q"]'),o=n?.value.trim()??"";n&&""!==o?("refused"!==V(o,{type:"question",about:g.about})&&(n.value=""),m.matches&&n.blur()):n?.focus()}function wt(t){if(!(bt()&&t.target instanceof Element))return;const e=t.target.closest("[data-callimacus-ask]");if(e){const n=e.dataset.callimacusAsk?.trim()??"";return void(""!==n&&(t.preventDefault(),V(n,{type:"relatedQuestion"})))}t.target.closest("[data-callimacus-open]")&&(t.preventDefault(),pt())}function kt(t){var e;bt()&&("/"!==t.key||t.metaKey||t.ctrlKey||t.altKey||(e=t.target)instanceof Element&&null!==e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')?"Escape"===t.key&&t.target instanceof HTMLElement&&t.target.matches('[data-callimacus-form] input[name="q"]')&&t.target.blur():(t.preventDefault(),pt()))}const St={ask:t=>"refused"!==V(t,{type:"question"}),get thread(){return[...g.thread].sort((t,e)=>t.index-e.index).map(t=>tt(t))},ctx:E,timings:b,get state(){return g.ui},get storyId(){return g.storyId},reset:function(){at(),clearTimeout(g.round?.timer),g.round=void 0,g.queue=[];for(const t of g.thread)t.el.remove();g.thread=[],C(void 0),Go(pr),ut(),lt(),$(!1),S("idle"),A("")}};c.dataset.callimacusState=g.ui;const At=globalThis;if(At.callimacus=St,At.callimacusTheme={card:n.card,cards:n.cards},void 0!==Yt()||!c.hasAttribute(Cr))return c.removeAttribute(Cr),g.isOff=!0,S("error"),k("callimacus:ready",{designMode:i.designMode,off:!0}),{page:St,destroy:w};if(n.install?.(),function(t,e){Xo(t),document.addEventListener("visitorConsentCollected",()=>{Xo(t)},{signal:e})}(_r,h),g.storyId=wr(),document.addEventListener("submit",vt,{signal:h}),document.addEventListener("click",wt,{signal:h}),document.addEventListener("keydown",kt,{signal:h}),document.addEventListener("focusin",t=>{t.target instanceof Element&&t.target.matches('[data-callimacus-form] input[name="q"]')&&yt()},{signal:h}),dt.count?.addEventListener("click",ft,{signal:h}),dt.next?.addEventListener("click",()=>{g.queue.shift(),ut(),A(a.dequeued,{clearAfter:xr}),dt.input?.focus()},{signal:h}),R.dock?.querySelector("[data-callimacus-about-remove]")?.addEventListener("click",()=>{g.about=void 0,ht(),dt.input?.focus()},{signal:h}),function(){const{dock:t}=R;if(!t||"function"!=typeof ResizeObserver)return;const e=new ResizeObserver(()=>{c.style.setProperty("--cal-dock-space",`${Math.ceil(t.offsetHeight)}px`)});e.observe(t),p.push(e)}(),globalThis.addEventListener("pagehide",()=>{(void 0!==g.round||it().length>0)&&et()},{signal:h}),globalThis.addEventListener("pageshow",t=>{t.persisted&&function(){const t=t=>t.id??`${t.index}:${t.sent}`,e=new Set(g.thread.map(e=>t(e))),n=Sr().filter(n=>!e.has(t(n))),o=wr();if(void 0!==o&&o!==g.storyId&&(g.storyId=o),0!==n.length){for(const t of n)nt(t);mt(),ot(),N()}}()},{signal:h}),ht(),lt(),ut(),i.designMode)return k("callimacus:ready",{designMode:!0,off:!1}),{page:St,destroy:w};i.product&&ar("viewed",{handle:i.product.handle,title:i.product.title});const{stage:xt}=O();!function(){for(const t of Sr())nt(t);return 0!==g.thread.length&&(ot(),!0)}()?void 0!==g.storyId&&(g.hydrateMode="restore",st()):it().length>0&&(g.hydrateMode="refresh",st()),"home"===T()&&function(){const t=document.querySelector("[data-callimacus-welcome]");if(!t)return;const e=ir(),o=e.questions.slice(0,4),r=e.viewed.slice(0,4);t.querySelector(":scope > .cal-welcome__body")?.remove();const i=s("div","cal-welcome__body");if(0===g.thread.length&&o.length>0){const t=gt("Pick up where you left off"),e=s("div","cal-welcome__chips");for(const[t,{q:r}]of o.entries()){const o=s("button",`cal-chip ${0===t?n.classes.buttonPrimary:n.classes.buttonSecondary}`,r);o.type="button",o.dataset.callimacusAsk=r,e.append(o)}t.append(e),i.append(t)}const a=0===g.thread.length&&r.length>0?n.cards(r.map(t=>({handle:t.handle,title:t.title})),E):void 0;if(a){const t=gt("Recently viewed"),e=s("div","cal-welcome__cards");e.append(a),t.append(e),i.append(t)}t.hidden=0===i.childNodes.length,t.hidden||t.append(i)}();const _t=y(xt.dataset.askOnLoad);return""!==_t&&Do(g.thread)?.question!==_t&&V(_t,{type:"question"}),k("callimacus:ready",{designMode:!1,off:!1}),{page:St,destroy:w}}const qr="callimacus.pending";function $r(){return document.querySelector("#callimacus-config")??void 0}async function Nr(){const t=document.documentElement,n=function(){try{const t=JSON.parse($r()?.textContent??"{}");return u(t)?t:{}}catch{return{}}}(),r=function(t){return{cards:"own"===t.cards?"own":"auto",proxyBase:""===y(t.proxyBase)?"/apps/callimacus":y(t.proxyBase),searchTerms:y(t.searchTerms),template:y(t.template),starters:Array.isArray(t.starters)?t.starters.map(t=>y(t)).filter(t=>""!==t):[],designMode:!0===t.designMode,assistantLabel:""===y(t.assistantLabel)?"Ask":y(t.assistantLabel)}}(n),s=globalThis.Shopify?.theme?.id,a="number"==typeof s||"string"==typeof s?String(s):"",c=ne(r.proxyBase,a),d=()=>void 0!==Yt()||!t.hasAttribute(Cr),l=d()?void 0:async function(){const t=Vo();if(void 0!==t?.customerPrivacy||"function"!=typeof t?.loadFeatures)return;const{loadFeatures:n}=t;await new Promise(t=>{const o=setTimeout(t,1e3),r=()=>{clearTimeout(o),t()};try{n([{name:"consent-tracking-api",version:"0.2"}],r)}catch(t){e.warn("Shopify's privacy API did not load",t),r()}})}(),h=d()?void 0:await c.known(),p=h?.entrance&&{...h.entrance,starters:r.starters.length>0?r.starters:h.entrance.starters.slice(0,4)};let f;p&&0===r.starters.length&&p.starters.length>0&&function(t,e){const n=$r();n&&(n.textContent=JSON.stringify({...t,...e}))}(n,{starters:p.starters}),t.dataset.callimacusTemplate=r.template,d()||(f=await Ye({page:"product"!==r.template||r.designMode?"other":"product",stored:h?.look,post:async t=>async function(t,n,o){const r=await fetch(`${t}/look?theme_id=${encodeURIComponent(n)}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({tokens:o})});if(!r.ok)return void e.warn(`the store did not keep the look (${r.status})`);const i=await r.json();if(!u(i))return;const s=Zt(i.look);return s&&{stored:!0===i.stored,look:s}}(r.proxyBase,a,t),keep(t){c.keepLook(t)}}));const m=zt(r.assistantLabel),g=Vt({template:r.template,searchTerms:r.searchTerms,assistantLabel:r.assistantLabel,entrance:p}),b=Mt(r.cards);await l;const{page:v}=Or({kit:b,renderers:yt(b),session:c});Object.assign(v,{style:f,embed:{header:m,stage:g,...b.stats}});const w=o("sessionStorage",qr);i("sessionStorage",qr),void 0!==w&&""!==w.trim()&&v.ask(w)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Nr()},{once:!0}):Nr()}();
|
|
22
22
|
//# sourceMappingURL=callimacus.min.js.map
|