@callimacus/thamyr-shopify 4.18.0 → 4.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.core.md +14 -0
- package/CHANGELOG.md +28 -0
- package/README.md +22 -2
- package/dist/browser/callimacus.css +38 -0
- package/dist/browser/callimacus.min.js +3 -3
- package/dist/browser/callimacus.min.js.map +1 -1
- package/dist/browser/look-reader.min.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +2 -2
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
* See LICENSE.md for the full terms.
|
|
6
6
|
*
|
|
7
7
|
*/
|
|
8
|
-
!function(){"use strict";const t="[callimacus]",e={debug(...e){console.debug(t,...e)},info(...e){console.info(t,...e)},warn(...e){console.warn(t,...e)},error(...e){console.error(t,...e)}};function n(t){try{return globalThis[t]}catch{return}}function o(t,e){try{return n(t)?.getItem(e)??void 0}catch{return}}function r(t,o,r){try{const e=n(t);return!!e&&(e.setItem(o,r),!0)}catch(n){return e.warn(`could not write ${t} "${o}"`,n),!1}}function i(t,o){try{n(t)?.removeItem(o)}catch(n){e.warn(`could not clear ${t} "${o}"`,n)}}function s(t,e="",n){const o=document.createElement(t);return""!==e&&(o.className=e),void 0!==n&&(o.textContent=n),o}const a="http://www.w3.org/2000/svg";function c(t,e,n){const o=document.createElementNS(a,"svg");o.setAttribute("class",n),o.setAttribute("viewBox",t),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false");const r=document.createElementNS(a,"path");return r.setAttribute("d",e),r.setAttribute("fill","currentColor"),r.setAttribute("fill-rule","evenodd"),r.setAttribute("clip-rule","evenodd"),o.append(r),o}function d(t,e){for(const n of e.split(/\n{2,}/u)){const e=s("p");for(const[t,o]of n.split("**").entries())""!==o&&e.append(t%2==1?s("strong","",o):document.createTextNode(o));e.childNodes.length>0&&t.append(e)}}function l(t){for(let e=t;e&&e!==document.body;e=e.parentElement??void 0){const{position:t}=getComputedStyle(e);if("fixed"===t||"sticky"===t)return e}}function u(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function h(t){if(!u(t)||!u(t.fields))return!1;const e=t.fields["shopify-handle"];return"string"==typeof e&&""!==e}function p(t){return"string"==typeof t.kind&&""!==t.kind?t.kind:"product"}const f=/^\s*\{\s*"error"\s*:/u;function m(t){return"string"==typeof t&&""!==t.trim()&&!f.test(t)}function g(...t){for(const e of t)if(m(e))return e.trim();return""}function y(t){return"string"==typeof t?t.trim():""}function b(t){return null!==t.closest("[data-callimacus-ui], .cal-dock, .cal-stage, .cal-toast")}function v(t){const e=new Set,n=[];for(const o of t){if(!h(o))continue;const t=p(o),r=`${t}:${o.fields["shopify-handle"]}`,i=(o.fields.title??"").trim().toLowerCase(),s=`${t}|${i}`;e.has(r)||""!==i&&e.has(s)||(e.add(r),""!==i&&e.add(s),n.push(o))}return n}function w(t,e){const n=t.trim();if(n.length<=e)return n;const o=n.slice(0,e-1),r=o.lastIndexOf(" ");return`${(r>e/2?o.slice(0,r):o).trimEnd()}…`}function k(t){return u(t)&&u(t.meta)&&Array.isArray(t.sections)}function S(t){const e=(t.sections??[]).filter(t=>u(t)&&"text"===t.type&&m(t.content)).flatMap(t=>String(t.content).split(/\n{2,}/u)).map(t=>t.trim()).filter(t=>m(t)),n=[];let o=600;for(const t of e){if(t.length>o){0===n.length&&n.push(w(t,o));break}n.push(t),o-=t.length}return n}function A(t){const e=t?.data;return u(e)?Object.values(e):[]}function x(t){return A(t).some(t=>function(t){return null!=t&&("string"==typeof t?m(t):Array.isArray(t)?t.length>0:"object"!=typeof t||Object.keys(t).length>0)}(t))}function _(t){if(Array.isArray(t))return t.map(t=>_(t));if(k(t)){const e=t.meta??{};return{id:t.id,name:t.name,meta:{url:e.url,title:e.title,shopifyKind:e.shopifyKind},sections:S(t).map(t=>({type:"text",content:t}))}}if(h(t)&&"product"!==p(t)){const{fields:e}=t;return{id:t.id,kind:t.kind,fields:{title:e.title,"shopify-handle":e["shopify-handle"],"shopify-blogHandle":e["shopify-blogHandle"],"shopify-publishedAt":e["shopify-publishedAt"],"shopify-author":e["shopify-author"],"shopify-productsCount":e["shopify-productsCount"],descriptionText:m(e.descriptionText)?w(e.descriptionText,240):void 0,images:(e.images??[]).slice(0,2).map(t=>({url:t?.url,alt:t?.alt}))}}}if(h(t)){const{fields:e}=t;return{id:t.id,kind:t.kind,fields:{title:e.title,"shopify-handle":e["shopify-handle"],"shopify-vendor":e["shopify-vendor"],"shopify-productType":e["shopify-productType"],price:e.price,availableSizes:e.availableSizes,images:(e.images??[]).slice(0,2).map(t=>({url:t?.url,alt:t?.alt})),variantTree:{variants:(e.variantTree?.variants??[]).map(t=>({id:t?.id,axes:t?.axes,price:t?.price,orderable:t?.orderable}))}}}}return u(t)?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,_(e)])):t}const C=["aria-labelledby","aria-describedby","aria-controls","for","form"];function E(t){const e=t.fields.variantTree?.variants;return Array.isArray(e)?e:[]}function R(t){const e=E(t);return e.length>0&&e.every(t=>!0!==t?.orderable)}function T(t){const e=globalThis.Shopify,n=g(t.settings.rootUrl,e?.routes?.root,"/");return n.endsWith("/")?n:`${n}/`}async function q(t){return new Promise(e=>{setTimeout(e,t)})}function O(t,e,n){const{hit:o}=t,r=s("span");if(E(o).length>1||Array.isArray(o.fields.availableSizes)&&o.fields.availableSizes.length>1){const t=s("a",n.className);return t.href=e.url(o),r.textContent=n.labels.choose,t.append(r),t}const i=s("button",n.className);i.type="button",i.setAttribute("aria-live","polite"),i.append(r),n.busy&&i.append(n.busy);const a=e.variantId(o);if(""===a)return r.textContent=n.labels.soldOut,i.disabled=!0,i;r.textContent=n.labels.add;return i.addEventListener("click",()=>{(async()=>{if("true"!==i.getAttribute("aria-disabled")){i.setAttribute("aria-disabled","true"),i.classList.add("loading"),n.busy?.classList.remove("hidden");try{await e.addToCart(a),e.remember?.("added",t.handle),r.textContent=n.labels.added,await q(2e3),r.textContent=n.labels.add}catch(t){r.textContent=t instanceof Error&&""!==t.message?t.message:n.labels.failed}finally{i.classList.remove("loading"),n.busy?.classList.add("hidden"),i.removeAttribute("aria-disabled")}}})()}),i}function $(t){if("string"==typeof t){const e=t.trim();return""===e?void 0:{handle:e,hit:void 0,title:""}}return h(t)?"product"===p(t)?{handle:t.fields["shopify-handle"],hit:t,title:y(t.fields.title)}:void 0:u(t)&&""!==y(t.handle)?{handle:y(t.handle),hit:void 0,title:y(t.title)}:void 0}function N(t,e){const n=new Map,o=new Map,r=new Map,i=new Map,a=[];let c,d=0;function l(){for(;d<6&&a.length>0;)d+=1,a.shift()?.()}async function u(r,i){const{handle:s}=r,c=n.get(s);if(c)return c;const u="string"==typeof t?`${T(i)}products/${encodeURIComponent(s)}?section_id=${t}`:t(r,T(i)),h=async function(t){return new Promise((e,n)=>{a.push(()=>{t().then(e).catch(n).finally(()=>{d-=1,l()})}),l()})}(async()=>fetch(u,{headers:{Accept:"text/html"}})).then(async t=>t.ok?t.text():void 0).then(t=>void 0===t?void 0:e.extract(t,r)).catch(()=>{}).then(t=>(o.set(s,t),t));return n.set(s,h),h}function h(t,n,o){const i=t.content.firstElementChild;if(!i)throw new Error("empty card template");const s=document.importNode(i,!0);if(void 0!==o.sizes)for(const t of s.querySelectorAll("img[srcset]"))t.sizes=o.sizes;const a=(r.get(n)??0)+1;return r.set(n,a),e.prepare?.(s),a>1&&function(t,e){const n=new Map;for(const o of t.querySelectorAll("[id]"))n.set(o.id,o.id+e),o.id+=e;for(const e of t.querySelectorAll(C.map(t=>`[${t}]`).join(",")))for(const t of C){const o=e.getAttribute(t);null!==o&&""!==o&&e.setAttribute(t,o.split(/\s+/u).map(t=>n.get(t)??t).join(" "))}}(s,`-${a}`),s}function p(t,n,o){t.classList.remove("cal-card--pending"),t.classList.add("cal-card--offline"),o.hit||e.offline(n,o)}return{card:function(t,n,r={}){const a=$(t);if(!a)return;c=n,a.hit&&function(t,e){for(const n of E(t)){const t=String(n?.id??"").split("/").pop()??"";""!==t&&i.set(t,e)}}(a.hit,a.handle);const d=s("div","cal-card");d.dataset.handle=a.handle;const l=o.get(a.handle);if(l)return d.append(h(l,a.handle,r)),d;const f=a.hit?e.placeholder({...a,hit:a.hit},n,r):e.skeleton(a,n,r);return d.append(f),o.has(a.handle)?(p(d,f,a),d):(d.classList.add("cal-card--pending"),u(a,n).then(async t=>{t?await async function({host:t,draft:e},n,o,r){const i=h(n,o,r),s=e.querySelector("img"),a=i.querySelector("img");a&&s?.complete&&s.naturalWidth>0&&(a.loading="eager",await Promise.race([a.decode().catch(()=>{}),q(800)])),e.replaceWith(i),t.classList.remove("cal-card--pending")}({host:d,draft:f},t,a.handle,r):p(d,f,a)}),d)},rememberAdded:function(t){const e="string"==typeof t||"number"==typeof t?String(t).split("/").pop()??"":"",n=i.get(e);void 0!==n&&c?.remember?.("added",n)}}}const L=globalThis;function I(){return"undefined"==typeof PUB_SUB_EVENTS?void 0:PUB_SUB_EVENTS}const B={Accept:"application/javascript","X-Requested-With":"XMLHttpRequest"};async function M(t,e){let n;try{n=await fetch(`${t.cartAddUrl}.js`,{method:"POST",...e})}catch(t){throw new Error("Could not reach the cart. Check your connection and try again.",{cause:t})}const o=await n.json().catch(()=>({})),r=u(o)?o:{};return{json:r,isRefused:!n.ok||Boolean(r.status)}}function j(t){return new Error(g(t.description,t.message,"Could not add to cart."))}const U="cart:update";function F(t,e){document.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:e}))}async function D(t,e,n){const o=new FormData;o.append("id",t),o.append("quantity",String(e));const r=[...document.querySelectorAll("cart-items-component[data-section-id]")].map(t=>t.dataset.sectionId??"").filter(t=>""!==t);r.length>0&&o.append("sections",r.join(","));const{json:i,isRefused:s}=await M(n,{headers:B,body:o});if(s)throw F("cart:error",{sourceId:"callimacus",data:{message:i.message,errors:i.errors,description:i.description}}),j(i);const a=await async function(t){try{const e=await fetch(`${T({settings:t})}cart.js`,{headers:{accept:"application/json"}}),n=await e.json();return u(n)?n:void 0}catch{return}}(n),c="number"==typeof a?.item_count?a.item_count:void 0;return F(U,{resource:a,sourceId:"callimacus",data:{source:void 0===c?"product-form-component":"callimacus",itemCount:c??e,variantId:t,sections:u(i.sections)?i.sections:void 0}}),i}const P=/^[*\-•]\s+(?<text>\S.*)$/u,W=/^\d+[).]\s+(?<text>\S.*)$/u,z=/^#{1,6}\s+(?<text>\S.*)$/u,V=/^\s*(?:[*\-•]|\d+[).]|#{1,6})\s*$/u;const H=new WeakMap;function K(t,e){H.get(t)!==e&&(H.set(t,e),t.replaceChildren(),function(t,e){for(const[n,o]of e.split("**").entries())""!==o&&t.append(n%2==1?s("strong","",o):document.createTextNode(o))}(t,e))}function J(t,e){for(const[n,o]of e.entries()){let e=t.children.item(n);null===e&&(e=s("li"),t.append(e)),K(e,o)}for(;t.children.length>e.length;)t.lastElementChild?.remove()}const Y=new WeakMap;function G(t,e,n){const o=Y.get(t)??s("span","cal-caret");Y.set(t,o),o.setAttribute("aria-hidden","true"),o.remove();const r=function(t,e){const n=t.replaceAll(/\r\n?/gu,"\n").split("\n");!e&&V.test(n.at(-1)??"")&&n.pop();const o=[];let r,i;for(const t of n){const e=t.trim();if(""===e){r=void 0,i=void 0;continue}const n=z.exec(e);if(n){o.push({tag:"h3",text:n.groups?.text??""}),r=void 0,i=void 0;continue}const s=P.exec(e),a=s??W.exec(e);if(a){const t=s?"ul":"ol";i?.tag!==t&&(i={tag:t,items:[]},o.push(i)),i.items.push(a.groups?.text??""),r=void 0;continue}i&&/^\s/u.test(t)?i.items[i.items.length-1]+=` ${e}`:(i=void 0,r?r.text+=` ${e}`:(r={tag:"p",text:e},o.push(r)))}return o}(e,n);for(const[e,n]of r.entries()){let o=t.children.item(e);if(o?.tagName.toLowerCase()!==n.tag){const e=s(n.tag);null===o?t.append(e):o.replaceWith(e),o=e}"items"in n?J(o,n.items):K(o,n.text)}for(;t.children.length>r.length;)t.lastElementChild?.remove();const i=t.lastElementChild;!n&&i&&(i.matches("ul, ol")?i.lastElementChild??i:i).append(o)}function X(t,e,n=!0,o=""){const r=s("div",`${e} cal-prose ${o}`.trim());return G(r,t,n),r}function Z(t){return Array.isArray(t)?t:[]}function Q(t){return u(t)?t:{}}let tt=0;function et(t){return tt+=1,`cal-${t}-${tt}`}function nt(){return c("0 0 14 10","M8.537.808a.5.5 0 01.817-.162l4 4a.5.5 0 010 .708l-4 4a.5.5 0 11-.708-.708L11.793 5.5H1a.5.5 0 010-1h10.793L8.646 1.354a.5.5 0 01-.109-.546z","cal-icon cal-icon--arrow")}function ot(){return c("0 0 10 6","M9.354.646a.5.5 0 00-.708 0L5 4.293 1.354.646a.5.5 0 00-.708.708l4 4a.5.5 0 00.708 0l4-4a.5.5 0 000-.708z","cal-icon cal-icon--caret")}function rt(t,e,n){return`${t} ${1===t?e:n}`}const it=["text","message","reply","answer","intro","body"],st=["What would you recommend?","Show me what is new","What are your best sellers?","Help me find a gift"];function at(t){return Z(t.fields.images).length>1?1:0}function ct(t,e,{index:n=0,widths:o,sizes:r,eager:i=!1,className:a=""}){const c=o[Math.floor(o.length/2)]??800,d=t.imageUrl(e,{index:n,width:c});if(""===d)return;const l=s("img",a);return l.srcset=o.map(o=>`${t.imageUrl(e,{index:n,width:o})} ${o}w`).join(", "),l.sizes=r,l.src=d,l.alt=g(e.fields.images?.[n]?.alt,e.fields.title),l.decoding="async",l.loading=i?"eager":"lazy",i&&(l.fetchPriority="high"),function(t){t.classList.add("cal-reveal");const e=()=>{t.classList.add("is-ready")};t.complete&&t.naturalWidth>0?e():(t.addEventListener("load",e,{once:!0}),t.addEventListener("error",e,{once:!0}))}(l),l}const dt=[360,535,750,1070];function lt(t,e){const n="string"==typeof t?new Date(t):void 0;return!n||Number.isNaN(n.getTime())?"":function(t){let e=ut.get(t);if(!e){try{e=new Intl.DateTimeFormat(t,{dateStyle:"medium"})}catch{e=new Intl.DateTimeFormat("en",{dateStyle:"medium"})}ut.set(t,e)}return e}(e).format(n)}const ut=new Map;function ht(t,e,n){const o=p(t),r=ct(e,t,{widths:dt,sizes:n}),i=s("article",`cal-entry cal-entry--${"collection"===o||"article"===o?o:"other"}${r?"":" cal-entry--text"}`);if(r){const t=s("div","cal-entry__media cal-media");t.append(r),i.append(t)}const a=s("div","cal-entry__body"),c=function(t,e){const{fields:n}=t;switch(p(t)){case"collection":{const t=n["shopify-productsCount"];return"number"==typeof t&&t>0?rt(t,"product","products"):""}case"article":return[lt(n["shopify-publishedAt"],e.settings.language),g(n["shopify-author"])].filter(t=>""!==t).join(" · ");default:return""}}(t,e);""!==c&&a.append(s("p","cal-entry__meta",c));const d=g(t.fields.title,t.fields["shopify-handle"].replaceAll("-"," ")),l=s("h3","cal-entry__title"),u=e.url(t);if(""===u)l.textContent=d;else{const t=s("a","cal-entry__link",d);t.href=u,l.append(t)}a.append(l);const h=g(t.fields.descriptionText);return""===h||"collection"===o&&r||a.append(s("p","cal-entry__text",h)),i.append(a),i}function pt(t,e,n){const o=s("ul",`cal-entries cal-entries--${n}`);o.setAttribute("role","list");const r=4===n?"(min-width: 990px) 25vw, (min-width: 750px) 33vw, 50vw":"(min-width: 750px) 33vw, 100vw";for(const n of t){const t=s("li","cal-entries__item");t.append(ht(n,e,r)),o.append(t)}return o}const ft=new WeakMap;function mt(t,e){const n=JSON.stringify(Q(t.data),(t,e)=>{const n=u(e)&&u(e.fields)?e.fields["shopify-handle"]:void 0;return"string"==typeof n?n:e});return`${e.chapter.isFirst?1:0}|${e.chapter.question}|${n}`}function gt(t,e){return{type:t,render(t,n){const o=e(Q(t.data),n,t);return o&&ft.set(o,mt(t,n)),o},update:(t,e,n)=>ft.get(t)===mt(e,n)}}function yt(t){const{classes:e}=t;function n(t,e="section"){return s(e,`cal-section cal-${t}`)}function o(...t){const n=s("div",`${e.pageWidth} cal-section__inner`);return n.append(...t.filter(t=>void 0!==t)),n}function r(t){return s("p","cal-eyebrow",t)}function i(t,e,n){const o=s("div","cal-head"),r=s("h2","cal-title",e);return r.id=et("title"),t.setAttribute("aria-labelledby",r.id),o.append(r),void 0!==n&&o.append(s("p","cal-head__meta",n)),o}function a(t,n,o=""){const r=s("button",`${e.buttonSecondary} cal-chip ${o}`.trim());return r.type="button",r.dataset.callimacusAsk=n,n!==t&&(r.title=n),r.append(s("span","cal-chip__label",t),nt()),r}function c(t){const e=s("ul","cal-chips");e.setAttribute("role","list");for(const n of t){const t=s("li");t.append(a(n.label,n.question)),e.append(t)}return e}function d(t,e,n){const o=s("a",n);o.href=e.url(t);const r=g(t.fields.title);return o.append(s("span","",""===r?"Shop now":`Shop ${r}`),nt()),o}function l(t,e){const n=g(e).replace(/^Show me .+? — /u,"");if(""===n)return`Show me ${t}`;return`Show me ${t} — ${/^(?:I\b|I'|[A-Z]{2})/u.test(n)?n:n.charAt(0).toLowerCase()+n.slice(1)}`}function u(r,i,s,a=!0){if(""===r&&0===i.length)return;const c=n("note"),d=o();""!==r&&d.append(X(r,e.rte,a,"cal-prose--note"));const l=i.filter(t=>"product"!==p(t)),u=[t.cards(i.filter(t=>"product"===p(t)),s),l.length>0?pt(l,s,3):void 0];return d.append(...u.filter(t=>void 0!==t)),c.append(d),c}function h(t,e,n,o){return it.map(e=>g(t[e])).find(t=>""!==t)??(e.length>0?"":n.text(o))}function f(t,e){const n=g(Q(t.data).text,e.text(t));return 0===e.chapter.blocks.filter(e=>e.id!==t.id).length||/solomei\.ai/iu.test(n)?{kind:"redirect",text:n}:{kind:""!==n&&e.final?"note":"wait",text:n}}function m(t){const e=n("redirect"),r=s("p","cal-redirect__text",`I can help with questions about what ${t.settings.storeName} sells.`),i=(t.settings.starters.length>0?t.settings.starters.slice(0,4):st).map(t=>({label:t,question:t}));return e.append(o(r,c(i))),e}const y=[(b="custom:storefrontReply",v=(t,e,n)=>g(t.text,e.text(n)),w=(t,r)=>{const i=n("answer"),a=s("div","cal-answer__body");return a.append(X(t,e.rte,r.final,"cal-prose--answer")),i.append(o(a)),i},{type:b,render(t,e){const n=v(Q(t.data),e,t);return""===n?void 0:w(n,e)},update(t,e,n){const o=t instanceof Element?t.querySelector(".cal-prose"):void 0,r=v(Q(e.data),n,e);return!(!o||""===r||(G(o,r,n.final),0))}}),gt("custom:editorialHero",(t,i)=>{const a=Q(t.copy),c={eyebrow:g(a.eyebrow),headline:g(a.headline),dek:g(a.dek)},l=i.hits(t.lead).at(0),{isFirst:u}=i.chapter,h=l?ct(i,l,{index:at(l),widths:u?[750,1100,1500,1800,2400]:[200,320,480],sizes:u?"100vw":"(min-width: 750px) 160px, 96px",eager:u}):void 0;if(h||""!==c.eyebrow||""!==c.headline||""!==c.dek)return u?function(t,o,i,a){const c=n("hero");c.classList.add("cal-hero--lead");const l=s("div","cal-hero__banner "+(i?"cal-hero__banner--image":"cal-hero__banner--text"));if(i){const t=s("div","cal-hero__media cal-media");t.append(i),l.append(t)}if(""!==t.eyebrow||""!==t.headline||""!==t.dek){const n=s("div",`cal-hero__content ${e.pageWidth}`),i=s("div","cal-hero__box");if(""!==t.eyebrow&&i.append(r(t.eyebrow)),""!==t.headline&&i.append(s("h2","cal-display cal-hero__headline",t.headline)),""!==t.dek&&i.append(s("p","cal-hero__dek",t.dek)),o){const t=s("div","cal-hero__buttons");t.append(d(o,a,`${e.buttonPrimary} cal-hero__cta`)),i.append(t)}n.append(i),l.append(n)}return c.append(l),c}(c,l,h,i):function(t,i,a,c){const l=n("hero");l.classList.add("cal-hero--compact");const u=s("div","cal-hero__row");if(a&&i){const t=s("a","cal-hero__thumb cal-media");t.href=c.url(i),t.tabIndex=-1,t.setAttribute("aria-hidden","true"),t.append(a),u.append(t)}const h=s("div","cal-hero__text");return""!==t.eyebrow&&h.append(r(t.eyebrow)),""!==t.headline&&h.append(s("h2","cal-title cal-hero__headline",t.headline)),""!==t.dek&&h.append(s("p","cal-hero__dek",t.dek)),i&&h.append(d(i,c,`${e.link} cal-link`)),u.append(h),l.append(o(u)),l}(c,l,h,i)}),gt("custom:storefrontPicks",(e,r,s)=>{const a=r.hits(e.picks);return function(e,r,s){if(0===r.length)return;const a=n("picks"),c=i(a,e,rt(r.length,"product","products"));return a.append(o(c,t.cards(r,s))),a}("Picked for you",a.length>0?a:r.picks(s),r)}),gt("custom:pageAnswer",(t,i)=>{const a=Z(t.pages).filter(t=>k(t)).map(t=>({title:g(t.meta?.title,t.name),kind:t.meta?.shopifyKind,text:S(t),url:i.url(t)})).filter(t=>""!==t.title&&t.text.length>0&&""!==t.url).slice(0,2);if(0===a.length)return;const c=n("pages"),d=s("div","cal-pages__list");return d.append(...a.map(t=>function(t,n){const o=s("article","cal-page"),i=s("h2","cal-subtitle cal-page__title",t.title);i.id=et("title"),o.setAttribute("aria-labelledby",i.id);const a=s("a",`${e.link} cal-link cal-page__link`);return a.href=t.url,a.append(s("span","","Read the full "+("policy"===t.kind?"policy":"page")),s("span",e.visuallyHidden,`: ${t.title}`),nt()),o.append(r("policy"===t.kind?"Store policy":`From ${n.settings.storeName}`),i,X(t.text.join("\n\n"),e.rte,!0,"cal-page__text"),a),o}(t,i))),c.append(o(d)),c}),gt("custom:collectionGrid",(t,e)=>{const r=e.hits(t.collections).filter(t=>"collection"===p(t)&&0!==t.fields["shopify-productsCount"]);if(0===r.length)return;const s=n("collections"),a=i(s,"Shop by collection",rt(r.length,"collection","collections"));return s.append(o(a,pt(r,e,4))),s}),gt("custom:storyCards",(t,e)=>{const r=e.hits(t.stories).filter(t=>"article"===p(t));if(0===r.length)return;const s=n("stories"),a=i(s,"From the journal",rt(r.length,"story","stories"));return s.append(o(a,pt(r,e,3))),s}),gt("custom:problemGuide",(t,r)=>{const c=Q(t.guide),d=Z(c.steps).map(t=>Q(t)).map(t=>({title:g(t.title),body:g(t.body),shopFor:g(t.shopFor)})).filter(t=>""!==t.title||""!==t.body);if(0===d.length)return;const u=n("guide"),h=s("ol",`cal-steps cal-steps--${Math.min(d.length,4)}`);h.setAttribute("role","list");for(const[t,n]of d.entries()){const o=s("li","cal-step"),i=s("div","cal-step__card"),c=s("span","cal-step__index",String(t+1).padStart(2,"0"));c.setAttribute("aria-hidden","true");const d=s("div","cal-step__info");""!==n.title&&d.append(s("h3","cal-step__title",n.title)),""!==n.body&&d.append(X(n.body,e.rte,!0,"cal-step__body")),""!==n.shopFor&&d.append(a(`Shop ${n.shopFor}`,l(n.shopFor,r.chapter.question),"cal-chip--compact cal-step__shop")),i.append(c,d),o.append(i),h.append(o)}const p=i(u,g(c.title,"Step by step"),rt(d.length,"step","steps"));return u.append(o(p,h)),u}),gt("custom:materialStory",(i,a)=>{const c=Q(i.story),d=g(c.material),l=g(c.headline),u=g(c.body),h=Z(c.facts).map(t=>g(t)).filter(t=>""!==t),p=a.hits(i.products).slice(0,3);if(""===l&&""===u&&0===h.length&&0===p.length)return;const f=n("material"),m=p.at(0),y=m?ct(a,m,{index:at(m),widths:[535,750,1070,1500],sizes:"(min-width: 1600px) 750px, (min-width: 750px) calc((100vw - 130px) / 2), calc(100vw - 30px)"}):void 0;if(""!==l||""!==u||""!==d||h.length>0){const t=s("div","cal-material__feature"+(y?"":" cal-material__feature--text"));if(y){const e=s("div","cal-material__media cal-media");e.append(y),t.append(e)}const n=s("div","cal-material__content");if(""!==d&&n.append(r(d)),""!==l){const t=s("h2","cal-title cal-material__heading",l);t.id=et("title"),f.setAttribute("aria-labelledby",t.id),n.append(t)}if(""!==u&&n.append(X(u,e.rte,!0,"cal-material__body")),h.length>0){const t=s("ul","cal-facts");t.setAttribute("role","list");for(const e of h)t.append(s("li","cal-facts__item",e));n.append(t)}t.append(n),f.append(o(t))}if(p.length>0){const e=s("div","cal-material__products");e.append(s("h3","cal-subtitle",""===d?"Shop the story":`Made with ${d}`));const n=t.cards(p,a,{columns:3});n&&e.append(n),f.append(o(e))}return f}),gt("custom:sizeCare",t=>{const i=Z(t.faq).map(t=>Q(t)).map(t=>({question:g(t.question),answer:g(t.answer)})).filter(t=>""!==t.question&&""!==t.answer);if(0===i.length)return;const a=n("faq"),c=s("div","cal-faq__layout"),d=s("div","cal-faq__header"),l=s("h2","cal-title","Good to know");l.id=et("title"),a.setAttribute("aria-labelledby",l.id),d.append(r("Sizes and care"),l);const u=s("div","cal-faq__list");for(const[t,n]of i.entries()){const o=et("faq"),r=s("div","cal-faq__item"),i=s("details");i.open=0===t;const a=s("summary","cal-faq__summary");a.id=`${o}-summary`,a.append(s("h3","cal-faq__question",n.question),ot());const c=s("div","cal-faq__answer");c.id=`${o}-content`,c.setAttribute("role","region"),c.setAttribute("aria-labelledby",a.id),c.append(X(n.answer,e.rte)),i.append(a,c),r.append(i),u.append(r)}return c.append(d,u),a.append(o(c)),a}),gt("custom:compareSet",(i,a)=>{const c=Q(i.pair),d=Q(i.verdict),l=a.hits(i.first).at(0),u=a.hits(i.second).at(0),h=Z(d.rows).map(t=>Q(t)).map(t=>({aspect:g(t.aspect),first:g(t.first),second:g(t.second)})).filter(t=>""!==t.aspect),p=g(d.summary);if(!l&&!u&&""===p&&0===h.length)return;const f=g(l?.fields.title,c.first,"The first"),m=g(u?.fields.title,c.second,"The second"),y=n("compare");l||u||y.classList.add("cal-compare--text");const b=s("div","cal-compare__layout"),v=s("div","cal-compare__intro"),w=s("h2","cal-title",`${f} or ${m}?`);w.id=et("title"),y.setAttribute("aria-labelledby",w.id),v.append(r("Side by side"),w),""!==p&&v.append(X(p,e.rte,!0,"cal-compare__summary")),b.append(v);for(const[e,n]of[l,u].entries()){const o=s("div","cal-compare__card cal-compare__card--"+(0===e?"first":"second")),r=n?t.card(n,a):void 0;r&&o.append(r),b.append(o)}return h.length>0&&b.append(function(t,n,o){const r=s("div","cal-compare__table");r.setAttribute("role","table"),r.setAttribute("aria-label",`${t} compared with ${n}`);const i=s("div","cal-compare__row cal-compare__row--head");i.setAttribute("role","row");const a=s("span","cal-compare__aspect");a.setAttribute("role","columnheader"),a.append(s("span",e.visuallyHidden,"Aspect")),i.append(a);for(const e of[t,n]){const t=s("span","cal-compare__value",e);t.setAttribute("role","columnheader"),i.append(t)}r.append(i);for(const t of o){const e=s("div","cal-compare__row");e.setAttribute("role","row");const n=s("span","cal-compare__aspect",t.aspect);n.setAttribute("role","rowheader"),e.append(n);for(const n of[t.first,t.second]){const t=s("span","cal-compare__value",n);t.setAttribute("role","cell"),e.append(t)}r.append(e)}return r}(f,m,h)),y.append(o(b)),y}),gt("custom:completeSet",(e,r)=>{const a=Z(e.companions).map(t=>Q(t)).map(t=>({why:g(t.why),hit:r.hits(t.product).at(0)})).filter(t=>void 0!==t.hit).slice(0,3);if(0===a.length)return;const c=n("set"),d=s("div",`cal-set__collage cal-set__collage--${a.length}`);for(const[e,n]of a.entries()){const o=s("div","cal-set__item cal-set__item--"+(0===e?"lead":"side")),i=s("figure","cal-set__piece"),a=t.card(n.hit,r,0===e?{sizes:"(min-width: 1600px) 780px, (min-width: 750px) calc((100vw - 130px) / 2), calc(100vw - 30px)"}:{});a&&i.append(a),""!==n.why&&i.append(s("figcaption","cal-set__why",n.why)),o.append(i),d.append(o)}return c.append(o(i(c,"Complete the set"),d)),c}),gt("custom:followUps",t=>{const e=Z(t.next).map(t=>Q(t)).map(t=>({label:g(t.label,t.question),question:g(t.question,t.label)})).filter(t=>""!==t.question);if(0===e.length)return;const r=n("next","nav"),i=s("h2","cal-eyebrow cal-next__title","Keep exploring");return i.id=et("title"),r.setAttribute("aria-labelledby",i.id),r.append(o(i,c(e))),r}),{type:"*",render(t,e){const n=e.picks(t);return u(h(Q(t.data),n,e,t),n,e,e.final)},update(t,e,n){const o=t instanceof Element?t.querySelector(".cal-prose"):void 0,r=n.picks(e),i=h(Q(e.data),r,n,e);return!(!o||""===i||r.length>0)&&(G(o,i,n.final),!0)}}];var b,v,w;for(const t of["demosthenesResponse","custom:demosthenesResponse"])y.push({type:t,render(t,e){const n=f(t,e);return"redirect"===n.kind?m(e):"wait"===n.kind?void 0:u(n.text,[],e)},update(t,e,n){const o=f(e,n);if("redirect"===o.kind)return t instanceof Element&&t.classList.contains("cal-redirect");const r=t instanceof Element?t.querySelector(".cal-prose"):void 0;return!(!r||"note"!==o.kind)&&(G(r,o.text,!0),!0)}});return y}const bt="callimacus.cards",vt=["_pos","_sid","_ss","_psq","_fid"],wt=new Set(["TABLE","THEAD","TBODY","TFOOT","TR","TD","TH"]);function kt(t){if(null!==t)try{const e=/\/products\/(?<handle>[^#/?]+)/u.exec(new URL(t,globalThis.location.origin).pathname);return void 0===e?.groups?.handle?void 0:decodeURIComponent(e.groups.handle)}catch{return}}function St(t,e){return[...t.querySelectorAll('a[href*="/products/"]')].some(t=>{const n=kt(t.getAttribute("href"));return void 0!==n&&n!==e})}function At(){const t=o("sessionStorage",bt),n={searches:0,sectionId:void 0,borrowed:0,missed:[],styles:0,scripts:[],verdict:"fits"===t||"fails"===t?t:"unknown",why:void 0===t?"":"decided on an earlier page of this tab"},i=new Set;return{stats:n,source:function(t,e){const o=""===t.title?t.handle.replaceAll("-"," "):t.title,r=new URLSearchParams({type:"product",q:o,"options[prefix]":"last"});return void 0!==n.sectionId&&r.set("section_id",n.sectionId),n.searches+=1,`${e}search?${r.toString()}`},extract:function(t,o){const r=document.createElement("template");r.innerHTML=t;const s=function(t,e){const n=[...(t.querySelector("main")??t).querySelectorAll('a[href*="/products/"]')].filter(t=>kt(t.getAttribute("href"))===e&&!t.closest('cart-drawer, cart-drawer-component, cart-notification, cart-items, [id^="CartDrawer"], [id^="cart-notification"], [class*="cart-drawer"], .cart-item'));for(const t of n){let n=t;for(;n.parentElement&&!n.parentElement.matches('main, body, .shopify-section, ul, ol, [role="list"], form, section, slider-component, .grid, [class*="product-grid"]')&&!St(n.parentElement,e)&&!n.parentElement.querySelector("h1");)n=n.parentElement;if("LI"===n.tagName&&1===n.childElementCount&&n.firstElementChild&&(n=n.firstElementChild),!wt.has(n.tagName)&&!n.closest("table")&&n.querySelector("img, picture, svg")&&(n!==t||""!==n.textContent.trim()))return n}}(r.content,o.handle);if(!s)return void n.missed.push({handle:o.handle,why:"not in the search results"});const a=s.closest('[id^="shopify-section-"]');a&&void 0===n.sectionId&&(n.sectionId=a.id.slice(16),e.info(`borrowing cards from the search section ${n.sectionId}`)),a&&function(t){for(const e of t.querySelectorAll("style")){const t=e.textContent;if(i.has(t))continue;i.add(t);const o=document.createElement("style");o.dataset.callimacusBorrowed="",o.textContent=t,document.head.append(o),n.styles+=1}const e=new Set([...document.querySelectorAll('link[rel="stylesheet"], script[src]')].map(t=>(t.getAttribute("href")??t.getAttribute("src")??"").split("?",1)[0]));for(const o of t.querySelectorAll('link[rel="stylesheet"]')){const t=o.getAttribute("href")??"",r=t.split("?",1)[0]??t;""===t||e.has(r)||i.has(r)||(i.add(r),document.head.append(o.cloneNode(!0)),n.styles+=1)}for(const o of t.querySelectorAll("script[src]")){const t=o.getAttribute("src")??"",r=t.split("?",1)[0]??t;if(""===t||e.has(r)||i.has(r))continue;i.add(r);const s=document.createElement("script");s.src=t,s.defer=!0,document.head.append(s),n.scripts.push(r.split("/").pop()??r)}}(a);const c=document.createElement("template");return c.content.append(s),n.borrowed+=1,c},prepare:function(t){!function(t){for(const e of t.querySelectorAll("a[href]")){const t=e.getAttribute("href")??"";try{const n=new URL(t,globalThis.location.origin);if(vt.some(t=>n.searchParams.has(t))){for(const t of vt)n.searchParams.delete(t);const o=n.origin===globalThis.location.origin&&!/^https?:/iu.test(t);e.setAttribute("href",o?`${n.pathname}${n.search}${n.hash}`:n.href)}}catch{}}}(t);for(const e of t.querySelectorAll('dialog, [role="dialog"], quick-add-modal, [class*="modal"][id]')){const t=""===e.id?void 0:document.querySelector(`#${CSS.escape(e.id)}`);t&&t!==e?e.remove():t||document.body.append(e)}},check:function(t){if("unknown"!==n.verdict)return n.verdict;const o=function(t){const e=t.getBoundingClientRect();if(e.width<40||e.height<40)return;const n=t.querySelector("img, picture, svg"),o=n?.getBoundingClientRect();if(!n||!o||0===o.height)return;const r=[...t.querySelectorAll('a[href*="/products/"], h2, h3, h4, p, [class*="title"], [class*="price"]')].filter(t=>!t.contains(n)&&!n.contains(t)&&""!==t.textContent.trim()).map(t=>t.getBoundingClientRect()).find(t=>t.height>=8&&t.width>=8&&!(t.top<=o.top&&t.bottom>=o.bottom));return r?e.height<e.width?{fits:!1,why:`the card is wider than it is tall (${Math.round(e.width)} by ${Math.round(e.height)} px): a list row`}:o.bottom>r.top+4?{fits:!1,why:"the card's text sits beside its picture, not under it"}:{fits:!0,why:"a picture above its text, taller than wide"}:{fits:!1,why:"the card has no text beside its picture"}}(t);return o&&(n.verdict=o.fits?"fits":"fails",n.why=o.why,r("sessionStorage",bt,n.verdict),e.info(`the theme's cards ${o.fits?"fit":"do not fit"}: ${o.why}`)),n.verdict}}}const xt=[240,360,480,640,840,1080],_t={add:"Add to cart",added:"Added",choose:"Choose options",soldOut:"Sold out",failed:"Could not add. Try again"},Ct=Object.freeze({pageWidth:"cal-page-width",buttonPrimary:"cal-button",buttonSecondary:"cal-button cal-button--secondary",link:"cal-link",rte:"cal-rte",visuallyHidden:"cal-visually-hidden",grid:t=>`cal-egrid cal-egrid--${t}`,gridItem:"cal-egrid__item"});function Et(){const t=document.querySelector("cart-notification, cart-drawer");return"function"==typeof t?.getSectionsToRender?"dawn":document.querySelector("cart-items-component, cart-drawer-component, cart-icon")?"horizon":"plain"}function Rt(t){return[...t.querySelectorAll('a[href$="/cart"], a[href*="/cart?"], a[href$="/cart/"]')].filter(t=>!b(t))}let Tt;async function qt(t,n,o,r){const{json:i,isRefused:a}=await M(o,{headers:{"content-type":"application/json",accept:"application/json","x-requested-with":"XMLHttpRequest"},body:JSON.stringify({items:[{id:Number(t),quantity:n}]})});if(a)throw j(i);const c=Array.isArray(i.items)&&u(i.items[0])?i.items[0]:{};!function(t,e){document.querySelector(".cal-toast")?.remove(),clearTimeout(Tt);const n=s("div","cal-toast");n.setAttribute("role","status"),n.dataset.callimacusUi="",n.append(s("p","cal-toast__text",""===t?"Added to your cart":`Added to your cart: ${t}`));const o=s("a","cal-button cal-toast__action","View cart");o.href=`${T({settings:e})}cart`,n.append(o),document.body.append(n),Tt=setTimeout(()=>{n.remove()},5e3)}(g(c.product_title,c.title),o),document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i}));const d=await async function(){const t=Rt(document),n=t.at(0);if(void 0===n)return!1;const o=n.closest('[id^="shopify-section-"]')?.id.slice(16)??"";let r="";try{if(""!==o){const t=new URL(globalThis.location.href);t.search=`sections=${encodeURIComponent(o)}`;const e=await fetch(t,{headers:{accept:"application/json"}}),n=await e.json();r=u(n)&&"string"==typeof n[o]?n[o]:""}if(""===r){const t=await fetch(globalThis.location.href,{headers:{accept:"text/html"}});r=await t.text()}}catch(t){return e.warn("could not redraw the cart icon",t),!1}const i=Rt((new DOMParser).parseFromString(r,"text/html"));let s=0;for(const[e,n]of t.entries()){const t=(""===n.id?void 0:i.find(t=>t.id===n.id))??i.at(e);void 0!==t&&t.innerHTML!==n.innerHTML&&(n.innerHTML=t.innerHTML,s+=1)}return s>0}();return r.cart[d?"iconRedrawn":"iconMissed"]+=1,{...c,handle:g(c.handle)}}function Ot(t,e){const n=s("div","cal-ecard"),o=s("div","cal-ecard__media"),r=s("div","cal-ecard__info"),i=s("a","cal-ecard__title",t);return i.href=e,r.append(i),n.append(o,r),{root:n,info:r,title:i,media:o}}function $t(t,e){const n=s("div","cal-ecard__quick-add cal-card__quick-add");return n.append(O(t,e,{className:"cal-button cal-button--secondary cal-ecard__add",labels:_t})),n}function Nt(t,e,n={}){const{hit:o}=t,r=e.url(o),i=Ot(t.title,r),a=ct(e,o,{widths:xt,sizes:n.sizes??"(min-width: 990px) calc((100vw - 160px) / 4), (min-width: 750px) calc((100vw - 120px) / 3), calc((100vw - 40px) / 2)"});if(a){const t=s("a","cal-ecard__image");t.href=r,t.tabIndex=-1,t.setAttribute("aria-hidden","true"),t.append(a),i.media.append(t)}return i.info.append(s("p","cal-ecard__price"+(R(o)?" cal-ecard__price--sold-out":""),function(t,e){const{fields:n}=t,o=u(n.priceRange)?n.priceRange:{},r=Number(o.min),i=Number(o.max);if(Number.isFinite(r)&&Number.isFinite(i)&&r<i){const t=g(o.currency,"object"==typeof n.price?n.price.currency:"");return`From ${e.money(""===t?r:{amount:r,currency:t})}`}return void 0===n.price?"":e.money(n.price)}(o,e))),!1===n.quickAdd||R(o)||i.info.append($t(t,e)),i.root}function Lt(t,e){const n=Ot("",`${T(e)}products/${encodeURIComponent(t.handle)}`);return n.root.classList.add("cal-card__skeleton"),n.title.append(s("span","cal-card__line")),n.title.setAttribute("aria-label",""===t.title?"Loading product":t.title),n.root}function It(t,e){t.classList.remove("cal-card__skeleton");const n=t.querySelector(":scope .cal-ecard__title");n&&(n.removeAttribute("aria-label"),n.textContent=""===e.title?e.handle.replaceAll("-"," "):e.title)}function Bt(){const t=new Map;async function e(e,n){let o=t.get(e);return o||(o=fetch(`${T(n)}products/${encodeURIComponent(e)}.js`,{headers:{accept:"application/json"}}).then(async t=>t.ok?t.json():void 0).then(t=>u(t)?function(t){const e=g(t.handle);if(""===e)return;const n=Array.isArray(t.variants)?t.variants.filter(t=>u(t)):[],o=Array.isArray(t.images)?t.images.filter(t=>"string"==typeof t):[],r=t=>Number(t)/100;return{fields:{"shopify-handle":e,title:g(t.title),price:r(t.price),priceRange:{min:r(t.price_min),max:r(t.price_max)},images:o.map(t=>({url:t.startsWith("//")?`https:${t}`:t})),variantTree:{variants:n.map(t=>({id:t.id,orderable:!0===t.available,online:!0}))}}}}(t):void 0).catch(()=>{}),t.set(e,o)),o}function n({host:t,ref:n,ctx:o,options:r}){if(n.hit){const i=Nt({...n,hit:n.hit},o,r);return t.replaceChildren(i),void(0===(n.hit.fields.images??[]).length&&e(n.handle,o).then(t=>{if(!t||!i.isConnected)return;const e={...t,fields:{...t.fields,...n.hit?.fields,images:t.fields.images}};i.replaceWith(Nt({...n,hit:e},o,r))}))}const i=Lt(n,o);t.replaceChildren(i),t.classList.add("cal-card--pending"),e(n.handle,o).then(e=>{t.classList.remove("cal-card--pending"),e?i.replaceWith(Nt({handle:n.handle,hit:e,title:g(n.title,e.fields.title)},o,r)):It(i,n)})}return{card:function(t,e,o={}){const r=$(t);if(!r)return;const i=s("div","cal-card");return i.dataset.handle=r.handle,n({host:i,ref:r,ctx:e,options:o}),i},draw:n}}function Mt(t){const n=Bt(),o=At(),r={cart:{kind:void 0,adds:0,iconRedrawn:0,iconMissed:0},addedButtons:0,borrow:o.stats},i=new Set,a=N(o.source,{extract:o.extract,prepare:o.prepare,placeholder:Nt,skeleton:Lt,offline:It});let c=!1;const d=t=>!t.classList.contains("cal-card--pending")&&null!==t.firstElementChild&&!t.firstElementChild.classList.contains("cal-ecard");function l(t){const e=t.host.firstElementChild;if(null===e||!d(t.host))return;if("fails"===o.check(e))return void function(){for(const t of i)t.host.isConnected?d(t.host)&&(n.draw(t),i.delete(t)):i.delete(t)}();if(function({host:t,ref:e,ctx:n,options:o}){const i=t.firstElementChild;null!==i?.querySelector('button[name="add"], form[action*="/cart/add"], modal-opener, [data-quick-add], quick-add-component, .quick-add, product-form-component')||null!==t.querySelector(":scope > .cal-ecard__quick-add")||null===i||!1===o.quickAdd||!e.hit||R(e.hit)||(t.append($t({...e,hit:e.hit},n)),r.addedButtons+=1)}(t),"unknown"!==o.stats.verdict)return;const s=()=>{l(t)};if(e.querySelector("img")?.addEventListener("load",s,{once:!0}),"function"!=typeof IntersectionObserver)return;const a=new IntersectionObserver(t=>{t.every(t=>!t.isIntersecting)||(a.disconnect(),s())});a.observe(t.host)}function h(e,r,s={}){if("auto"!==t||"fails"===o.stats.verdict)return n.card(e,r,s);!function(){if(c)return;c=!0;const t=I();t&&"function"==typeof L.subscribe&&L.subscribe(t.cartUpdate,t=>{const e=u(t)?t:{};"product-form"===e.source&&a.rememberAdded(e.productVariantId)}),document.addEventListener(U,t=>{const{detail:e}=t,n=u(e)&&u(e.data)?e.data:{};u(e)&&"product-form-component"===n.source&&!0!==n.didError&&a.rememberAdded(e.sourceId)})}();const h=a.card(e,r,s),p=$(e);if(!h||!p)return h;const f={host:h,ref:p,ctx:r,options:s};if(i.add(f),d(h))queueMicrotask(()=>{l(f)});else{const t=new MutationObserver(()=>{h.classList.contains("cal-card--pending")||(t.disconnect(),l(f))});t.observe(h,{childList:!0,attributes:!0,attributeFilter:["class"]})}return h}return Object.freeze({classes:Ct,card:h,cards:(t,e,n={})=>function(t,e){if(0===t.length)return;const n=[2,3,4,5].includes(e.columns??4)?e.columns??4:4,o=s("ul",`${Ct.grid(n)} cal-grid`);o.setAttribute("role","list");for(const e of t){const t=s("li",Ct.gridItem);t.append(e),o.append(t)}return o}(function(t,e){return(Array.isArray(t)?t:[]).map(t=>e(t)).filter(t=>void 0!==t)}(t,t=>h(t,e,n)),n),addToCart:async function(t,n,o){const i=Et();let s;return r.cart.kind=i,s="dawn"===i?await async function(t,n,o){const r=document.querySelector("cart-notification")??document.querySelector("cart-drawer")??void 0,i=new FormData;i.append("id",t),i.append("quantity",String(n)),"function"==typeof r?.getSectionsToRender&&(i.append("sections",r.getSectionsToRender().map(t=>t.id).join(",")),i.append("sections_url",globalThis.location.pathname),r.setActiveElement?.(document.activeElement));const{json:s,isRefused:a}=await M(o,{headers:B,body:i}),c=I();if(a)throw c&&"function"==typeof L.publish&&L.publish(c.cartError,{source:"callimacus",productVariantId:t,errors:s.description,message:s.message}),j(s);if(c&&"function"==typeof L.publish&&L.publish(c.cartUpdate,{source:"callimacus",productVariantId:t}),"function"==typeof r?.renderContents&&void 0!==s.sections)try{return r.renderContents(s),r.classList.remove("is-empty"),s}catch(t){e.error("the cart could not redraw itself after adding",t)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:s})),s}(t,n,o):"horizon"===i?await D(t,n,o):await qt(t,n,o,r),r.cart.adds+=1,s},install(){"dawn"===Et()&&"function"!=typeof L.getCurrentSellingPlanId&&(L.getCurrentSellingPlanId=()=>"")},stats:r})}const jt=["header details-modal summary",'header [class*="search"] summary','header a[href$="/search"]','header a[href*="/search?"]','header button[aria-label*="earch" i]','header summary[aria-label*="earch" i]','header [class*="search-toggle"]',"header search-button button",'header [class*="search"] button','[class*="header"] a[href$="/search"]','[class*="header"] [class*="search-toggle"]','[class*="header"] button[aria-label*="earch" i]'],Ut=['header a[href$="/cart"]','[class*="header"] a[href$="/cart"]'],Ft=/search|js-|drawer|modal|toggle|open|trigger|active/iu,Dt="http://www.w3.org/2000/svg";function Pt(t){const e=t.getBoundingClientRect();return e.width>0&&e.height>0}function Wt(t){for(const e of t){const t=[...document.querySelectorAll(e)].find(t=>Pt(t)&&!t.closest("[data-callimacus-ui]"));if(t)return{node:t,selector:e}}}function zt(t){const e=Wt(jt)??Wt(Ut);if(!e)return{placed:!1,how:"no search or cart control found in the header"};const n=e.node,o=s("button","cal-header-ask");o.type="button",o.dataset.callimacusOpen="",o.dataset.callimacusUi="",o.setAttribute("aria-label",t);for(const t of n.classList)Ft.test(t)||o.classList.add(t);const r=Math.round(n.querySelector("svg")?.getBoundingClientRect().width??0);return o.append(function(t){const e=document.createElementNS(Dt,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width",String(t)),e.setAttribute("height",String(t)),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");const n=document.createElementNS(Dt,"path");return n.setAttribute("d","M12 3.5l1.6 4.4 4.4 1.6-4.4 1.6L12 15.5l-1.6-4.4L6 9.5l4.4-1.6zM18.5 14l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.4"),n.setAttribute("stroke-linejoin","round"),e.append(n),e}(r>0?r:20)),function(t){let e=t.closest("details-modal, details")??t;for(e.parentElement?.matches("details-modal")&&(e=e.parentElement);1===e.parentElement?.childElementCount&&!e.parentElement.matches('header, nav, [class*="icons"], [class*="actions"]');)e=e.parentElement;return e}(n).before(o),{placed:!0,how:`before ${e.selector}`}}function Vt({template:t,searchTerms:e,assistantLabel:n,entrance:o}){const r=s("div","cal-stage");r.dataset.callimacusUi="";const i=s("div");if(i.dataset.callimacusStage="",i.dataset.stageKind="index"===t?"home":"search"===t?"search":"page","search"===t&&""!==e){const t=s("div","cal-stage__intro cal-page-width");t.append(s("p","cal-stage__lede",`Answering “${e}”`)),r.append(t),i.dataset.askOnLoad=e}if("index"===t&&o&&r.append(function(t,e){const n=s("div","cal-stage__intro cal-entrance cal-page-width");""!==t.heading&&n.append(s("h2","cal-stage__heading",t.heading)),""!==t.subheading&&n.append(s("p","cal-stage__lede",t.subheading));const o=s("form","cal-entrance__form");o.dataset.callimacusForm="";const r=s("input","cal-entrance__input");r.type="text",r.name="q",r.maxLength=200,r.autocomplete="off",r.enterKeyHint="send",r.placeholder=""===t.placeholder?`${e} anything`:t.placeholder,r.setAttribute("aria-label",e);const i=s("button","cal-button",""===t.buttonLabel?"Ask":t.buttonLabel);if(i.type="submit",o.append(r,i),n.append(o),t.starters.length>0){const e=s("div","cal-entrance__starters");for(const n of t.starters){const t=s("button","cal-chip cal-button cal-button--secondary",n);t.type="button",t.dataset.callimacusAsk=n,e.append(t)}n.append(e)}return n}(o,n)),"index"===t){const t=s("div","cal-welcome cal-page-width");t.dataset.callimacusWelcome="",t.hidden=!0,i.append(t)}const a=s("div");a.dataset.callimacusThread="",i.append(a),r.append(i);const c=document.querySelector("#MainContent")??document.querySelector("main")??document.querySelector('[role="main"]')??document.body,d="product"===t?function(t){const e=t.querySelector('form[action*="/cart/add"]'),n=e?.closest('[id^="shopify-section-"]')??void 0;return n&&t.contains(n)?n:void 0}(c):"index"===t?function(t){return t.querySelector(':scope > [id^="shopify-section-"]')??void 0}(c):void 0;return d?(d.after(r),{placed:!0,how:`after ${d.id}`}):(c.prepend(r),{placed:!0,how:`top of ${""===c.id?c.tagName.toLowerCase():`#${c.id}`}`})}const Ht="callimacus.rejected";function Kt(t){const e=Number(t);return Number.isSafeInteger(e)?e:0}function Jt({status:t,reason:e}){r("sessionStorage",Ht,JSON.stringify({status:t,...void 0!==e&&{reason:e},until:Date.now()+6e5}))}function Yt(){const t=o("sessionStorage",Ht);if(void 0===t)return;let e;try{e=JSON.parse(t)}catch{e=void 0}return u(e)?"number"==typeof e.until&&e.until<=Date.now()?void i("sessionStorage",Ht):{status:Kt(e.status),..."string"==typeof e.reason&&{reason:e.reason}}:{status:Kt(t)}}const Gt="callimacus.session";function Xt(t){return"string"==typeof t?t:""}function Zt(t){return u(t)&&u(t.tokens)&&"string"==typeof t.css?{tokens:t.tokens,css:t.css,readAt:Xt(t.readAt)}:void 0}function Qt(t){if(!u(t))return;const e=Array.isArray(t.starters)?t.starters.filter(t=>"string"==typeof t&&""!==t.trim()):[];return{heading:Xt(t.heading),subheading:Xt(t.subheading),placeholder:Xt(t.placeholder),buttonLabel:Xt(t.buttonLabel),starters:e}}function te(t,e){if(u(t)&&""!==Xt(t.token)&&""!==Xt(t.endpoint)&&!Number.isNaN(Date.parse(Xt(t.expiresAt))))return{token:Xt(t.token),endpoint:Xt(t.endpoint),expiresAt:Xt(t.expiresAt),themeId:e,entrance:Qt(t.entrance),look:Zt(t.look)}}async function ee(t){try{const e=await t.json();return u(e)&&"string"==typeof e.reason?e.reason:void 0}catch{return}}function ne(t,n){const i=t.endsWith("/")?t.slice(0,-1):t;let s,a;function c(t){return s=t,t&&r("sessionStorage",Gt,JSON.stringify(t)),t}async function d(){return a??=(async()=>{try{const t=await fetch(`${i}/session?theme_id=${encodeURIComponent(n)}`,{headers:{accept:"application/json"}});if([401,403,404].includes(t.status))return Jt({status:t.status,reason:await ee(t)}),c(void 0);if(!t.ok)throw new Error(`the storefront session answered ${t.status}`);return c(te(await t.json(),n))}finally{a=void 0}})(),a}async function l(){return s??=await async function(){const t=globalThis.callimacusSession;if(Reflect.deleteProperty(globalThis,"callimacusSession"),t)try{return te(await t,n)}catch(t){return void e.warn("the loader could not get a storefront session",t)}}()??function(){try{const t=JSON.parse(o("sessionStorage",Gt)??"null");return u(t)&&t.themeId===n?te(t,n):void 0}catch{return}}(),s}return{current:async function(){if(void 0!==Yt())return;const t=await l(),e=function(t){return void 0!==t&&Date.parse(t.expiresAt)-Date.now()>3e5}(t)?t:await d();return e?{token:e.token,endpoint:e.endpoint}:void 0},renew:async function(){const t=await d();return t?{token:t.token,endpoint:t.endpoint}:void 0},known:l,keepLook:function(t){s&&c({...s,look:t})}}}const oe={fg:{property:"--cal-fg",kind:"color"},bg:{property:"--cal-bg",kind:"color"},bodyFont:{property:"--cal-font-body",kind:"font"},bodyWeight:{property:"--cal-font-body-weight",kind:"keyword"},bodyStyle:{property:"--cal-font-body-style",kind:"keyword"},bodySize:{property:"--cal-body-size",kind:"length"},headingFont:{property:"--cal-font-heading",kind:"font"},headingWeight:{property:"--cal-font-heading-weight",kind:"keyword"},headingStyle:{property:"--cal-font-heading-style",kind:"keyword"},headingCase:{property:"--cal-heading-transform",kind:"keyword"},buttonBg:{property:"--cal-button-bg",kind:"color"},buttonFg:{property:"--cal-button-fg",kind:"color"},buttonBorderColor:{property:"--cal-button-border-color",kind:"color"},buttonBorderWidth:{property:"--cal-button-border-width",kind:"length"},buttonRadius:{property:"--cal-radius-button",kind:"length"},buttonCase:{property:"--cal-button-transform",kind:"keyword"},buttonSpacing:{property:"--cal-button-letter-spacing",kind:"length"},buttonFont:{property:"--cal-font-button",kind:"font"},buttonWeight:{property:"--cal-font-button-weight",kind:"keyword"},secondaryFg:{property:"--cal-button2-fg",kind:"color"},mediaRadius:{property:"--cal-radius-media",kind:"length"},cardRadius:{property:"--cal-radius-card",kind:"length"},pageWidth:{property:"--cal-page-width",kind:"length"}},re={color:/^(?:#[\da-f]{3,8}|transparent|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([\s\d%+,\-./a-z]{1,80}\))$/iu,font:/^[\p{Letter}\p{Number} "',\-_]{1,200}$/u,length:/^(?:normal|none|-?(?:\d+(?:\.\d*)?|\.\d+)(?:px|rem|em|%|ch|vw)?)$/iu,keyword:/^(?:normal|bold|bolder|lighter|italic|oblique|none|uppercase|lowercase|capitalize|[1-9]\d{0,2}|1000)$/iu};function ie(t){return Object.entries(t).filter(t=>{return e=t[0],Object.hasOwn(oe,e)&&"string"==typeof t[1];var e}).map(([t,e])=>`${oe[t].property}:${e}`).join(";")}const se=/^#(?<digits>[\da-f]{3,8})$/u,ae=/^rgba?\((?<channels>[^)]*)\)$/u;function ce(t){const e=t.trim().toLowerCase(),n=se.exec(e)?.groups?.digits;if(void 0!==n){const t=n.length<=4?[...n].map(t=>t+t).join(""):n;if(6!==t.length&&8!==t.length)return;const e=e=>Number.parseInt(t.slice(e,e+2),16);return[e(0),e(2),e(4),8===t.length?e(6)/255:1]}const o=ae.exec(e)?.groups?.channels?.split(/[\s,/]+/u).filter(t=>""!==t);if(void 0===o||o.length<3||o.length>4)return;const[r=NaN,i=NaN,s=NaN,a=1]=o.map((t,e)=>function(t,e){const n=Number(t.endsWith("%")?t.slice(0,-1):t);return t.endsWith("%")?3===e?n/100:2.55*n:n}(t,e));return[r,i,s,a].some(t=>Number.isNaN(t))?void 0:[r,i,s,a]}function de([t,e,n]){const o=t=>{const e=t/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4};return.2126*o(t)+.7152*o(e)+.0722*o(n)}function le(t,e){return(Math.max(de(t),de(e))+.05)/(Math.min(de(t),de(e))+.05)}function ue(t){const e=void 0===t.bg?void 0:ce(t.bg),n=void 0===t.buttonBg?void 0:ce(t.buttonBg),o=void 0!==n&&n[3]>.5?n:e,r=void 0===t.buttonFg?void 0:ce(t.buttonFg);if(void 0===o||void 0===r)return t;const i=le(r,o);if(i>=3)return t;let s;for(const e of[t.fg,t.bg]){const t=void 0===e?void 0:ce(e),n=void 0===t?0:le(t,o);void 0!==e&&n>(s?.ratio??i)&&(s={value:e,ratio:n})}return void 0===s?t:{...t,buttonFg:s.value}}const he="callimacus-look";let pe;function fe(){return pe?.isConnected||(pe=document.createElement("div"),pe.setAttribute("aria-hidden","true"),pe.style.cssText="position:absolute;left:-9999px;top:0;width:400px;visibility:hidden;pointer-events:none;",document.body.append(pe)),pe}function me(t,e){const n=document.createElement("span");if(n.style.display="block",n.style[t]=e,""===n.style[t])return"";fe().append(n);const o=getComputedStyle(n)[t];return n.remove(),o}function ge(t){const e=t.getBoundingClientRect(),n=getComputedStyle(t);return e.width>4&&e.height>4&&"hidden"!==n.visibility&&"none"!==n.display}function ye(t){return"transparent"===t||/^rgba\((?:[^),]*,){3}\s*0(?:\.0+)?\)$/u.test(t)||/\/\s*0(?:\.0+)?\)$/u.test(t)}function be(t,e=()=>!0){for(const n of t)for(const t of document.querySelectorAll(n))if(!b(t)&&ge(t)&&e(t))return{node:t,selector:n}}function ve(t){const e=[...t.classList].slice(0,2).map(t=>`.${t}`).join("");return`${t.tagName.toLowerCase()}${e}`}const we=/\b(?:add to (?:cart|bag|basket)|buy now|add)\b/iu,ke=['form[action*="/cart/add"] button[type="submit"]','form[action*="/cart/add"] button[name="add"]','form[action*="/cart/add"] input[type="submit"]','form[action*="/cart/add"] button:not([type="button"])'],Se=["main .button:not(.button--secondary):not(.button--tertiary)","main .btn:not(.btn--secondary)",'main a[class*="button"]','main button[class*="button"]',".shopify-section .button",".shopify-section .btn",'main button[type="submit"]'],Ae=[".shopify-payment-button__button--unbranded"],xe=/secondary|outline|tertiary/iu,_e=["main .button--secondary","main .btn--secondary",'main [class*="button-secondary"]'],Ce=["main h1","main h2","h1","h2",".h1",".h2"],Ee=['main a[href*="/products/"] img','a[href*="/products/"] img'],Re=[".card","product-card",".product-card",'[class*="product-card"]',".grid-product",".grid-view-item",".product-item"],Te=["main .page-width",".page-width","main .container","main .wrapper",".page-container .page-width","main .grid__item"],qe=/banner|hero|slideshow|slider|carousel|video|image-with-text/iu;function Oe(t,e){const n=[];for(let o=t.parentElement;o&&n.length<e;o=o.parentElement)n.push(o);return n}function $e(t){return t.matches('button, a[href], input[type="submit"], input[type="button"]')}function Ne(t){const e=[];let n=0,o=0;for(const[r,i]of[...t].entries())n+="("===i?1:")"===i?-1:0,","===i&&0===n&&(e.push(t.slice(o,r)),o=r+1);return e.push(t.slice(o)),e}function Le(t){for(const e of["::after","::before"]){const n=Ne(getComputedStyle(t,e).boxShadow);for(const t of n){const n=/^(?<color>rgba?\([^)]*\))\s+0px\s+0px\s+0px\s+(?<width>[\d.]+)px$/u.exec(t.trim());if(void 0!==n?.groups?.color&&!ye(n.groups.color))return{width:`${n.groups.width}px`,color:n.groups.color,how:`${e} outline`}}}}function Ie(t){return e=t.borderTopWidth,Number(e.replace(/px$/u,""))>0&&"none"!==t.borderTopStyle&&!ye(t.borderTopColor);var e}function Be(t){const e=t.getBoundingClientRect(),n=getComputedStyle(t);return e.width>=60&&e.height>=28&&!t.closest('header, nav, footer, [role="dialog"], dialog')&&(!ye(n.backgroundColor)||Ie(n)||void 0!==Le(t))}function Me(t){let e=t.parentElement;for(let t=0;e&&t<8&&!e.matches("main, body");t+=1){if(qe.test(e.className)||"none"!==getComputedStyle(e).backgroundImage)return!0;e=e.parentElement}return!1}function je(t,e){return xe.test(t.className)||getComputedStyle(t).backgroundColor===e}function Ue(t,e){const n=t=>e=>$e(e)&&Be(e)&&Me(e)===t,o="product"===t?be(ke,n(!1))??function(){for(const t of document.querySelectorAll('main button, main a[href], main input[type="submit"]')){const e=t instanceof HTMLInputElement?t.value:t.textContent;if(we.test(e.trim())&&!b(t)&&ge(t)&&Be(t))return{node:t,selector:"a button labelled add to cart"}}}():void 0,r=(o&&je(o.node,e)?be([...Ae,...Se],t=>n(!1)(t)&&!je(t,e)):void 0)??o??be(Se,n(!1))??("other"===t?be(Se,n(!0)):void 0);return r?{node:r.node,how:`button ${ve(r.node)}`}:void 0}function Fe(t,e,n,o){const r=Ie(e),i=r||!o?void 0:Le(o),s=r||void 0!==i;ye(e.backgroundColor)?s&&t("buttonBg","transparent",`${n} (outline)`):t("buttonBg",e.backgroundColor,n),t("buttonFg",e.color,n),i?(t("buttonBorderColor",i.color,`${n} ${i.how}`),t("buttonBorderWidth",i.width,`${n} ${i.how}`)):(t("buttonBorderColor",r?e.borderTopColor:e.backgroundColor,n),t("buttonBorderWidth",r?e.borderTopWidth:"0px",n)),t("buttonRadius",e.borderTopLeftRadius,n),t("buttonCase",e.textTransform,n),t("buttonSpacing","normal"===e.letterSpacing?"0px":e.letterSpacing,n),t("buttonFont",e.fontFamily,n),t("buttonWeight",e.fontWeight,n)}const De=[{name:"Dawn",marker:"--font-body-family",read:{fg:"rgb(var(--color-foreground, var(--color-base-text)))",bg:"rgb(var(--color-background, var(--color-base-background-1)))",bodyFont:"var(--font-body-family)",headingFont:"var(--font-heading-family)",buttonBg:"rgb(var(--color-button, var(--color-base-accent-1)))",buttonFg:"rgb(var(--color-button-text, var(--color-base-solid-button-labels)))",buttonRadius:"var(--buttons-radius)",mediaRadius:"var(--media-radius)",cardRadius:"var(--product-card-corner-radius)",pageWidth:"var(--page-width)"}},{name:"Horizon",marker:"--font-body--family",read:{fg:"var(--color-foreground)",bg:"var(--color-background)",bodyFont:"var(--font-body--family)",headingFont:"var(--font-heading--family)",buttonRadius:"var(--style-border-radius-buttons-primary)"}}];function Pe(t,e){const{kind:n}=oe[t];return me("color"===n?"color":"length"===n?"pageWidth"===t?"width":"borderTopLeftRadius":"fontFamily",e)}function We(t){const e={},n=(t,n,o)=>{const r=n.trim();!(""===r||!("buttonBg"===t&&"transparent"===r)&&"color"===oe[t].kind&&ye(r))&&void 0===e[t]&&function(t,e){return e.length<=200&&re[t].test(e.trim())}(oe[t].kind,r)&&(e[t]={value:r,how:o})};return function(t,e){const n=getComputedStyle(document.body);t("fg",n.color,"body text");let o=n.backgroundColor;ye(o)&&(o=getComputedStyle(document.documentElement).backgroundColor),t("bg",ye(o)?"rgb(255, 255, 255)":o,ye(o)?"browser default":"page background"),t("bodyFont",n.fontFamily,"body text"),t("bodyWeight",n.fontWeight,"body text"),t("bodyStyle",n.fontStyle,"body text"),t("bodySize",n.fontSize,"body text");const r=be(Ce,t=>""!==t.textContent.trim());if(r){const e=getComputedStyle(r.node),n=`heading ${ve(r.node)}`;t("headingFont",e.fontFamily,n),t("headingWeight",e.fontWeight,n),t("headingStyle",e.fontStyle,n),t("headingCase",e.textTransform,n)}const i=Ue(e,ye(o)?"rgb(255, 255, 255)":o);i&&Fe(t,getComputedStyle(i.node),i.how,i.node);const s=be(_e,t=>$e(t)&&!Me(t));s&&t("secondaryFg",getComputedStyle(s.node).color,`button ${ve(s.node)}`);const a=be(Ee);if(a){const e=[a.node,...Oe(a.node,4)].find(t=>!["0px","0",""].includes(getComputedStyle(t).borderTopLeftRadius));t("mediaRadius",e?getComputedStyle(e).borderTopLeftRadius:"0px",e?`product image ${ve(e)}`:`product image ${ve(a.node)} (square)`)}const c=be(Re);c&&t("cardRadius",getComputedStyle(c.node).borderTopLeftRadius,`card ${ve(c.node)}`);const d=be(Te,t=>"none"!==getComputedStyle(t).maxWidth&&t.getBoundingClientRect().width>300);d&&t("pageWidth",getComputedStyle(d.node).maxWidth,`content width ${ve(d.node)}`)}(n,t),function(t){const e=getComputedStyle(document.documentElement),n=De.find(t=>""!==e.getPropertyValue(t.marker).trim());for(const[e,o]of Object.entries(n?.read??{}))t(e,Pe(e,o),`${n?.name??""} variable ${o}`)}(n),"other"===t&&void 0===e.buttonFg&&function(t){const e=document.createElement("a");e.className="button button--primary btn btn--primary",e.href="#",e.textContent="Probe",fe().append(e);const n=getComputedStyle(e);ye(n.backgroundColor)||Fe(t,n,"probe .button.btn",void 0)}(n),fe().remove(),e}function ze(t){return Object.fromEntries(Object.entries(t).map(([t,e])=>[t,e.value]))}function Ve(t){let e=document.querySelector(`#${he}`);e||(e=document.createElement("style"),e.id=he,document.head.append(e)),e.textContent=`:root{${ie(t)}}`}function He(t){return Object.keys(oe).filter(e=>void 0===t[e])}function Ke(){return"function"==typeof globalThis.matchMedia&&globalThis.matchMedia("(prefers-color-scheme: dark), (forced-colors: active), (prefers-contrast: more)").matches||void 0!==document.documentElement.dataset.darkreaderScheme||null!==document.querySelector('meta[name="darkreader"]')}function Je(t,e){const n=performance.now();t.readings=We("product"),t.measureMs=Math.round(performance.now()-n);const o=function(t,e){const n=ue({...t,...ze(e)});return Object.keys(oe).some(e=>n[e]!==t[e])?n:void 0}(e,t.readings);void 0!==o&&(Ve(o),t.look=o,t.unset=He(o))}async function Ye({page:t,stored:e,post:n,keep:o}){if(e){Ve(e.tokens);const n={source:"stored",page:t,readings:{},look:e.tokens,unset:He(e.tokens)};return"product"===t&&Ke()&&Je(n,e.tokens),n}const r=performance.now(),i=We(t),s=function(t){return ue(ze(t))}(i),a={source:"read",page:t,readings:i,look:s,unset:He(s),measureMs:Math.round(performance.now()-r)};if(Ve(s),"product"!==t||0===Object.keys(s).length||Ke())return a;const c=await n(s).catch(()=>{});return a.posted=void 0===c?"failed":c.stored?"stored":"kept",c&&o(c.look),c&&!c.stored&&(Ve(c.look.tokens),a.look=c.look.tokens,a.unset=He(c.look.tokens)),a}
|
|
8
|
+
!function(){"use strict";const t="[callimacus]",e={debug(...e){console.debug(t,...e)},info(...e){console.info(t,...e)},warn(...e){console.warn(t,...e)},error(...e){console.error(t,...e)}};function n(t){try{return globalThis[t]}catch{return}}function o(t,e){try{return n(t)?.getItem(e)??void 0}catch{return}}function r(t,o,r){try{const e=n(t);return!!e&&(e.setItem(o,r),!0)}catch(n){return e.warn(`could not write ${t} "${o}"`,n),!1}}function i(t,o){try{n(t)?.removeItem(o)}catch(n){e.warn(`could not clear ${t} "${o}"`,n)}}function s(t,e="",n){const o=document.createElement(t);return""!==e&&(o.className=e),void 0!==n&&(o.textContent=n),o}function a(t,e=""){const n=s("p",`cal-cart-notice ${e}`.trim(),t.message);return n.setAttribute("role","status"),n.dataset.outcome=t.outcome,n}const c="http://www.w3.org/2000/svg";function d(t,e,n){const o=document.createElementNS(c,"svg");o.setAttribute("class",n),o.setAttribute("viewBox",t),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false");const r=document.createElementNS(c,"path");return r.setAttribute("d",e),r.setAttribute("fill","currentColor"),r.setAttribute("fill-rule","evenodd"),r.setAttribute("clip-rule","evenodd"),o.append(r),o}function l(t,e){for(const n of e.split(/\n{2,}/u)){const e=s("p");for(const[t,o]of n.split("**").entries())""!==o&&e.append(t%2==1?s("strong","",o):document.createTextNode(o));e.childNodes.length>0&&t.append(e)}}function u(t){for(let e=t;e&&e!==document.body;e=e.parentElement??void 0){const{position:t}=getComputedStyle(e);if("fixed"===t||"sticky"===t)return e}}function h(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function p(t){if(!h(t)||!h(t.fields))return!1;const e=t.fields["shopify-handle"];return"string"==typeof e&&""!==e}function f(t){return"string"==typeof t.kind&&""!==t.kind?t.kind:"product"}const m=/^\s*\{\s*"error"\s*:/u;function g(t){return"string"==typeof t&&""!==t.trim()&&!m.test(t)}function y(...t){for(const e of t)if(g(e))return e.trim();return""}function b(t){return"string"==typeof t?t.trim():""}function v(t){return null!==t.closest("[data-callimacus-ui], .cal-dock, .cal-stage, .cal-toast")}function w(t){const e=new Set,n=[];for(const o of t){if(!p(o))continue;const t=f(o),r=`${t}:${o.fields["shopify-handle"]}`,i=(o.fields.title??"").trim().toLowerCase(),s=`${t}|${i}`;e.has(r)||""!==i&&e.has(s)||(e.add(r),""!==i&&e.add(s),n.push(o))}return n}function k(t,e){const n=t.trim();if(n.length<=e)return n;const o=n.slice(0,e-1),r=o.lastIndexOf(" ");return`${(r>e/2?o.slice(0,r):o).trimEnd()}…`}function S(t){return h(t)&&h(t.meta)&&Array.isArray(t.sections)}function A(t){const e=(t.sections??[]).filter(t=>h(t)&&"text"===t.type&&g(t.content)).flatMap(t=>String(t.content).split(/\n{2,}/u)).map(t=>t.trim()).filter(t=>g(t)),n=[];let o=600;for(const t of e){if(t.length>o){0===n.length&&n.push(k(t,o));break}n.push(t),o-=t.length}return n}function _(t){const e=t?.data;return h(e)?Object.values(e):[]}function x(t){return _(t).some(t=>function(t){return null!=t&&("string"==typeof t?g(t):Array.isArray(t)?t.length>0:"object"!=typeof t||Object.keys(t).length>0)}(t))}function C(t){if(Array.isArray(t))return t.map(t=>C(t));if(S(t)){const e=t.meta??{};return{id:t.id,name:t.name,meta:{url:e.url,title:e.title,shopifyKind:e.shopifyKind},sections:A(t).map(t=>({type:"text",content:t}))}}if(p(t)&&"product"!==f(t)){const{fields:e}=t;return{id:t.id,kind:t.kind,fields:{title:e.title,"shopify-handle":e["shopify-handle"],"shopify-blogHandle":e["shopify-blogHandle"],"shopify-publishedAt":e["shopify-publishedAt"],"shopify-author":e["shopify-author"],"shopify-productsCount":e["shopify-productsCount"],descriptionText:g(e.descriptionText)?k(e.descriptionText,240):void 0,images:(e.images??[]).slice(0,2).map(t=>({url:t?.url,alt:t?.alt}))}}}if(p(t)){const{fields:e}=t;return{id:t.id,kind:t.kind,fields:{title:e.title,"shopify-handle":e["shopify-handle"],"shopify-vendor":e["shopify-vendor"],"shopify-productType":e["shopify-productType"],price:e.price,availableSizes:e.availableSizes,images:(e.images??[]).slice(0,2).map(t=>({url:t?.url,alt:t?.alt})),variantTree:{variants:(e.variantTree?.variants??[]).map(t=>({id:t?.id,axes:t?.axes,price:t?.price,orderable:t?.orderable}))}}}}return h(t)?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,C(e)])):t}const E=["aria-labelledby","aria-describedby","aria-controls","for","form"];function R(t){const e=t.fields.variantTree?.variants;return Array.isArray(e)?e:[]}function T(t){const e=R(t);return e.length>0&&e.every(t=>!0!==t?.orderable)}function q(t){const e=globalThis.Shopify,n=y(t.settings.rootUrl,e?.routes?.root,"/");return n.endsWith("/")?n:`${n}/`}async function O(t){return new Promise(e=>{setTimeout(e,t)})}function $(t,e,n){const{hit:o}=t,r=s("span");if(R(o).length>1||Array.isArray(o.fields.availableSizes)&&o.fields.availableSizes.length>1){const t=s("a",n.className);return t.href=e.url(o),r.textContent=n.labels.choose,t.append(r),t}const i=s("button",n.className);i.type="button",i.setAttribute("aria-live","polite"),i.append(r),n.busy&&i.append(n.busy);const a=e.variantId(o);if(""===a)return r.textContent=n.labels.soldOut,i.disabled=!0,i;r.textContent=n.labels.add;return i.addEventListener("click",()=>{(async()=>{if("true"!==i.getAttribute("aria-disabled")){i.setAttribute("aria-disabled","true"),i.classList.add("loading"),n.busy?.classList.remove("hidden");try{await e.addToCart(a),e.remember?.("added",t.handle),r.textContent=n.labels.added,await O(2e3),r.textContent=n.labels.add}catch(t){r.textContent=t instanceof Error&&""!==t.message?t.message:n.labels.failed}finally{i.classList.remove("loading"),n.busy?.classList.add("hidden"),i.removeAttribute("aria-disabled")}}})()}),i}function N(t){if("string"==typeof t){const e=t.trim();return""===e?void 0:{handle:e,hit:void 0,title:""}}return p(t)?"product"===f(t)?{handle:t.fields["shopify-handle"],hit:t,title:b(t.fields.title)}:void 0:h(t)&&""!==b(t.handle)?{handle:b(t.handle),hit:void 0,title:b(t.title)}:void 0}function L(t,e){const n=new Map,o=new Map,r=new Map,i=new Map,a=[];let c,d=0;function l(){for(;d<6&&a.length>0;)d+=1,a.shift()?.()}async function u(r,i){const{handle:s}=r,c=n.get(s);if(c)return c;const u="string"==typeof t?`${q(i)}products/${encodeURIComponent(s)}?section_id=${t}`:t(r,q(i)),h=async function(t){return new Promise((e,n)=>{a.push(()=>{t().then(e).catch(n).finally(()=>{d-=1,l()})}),l()})}(async()=>fetch(u,{headers:{Accept:"text/html"}})).then(async t=>t.ok?t.text():void 0).then(t=>void 0===t?void 0:e.extract(t,r)).catch(()=>{}).then(t=>(o.set(s,t),t));return n.set(s,h),h}function h(t,n,o){const i=t.content.firstElementChild;if(!i)throw new Error("empty card template");const s=document.importNode(i,!0);if(void 0!==o.sizes)for(const t of s.querySelectorAll("img[srcset]"))t.sizes=o.sizes;const a=(r.get(n)??0)+1;return r.set(n,a),e.prepare?.(s),a>1&&function(t,e){const n=new Map;for(const o of t.querySelectorAll("[id]"))n.set(o.id,o.id+e),o.id+=e;for(const e of t.querySelectorAll(E.map(t=>`[${t}]`).join(",")))for(const t of E){const o=e.getAttribute(t);null!==o&&""!==o&&e.setAttribute(t,o.split(/\s+/u).map(t=>n.get(t)??t).join(" "))}}(s,`-${a}`),s}function p(t,n,o){t.classList.remove("cal-card--pending"),t.classList.add("cal-card--offline"),o.hit||e.offline(n,o)}return{card:function(t,n,r={}){const a=N(t);if(!a)return;c=n,a.hit&&function(t,e){for(const n of R(t)){const t=String(n?.id??"").split("/").pop()??"";""!==t&&i.set(t,e)}}(a.hit,a.handle);const d=s("div","cal-card");d.dataset.handle=a.handle;const l=o.get(a.handle);if(l)return d.append(h(l,a.handle,r)),d;const f=a.hit?e.placeholder({...a,hit:a.hit},n,r):e.skeleton(a,n,r);return d.append(f),o.has(a.handle)?(p(d,f,a),d):(d.classList.add("cal-card--pending"),u(a,n).then(async t=>{t?await async function({host:t,draft:e},n,o,r){const i=h(n,o,r),s=e.querySelector("img"),a=i.querySelector("img");a&&s?.complete&&s.naturalWidth>0&&(a.loading="eager",await Promise.race([a.decode().catch(()=>{}),O(800)])),e.replaceWith(i),t.classList.remove("cal-card--pending")}({host:d,draft:f},t,a.handle,r):p(d,f,a)}),d)},rememberAdded:function(t){const e="string"==typeof t||"number"==typeof t?String(t).split("/").pop()??"":"",n=i.get(e);void 0!==n&&c?.remember?.("added",n)}}}const I=globalThis;function B(){return"undefined"==typeof PUB_SUB_EVENTS?void 0:PUB_SUB_EVENTS}const M={Accept:"application/javascript","X-Requested-With":"XMLHttpRequest"};class j extends Error{code;constructor(t,e,n){super(e,n),this.name="CartAddError",this.code=t}}async function U(t){try{return await t(),{}}catch(t){const e=t instanceof Error&&""!==t.message?t.message:"Could not add to cart.";return{error:{code:t instanceof j?t.code:"failed",message:e}}}}async function F(t,e){let n;try{n=await fetch(`${t.cartAddUrl}.js`,{method:"POST",...e})}catch(t){throw new j("failed","Could not reach the cart. Check your connection and try again.",{cause:t})}const o=await n.json().catch(()=>{}),r=h(o)?o:{},i=y(r.description,r.message,"Could not add to cart.");return!Boolean(r.status)&&n.ok?{json:r,failure:void 0===o?new j("cart_unavailable",i):void 0}:{json:r,failure:new j(D("number"==typeof r.status?r.status:n.status),i)}}function D(t){return 422===t?"refused":404===t?"cart_unavailable":"failed"}const P="cart:update";function z(t,e){document.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:e}))}async function W(t,e,n){const o=new FormData;o.append("id",t),o.append("quantity",String(e));const r=[...document.querySelectorAll("cart-items-component[data-section-id]")].map(t=>t.dataset.sectionId??"").filter(t=>""!==t);r.length>0&&o.append("sections",r.join(","));const{json:i,failure:s}=await F(n,{headers:M,body:o});if(s)throw z("cart:error",{sourceId:"callimacus",data:{message:i.message,errors:i.errors,description:i.description}}),s;const a=await async function(t){try{const e=await fetch(`${q({settings:t})}cart.js`,{headers:{accept:"application/json"}}),n=await e.json();return h(n)?n:void 0}catch{return}}(n),c="number"==typeof a?.item_count?a.item_count:void 0;return z(P,{resource:a,sourceId:"callimacus",data:{source:void 0===c?"product-form-component":"callimacus",itemCount:c??e,variantId:t,sections:h(i.sections)?i.sections:void 0}}),i}
|
|
9
9
|
/*!
|
|
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 qn(){}class On 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=qn,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=In({xdomain:!1});return t&&null!==t.responseType}();function In(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 Bn="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=Bn?{}: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 Bn?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 On{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(In,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 V=Object.create(null);V.open="0",V.close="1",V.ping="2",V.pong="3",V.message="4",V.upgrade="5",V.noop="6";const H=Object.create(null);Object.keys(V).forEach(t=>{H[V[t]]=t});const K={type:"error",data:"parser error"},J="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Y="function"==typeof ArrayBuffer,G=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,X=({type:t,data:e},n,o)=>J&&e instanceof Blob?n?o(e):Z(e,o):Y&&(e instanceof ArrayBuffer||G(e))?n?o(e):Z(new Blob([e]),o):o(V[t]+(e||"")),Z=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function Q(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let tt;const et="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)et["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const nt="function"==typeof ArrayBuffer,ot=(t,e)=>{if("string"!=typeof t)return{type:"message",data:it(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:rt(t.substring(1),e)}:H[n]?t.length>1?{type:H[n],data:t.substring(1)}:{type:H[n]}:K},rt=(t,e)=>{if(nt){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=et[t.charCodeAt(e)],o=et[t.charCodeAt(e+1)],r=et[t.charCodeAt(e+2)],i=et[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 it(n,e)}return{base64:!0,data:t}},it=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,st=String.fromCharCode(30);function at(){return new TransformStream({transform(t,e){!function(t,e){J&&t.data instanceof Blob?t.data.arrayBuffer().then(Q).then(e):Y&&(t.data instanceof ArrayBuffer||G(t.data))?e(Q(t.data)):X(t,!1,t=>{tt||(tt=new TextEncoder),e(tt.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 ct;function dt(t){return t.reduce((t,e)=>t+e.length,0)}function lt(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 ut(t){if(t)return function(t){for(var e in ut.prototype)t[e]=ut.prototype[e];return t}(t)}ut.prototype.on=ut.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},ut.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},ut.prototype.off=ut.prototype.removeListener=ut.prototype.removeAllListeners=ut.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},ut.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},ut.prototype.emitReserved=ut.prototype.emit,ut.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},ut.prototype.hasListeners=function(t){return!!this.listeners(t).length};const ht="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),pt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ft(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const mt=pt.setTimeout,gt=pt.clearTimeout;function yt(t,e){e.useNativeTimers?(t.setTimeoutFn=mt.bind(pt),t.clearTimeoutFn=gt.bind(pt)):(t.setTimeoutFn=pt.setTimeout.bind(pt),t.clearTimeoutFn=pt.clearTimeout.bind(pt))}function bt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class vt extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}let wt=class extends ut{constructor(t){super(),this.writable=!1,yt(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 vt(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=ot(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 kt extends wt{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(st),o=[];for(let t=0;t<n.length;t++){const r=ot(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)=>{X(t,!1,t=>{o[i]=t,++r===n&&e(o.join(st))})})})(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]=bt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let St=!1;try{St="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const At=St;function _t(){}class xt extends kt{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 Ct extends ut{constructor(t,e,n){super(),this.createRequest=t,yt(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=ft(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=Ct.requestsCount++,Ct.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=_t,t)try{this.O.abort()}catch(t){}"undefined"!=typeof document&&delete Ct.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 Et(){for(let t in Ct.requests)Ct.requests.hasOwnProperty(t)&&Ct.requests[t].abort()}Ct.requestsCount=0,Ct.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Et):"function"==typeof addEventListener&&addEventListener("onpagehide"in pt?"pagehide":"unload",Et,!1));const Rt=function(){const t=Tt({xdomain:!1});return t&&null!==t.responseType}();function Tt(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||At))return new XMLHttpRequest}catch(t){}if(!e)try{return new(pt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const qt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Ot extends wt{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=qt?{}:ft(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;X(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}o&&ht(()=>{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]=bt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const $t=pt.WebSocket||pt.MozWebSocket;const Nt={websocket:class extends Ot{createSocket(t,e,n){return qt?new $t(t,e,n):e?new $t(t,e):new $t(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends wt{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){ct||(ct=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(dt(n)<1)break;const t=lt(n,1);i=!(128&~t[0]),r=127&t[0],o=r<126?3:126===r?1:2}else if(1===o){if(dt(n)<2)break;const t=lt(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),o=3}else if(2===o){if(dt(n)<8)break;const t=lt(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),i=e.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(K);break}r=i*Math.pow(2,32)+e.getUint32(4),o=3}else{if(dt(n)<r)break;const t=lt(n,r);a.enqueue(ot(i?t:ct.decode(t),e)),o=0}if(0===r||r>t){a.enqueue(K);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),o=at();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&&ht(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends xt{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Rt&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Ct(Tt,this.uri(),t)}}},Lt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,It=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Bt(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=Lt.exec(t||""),i={},s=14;for(;s--;)i[It[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 Mt="function"==typeof addEventListener&&"function"==typeof removeEventListener,jt=[];Mt&&addEventListener("offline",()=>{jt.forEach(t=>t())},!1);class Ut extends ut{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=Bt(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=Bt(e.host).host);if(yt(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=Nt),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)),Mt&&(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"})},jt.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&&Ut.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;Ut.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;Ut.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",Ut.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,ht(()=>{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(Ut.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(),Mt&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=jt.indexOf(this.$);-1!==t&&jt.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}}Ut.protocol=4;const Ft="function"==typeof ArrayBuffer,Dt=Object.prototype.toString,Pt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Dt.call(Blob),zt="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Dt.call(File);function Wt(t){return Ft&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||Pt&&t instanceof Blob||zt&&t instanceof File}function Vt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(Vt(t[e]))return!0;return!1}if(Wt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Vt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Vt(t[e]))return!0;return!1}function Ht(t){const e=[],n=t.data,o=t;return o.data=Kt(n,e),o.attachments=e.length,{packet:o,buffers:e}}function Kt(t,e,n){if(!t)return t;if(Wt(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]=Kt(t[o],e);return n}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!n)return Kt(t.toJSON(),e,!0);const o={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(o[n]=Kt(t[n],e));return o}return t}function Jt(t,e){return t.data=Yt(t.data,e),delete t.attachments,t}function Yt(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]=Yt(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=Yt(t[n],e));return t}const Gt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xt;!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"}(Xt||(Xt={}));class Zt extends ut{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===Xt.BINARY_EVENT;n||e.type===Xt.BINARY_ACK?(e.type=n?Xt.EVENT:Xt.ACK,this.reconstructor=new Qt(e)):super.emitReserved("decoded",e)}else{if(!Wt(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===Xt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Xt.BINARY_EVENT||n.type===Xt.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(!te(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(!Zt.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 Xt.CONNECT:return ee(e);case Xt.DISCONNECT:return void 0===e;case Xt.CONNECT_ERROR:return"string"==typeof e||ee(e);case Xt.EVENT:case Xt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===Gt.indexOf(e[0]));case Xt.ACK:case Xt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Qt{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=Jt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const te=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ee(t){return"[object Object]"===Object.prototype.toString.call(t)}var ne=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Xt},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==Xt.EVENT&&t.type!==Xt.ACK||!Vt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Xt.EVENT?Xt.BINARY_EVENT:Xt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Xt.BINARY_EVENT&&t.type!==Xt.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=Ht(t),n=this.encodeAsString(e.packet),o=e.buffers;return o.unshift(n),o}},Decoder:Zt,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||te(e))&&function(t,e){switch(t){case Xt.CONNECT:return void 0===e||ee(e);case Xt.DISCONNECT:return void 0===e;case Xt.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===Gt.indexOf(e[0]));case Xt.ACK:return Array.isArray(e);case Xt.CONNECT_ERROR:return"string"==typeof e||ee(e);default:return!1}}(t.type,t.data);var e}});function oe(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const re=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ie extends ut{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=[oe(t,"open",this.onopen.bind(this)),oe(t,"packet",this.onpacket.bind(this)),oe(t,"error",this.onerror.bind(this)),oe(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(re.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:Xt.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:Xt.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 Xt.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 Xt.EVENT:case Xt.BINARY_EVENT:this.onevent(t);break;case Xt.ACK:case Xt.BINARY_ACK:this.onack(t);break;case Xt.DISCONNECT:this.ondisconnect();break;case Xt.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:Xt.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:Xt.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 se(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}se.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)},se.prototype.reset=function(){this.attempts=0},se.prototype.setMin=function(t){this.ms=t},se.prototype.setMax=function(t){this.max=t},se.prototype.setJitter=function(t){this.jitter=t};class ae extends ut{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,yt(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 se({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||ne;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 Ut(this.uri,this.opts);const e=this.engine,n=this;this.ht="opening",this.skipReconnect=!1;const o=oe(e,"open",function(){n.onopen(),t&&t()}),r=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},i=oe(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(oe(t,"ping",this.onping.bind(this)),oe(t,"data",this.ondata.bind(this)),oe(t,"error",this.onerror.bind(this)),oe(t,"close",this.onclose.bind(this)),oe(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){ht(()=>{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 ie(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 ce={};function de(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=Bt(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=ce[r]&&i in ce[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new ae(o,e):(ce[r]||(ce[r]=new ae(o,e)),a=ce[r]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(de,{Manager:ae,Socket:ie,io:de,connect:de});
|
|
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="cart-command",wo="error",ko="server-response",So="client-ready",Ao="user-interaction",xo={debug:0,info:1,warn:2,error:3,silent:4},_o=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&&xo[t]>=xo[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 Co(){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 Eo,Ro;!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"}(Eo||(Eo={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Ro||(Ro={}));const To={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class qo{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??To.minVisibilityRatio;this.config={productSelector:t.productSelector??To.productSelector,blockSelector:t.blockSelector??To.blockSelector,maxTrackedElements:t.maxTrackedElements??To.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 _o.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=To;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{_o.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(So)}),this.socket.on("disconnect",()=>{_o.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&&(_o.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(wo,t=>{_o.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{_o.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{_o.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{_o.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{_o.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(ko,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){_o.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){_o.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&&(_o.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,_o.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){_o.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 _o.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new qo(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&&(_o.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};_o.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),_o.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...To,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 qo(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void _o.error("Socket is not connected. Cannot send interaction.");if(t===Eo.SUGGEST)return void _o.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Eo.BACK_FROM_ROUND&&void 0===e.chapterId)return void _o.error("BACK_FROM_ROUND requires chapterId.");const n={type:t,payload:this.enrichPayloadWithUiContext(e)},o={id:Co()};this.socket.emit(Ao,{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(Ao,{type:Eo.SUGGEST,payload:t}))}catch(t){return _o.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 $o=["hero","answer","picks","topic","cross","next","other"],No=["hero","answer","picks","topic","cross","next"],Lo=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 Io(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(Io(o)&&o.type===t)return o}}function Mo(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||(Lo.has(t)?void(i.has(t)||(i.add(t),e.warn(`no renderer for ${t}, skipped`))):r)}}function jo(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 Uo(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 $o){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 Fo(t,e){const n=t.slots.get(e);if(!n)throw new Error(`chapter has no ${e} slot`);return n}function Do(t,e){t.el.dataset.state=e,t.el.setAttribute("aria-busy",String("streaming"===e))}function Po(t){let e;for(const n of t)(!e||n.index>e.index)&&(e=n);return e}function Wo(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)}const zo=/^gid:\/\/shopify\/ProductVariant\/\d+$/u;function Vo({add:t,say:e,emit:n,copy:o}){const r=new Set;return async i=>{const s=function(t){if("object"!=typeof t||null===t)return;const{command:e,chapterId:n,variantId:o,quantity:r,item:i}=t;if("shopify-add"!==e||"string"!=typeof n||"string"!=typeof o||!zo.test(o))return;const s="number"==typeof r&&Number.isFinite(r)?Math.trunc(r):1,a="object"==typeof i&&null!==i&&"string"==typeof i.name?i.name:"";return{chapterId:n,variantId:o,quantity:Math.min(Math.max(s,1),10),name:a}}(i);if(!s||r.has(s.chapterId))return;r.add(s.chapterId);const{variantId:a,quantity:c}=s;try{await t(a,c),e(""===s.name?o.done:o.addedToBag(s.name),{clearAfter:8e3}),n("callimacus:cart",{outcome:"added",variantId:a,quantity:c})}catch(t){const r=t instanceof Error&&""!==t.message?t.message:o.notAdded;e(r,{clearAfter:8e3}),n("callimacus:cart",{outcome:"refused",variantId:a,quantity:c,message:r})}}}function Ho(t,e=""){return"string"==typeof t&&""!==t.trim()?t.trim():e}function Ko(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 Jo(){return globalThis.Shopify}function Yo(){try{const t=Jo()?.customerPrivacy?.preferencesProcessingAllowed?.();return void 0===t?"unknown":!0===t?"allowed":"refused"}catch{return"unknown"}}function Go(t){return o("sessionStorage",t)??("allowed"===Yo()?o("localStorage",t):void 0)}function Xo(t){const n=Go(t);if(void 0!==n&&""!==n)try{return JSON.parse(n)}catch{return void e.warn(`ignoring unreadable "${t}"`)}}function Zo(t,e){const n=r("sessionStorage",t,e);return"allowed"!==Yo()||r("localStorage",t,e)||i("localStorage",t),n}function Qo(t){i("localStorage",t),i("sessionStorage",t)}function tr(t){const e=Yo();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 er="callimacus.memory",nr=6,or=12,rr=12,ir=new TextEncoder;function sr(t){return Array.isArray(t)?t.filter(t=>u(t)):[]}function ar(t){return"number"==typeof t&&Number.isFinite(t)?t:0}function cr(){const t=Xo(er),e=u(t)?t:{};return{questions:sr(e.questions).filter(t=>"string"==typeof t.q).map(t=>({q:t.q,at:ar(t.at)})),viewed:sr(e.viewed).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,title:"string"==typeof t.title?t.title:"",at:ar(t.at)})),added:sr(e.added).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,at:ar(t.at)}))}}function dr(t){return"string"==typeof t?t:u(t)&&"string"==typeof t.handle?t.handle:""}function lr(t,n){const o=cr(),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=dr(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=dr(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}"`)}Zo(er,JSON.stringify(o))}function ur(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,nr).map(t=>n(t)),viewed:t.viewed.filter(t=>o(t.handle)).slice(0,or).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,rr)};for(;ir.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 hr(t){return s("div",`cal-skeleton__bone cal-skeleton__bone--${t}`)}function pr(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(hr("media"),hr("title"),hr("price")),t.append(o),n.append(t)}return n}function fr(){const t=s("div","cal-skeleton__lines");return t.append(hr("line"),hr("line"),hr("line")),t}function mr(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?[hr("hero")]:[hr("lead"),fr()];case"answer":return[fr()];case"picks":return[pr(4,n)];case"topic":return[hr("topic")];case"cross":return[pr(3,n)];case"next":{const t=s("div","cal-skeleton__chips");return t.append(hr("chip"),hr("chip"),hr("chip")),[t]}case"other":return[]}}(t,i,n)),r.append(a),o.append(r),o}const gr="callimacus.thread",yr="callimacus.storyId",br=15e5;function vr(t){return Array.isArray(t)?t.filter(t=>u(t)&&"string"==typeof t.id&&""!==t.id):[]}function wr(t){const e=t.inputEvent;return u(e)&&u(e.data)?y(e.data.value):""}function kr(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 Sr(t){const e=Number(t);return Number.isFinite(e)?e:0}function Ar(){return Go(yr)}function xr(t){void 0===t?Qo(yr):Zo(yr,t)}function _r(){const t=Xo(gr);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:Sr(t.index),status:Sr(t.status),blocks:vr(t.blocks)}}).sort((t,e)=>t.index-e.index).slice(-12):[]}function Cr(t){return Math.round(performance.now()-t.t0)}const Er=4e3,Rr=[gr,yr,er],Tr="data-callimacus-on",qr=new Set([401,403]),Or=new Set(["invalid_token","origin_not_allowed","paused"]);function $r(t){return"function"==typeof globalThis.matchMedia?globalThis.matchMedia(t):{matches:!1}}function Nr(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)&&""!==Ho(t.product.handle)?Object.freeze({handle:Ho(t.product.handle),title:Ho(t.product.title),id:"number"==typeof t.product.id||"string"==typeof t.product.id?t.product.id:void 0}):void 0,r=Ho(t.storeName,"this store");return Object.freeze({language:Ho(t.language,"en"),rootUrl:Ho(t.rootUrl,"/"),cartAddUrl:Ho(t.cartAddUrl,"/cart/add"),currency:Ho(t.currency,"USD"),designMode:!0===t.designMode||Boolean(n?.designMode),template:Ho(t.template),product:o,storeName:r,assistantLabel:Ho(t.assistantLabel,`Ask ${r}`),starters:Object.freeze(Array.isArray(t.starters)?t.starters.map(t=>Ho(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.`,addedToBag:t=>`${t} is in your bag.`,notAdded:"This product cannot be added right now."}}(i),c=document.documentElement,d=new AbortController,{signal:h}=d,p=[],f=$r("(prefers-reduced-motion: reduce)"),m=$r("(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=Mo(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,xr(g.storyId)}async function E(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&&lr("added",r.handle),r}const R=Vo({add:E,say:A,emit:k,copy:a}),T=Ko(i,{addToCart:E,ask:t=>"refused"!==K(t,{type:"relatedQuestion"}),remember:lr});const q={stage:void 0,thread:void 0,earlier:void 0,trimmed:void 0,dock:document.querySelector("[data-callimacus-dock]")??void 0};function O(){return q.stage?.dataset.stageKind??"page"}function $(){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",()=>{L(!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(q,{stage:t,thread:e,earlier:o,trimmed:r}),{stage:t,thread:e}}function N(){return q.thread??$().thread}function L(t){q.thread&&(q.thread.toggleAttribute("data-compact",t),I())}function I(){if(!q.earlier||!q.thread||!q.trimmed)return;const t=g.thread.length-1,e=Object.hasOwn(q.thread.dataset,"compact"),n=e&&t>0;q.earlier.hidden=!n,n&&(q.earlier.textContent=`Show ${t} earlier question${1===t?"":"s"}`),q.trimmed.hidden=e||0===g.thread.length||g.thread.some(t=>0===t.index)}function B(){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 M(t){g.nextKey+=1;const e=Uo(g.nextKey,t,n.classes);return e.toggle.addEventListener("click",()=>{U(e,Object.hasOwn(e.el.dataset,"collapsed"))},{signal:h}),e}function j(t){for(const e of No){const o=Fo(t,e);o.querySelector(":scope > .cal-block, :scope > .cal-skeleton")||o.append(mr(e,t.index,n.classes))}}function U(t,e,{shouldAnimate:n=!0}={}){e!==!Object.hasOwn(t.el.dataset,"collapsed")&&(e||t.thumbs.replaceChildren(...function(t){const e=new Set,n=[],o=Wo(t).flatMap(t=>T.picks(t));for(const t of o){if(4===n.length)break;const o=t.fields["shopify-handle"],r=T.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 F(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 D(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",()=>{K(t.question,{type:"question",about:t.about})},{signal:h}),r.append(i),t.body.append(r)}function P(t,e,n,o){const r=Fo(t,Lo.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=Cr(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 W(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=jo(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=P(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=jo(i,n,o);return!1===c?a.isBroken=!0:c&&a.wrap&&(a.wrap.replaceChildren(c),a.node=c),!1}function z(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({...T,chapter:n,final:e})}(t);let r=0;for(const[i,s]of Wo(t).entries())W(t,s,o,{order:i,stagger:r,hasBecomeDone:e,shouldAnimate:n})&&(r+=1)}const V=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;switch(n.type){case 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)??Z(o);if(i){e&&st(i,r),Q(i,o,g.round?.rec===i);continue}const s=wr(o);if(!e||""===s)continue;const{question:a,about:c}=kr(s);rt({id:o.id,question:a,about:c,sent:s,index:r,status:"number"==typeof o.status?o.status:0,blocks:vr(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)||st(t,n++);yt(),it(),ot()}e&&(g.hydrateMode="refresh")}(e):"restore"===g.hydrateMode&&(g.hydrateMode="refresh")}(n.story);break;case 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)??Z(t);n?Q(n,t,!0):e.debug("chapter-event for a chapter this page does not show",t.id)}(n.chapter);break;case vo:R(n.data);break;default: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&&V.didRenew())return;if(function(t){return qr.has(t.code)&&(!g.isConnected||Or.has(t.reason??""))}(t))return void H(t);const{round:r}=g;if(404===n&&(C(void 0),dt({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(()=>{X(r)},o),void G(r);const i=!g.isConnected;if(i&&"retries_exhausted"!==t.reason&&!(n>=400&&n<500))return void(r&&A(a.reconnecting));i&&V.markFailed();r?(A(i?a.unavailable:a.failed),tt(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"};H({code:t,reason:e})}});function H(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}),dt(),g.queue=[],pt(),g.round&&tt(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(Tr),A("");k("callimacus:off",{code:t.code,reason:t.reason})}function K(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:Er}),"refused";const s={display:o,about:n,type:e,sent:void 0===n?o:`${o} (about the ${n})`,visit:ur(cr(),o)};return lr("questions",o),k("callimacus:ask",{question:o,type:e,queued:Boolean(g.round)}),g.round?(g.queue.push(s),pt(),A(a.queued(o),{clearAfter:Er}),"queued"):(J(s),"sent")}function J(t){const e=M({question:t.display,about:t.about,sent:t.sent,index:Y()});for(const t of g.thread)U(t,!1);g.thread.push(e),N().prepend(e.el),B(),Do(e,"streaming"),j(e),yt(),ht(),I();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(()=>{X(n)},o),F(e),ot(),k("callimacus:chapter",et(e)),G(n)}function Y(){let t=0;for(const e of g.thread)t=Math.max(t,e.index+1);return t}function G(t){try{V.connect()}catch(n){return e.error("could not start the Callimacus client",n),void(g.round===t&&(A(a.unavailable),tt(t.rec,"error")))}if(g.round===t)try{!function(t){const e={visit:t.visit,shopifyCart:!0},n={...void 0!==g.storyId&&{storyId:g.storyId},language:i.language,inputEvent:{type:t.type,data:{value:t.rec.sent}},context:e};V.send(Eo.CREATE_ROUND,n)}(t)}catch(n){e.error("could not send the question",n),A(a.failed),tt(t.rec,"error")}}function X(t){g.round===t&&(e.warn(`no complete answer within ${o/1e3} s for “${t.rec.question}”`),A(a.timeout),tt(t.rec,"timeout"))}function Z(t){const e=wr(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 Q(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,vr(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=Cr(r),r.chapterId=i),S("streaming"),A(a.streaming));const s=!o&&4===t.status;z(t,{hasBecomeDone:s,shouldAnimate:n}),s&&tt(t,"done")}function tt(t,n){const o="done"!==n;Do(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),D(t,o&&!g.isOff),function(t,n,o){if("pending"!==t?.outcome)return;t.outcome=o,t.chapterId=n,t.doneMs=Cr(t),performance.mark(`callimacus:chapter-${t.chapter}:${o}`);const{t0:r,...i}=t;e.debug("timing",i)}(t.timing,t.id,n),ot(),k("callimacus:chapter",et(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:Er})),function(){if(void 0!==g.round||g.isOff)return;const t=g.queue.shift();if(!t)return;pt(),J(t)}())}function et(t){return{id:t.id,index:t.index,question:t.question,state:t.el.dataset.state}}function nt(t){return{id:t.id,question:t.question,about:t.about,sent:t.sent,index:t.index,status:t.status,blocks:t.blocks}}function ot(){!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>br){for(const t of e)t.blocks=_(t.blocks);n=JSON.stringify(e)}for(;e.length>0;){if(n.length<=br&&Zo(gr,n))return;e.shift(),n=JSON.stringify(e)}Qo(gr)}(g.thread.map(t=>nt(t))),xr(g.storyId)}function rt(t){const e=M(t);g.thread.push(e);const n=4===e.status,o=!n&&void 0!==e.id&&void 0!==g.storyId;return Do(e,n?"done":o?"streaming":"error"),o&&j(e),z(e,{shouldAnimate:!1}),n||o||D(e,!0),e}function it(){B();const t=Po(g.thread),e="home"===O();for(const n of g.thread)U(n,e&&n===t||g.round?.rec===n,{shouldAnimate:!1});!function(){const t=[...g.thread].sort((t,e)=>e.index-t.index);N().append(...t.map(t=>t.el))}(),L(!e),ht()}function st(t,e){t.index=e,t.el.dataset.chapterIndex=String(e)}function at(){return g.thread.filter(t=>void 0!==t.id&&4!==t.status&&g.round?.rec!==t&&"streaming"===t.el.dataset.state)}function ct(t=0){clearTimeout(g.refreshTimer);const{storyId:n}=g;if(!(void 0===n||g.isOff||t>0&&"restore"!==g.hydrateMode&&0===at().length))if(t>=6)dt({shouldFailPending:!0});else{try{V.send(Eo.GET_STORY,{storyId:n})}catch(t){e.error("could not start the Callimacus client",t)}g.refreshTimer=setTimeout(()=>{ct(t+1)},3e3)}}function dt({shouldFailPending:t=!1}={}){if(clearTimeout(g.refreshTimer),g.hydrateMode=void 0,t)for(const t of at())tt(t,"error")}const lt=t=>q.dock?.querySelector(t)??void 0,ut={input:lt('input[name="q"]'),chips:lt("[data-callimacus-dock-chips]"),count:lt("[data-callimacus-thread-count]"),countLabel:lt("[data-callimacus-thread-count-label]"),next:lt("[data-callimacus-next]"),nextLabel:lt("[data-callimacus-next-label]"),about:lt("[data-callimacus-about]"),aboutLabel:lt("[data-callimacus-about-label]")};function ht(){if(!ut.count)return;const t=g.thread.length;ut.count.hidden=0===t;const e=`${t} question${1===t?"":"s"}`;ut.countLabel&&(ut.countLabel.textContent=String(t)),ut.count.title=e,ut.count.setAttribute("aria-label",`${e} in this conversation. Show the conversation`)}function pt(){if(!ut.next)return;const[t]=g.queue;if(ut.next.hidden=void 0===t,void 0!==t){const e=g.queue.length>1?` (+${g.queue.length-1})`:"";ut.nextLabel&&(ut.nextLabel.textContent=`Next: ${t.display}${e}`),ut.next.setAttribute("aria-label",`Next question: ${t.display}. Remove it from the queue`)}ut.chips&&(ut.chips.hidden=[...ut.chips.children].every(t=>t instanceof HTMLElement&&!0===t.hidden))}function ft(){const t=g.about;ut.about&&(ut.about.hidden=void 0===t),void 0!==t&&ut.aboutLabel&&(ut.aboutLabel.textContent=`About: ${t}`),ut.input&&(ut.input.placeholder=void 0===t?ut.input.dataset.placeholder??ut.input.placeholder:"Ask anything about it")}function mt(){ut.input&&(ut.input.focus(),vt())}function gt(){L(!1);const t=Po(g.thread);t&&(U(t,!0),F(t))}function yt(){const t=document.querySelector("[data-callimacus-welcome]");t&&(t.hidden=!0)}function bt(t){const e=s("section","cal-welcome__group");return e.append(s("h2","cal-welcome__title",t)),e}function vt(){if(!i.designMode&&!g.isOff)try{V.connect()}catch(t){e.error("could not start the Callimacus client",t)}}function wt(){return!g.isOff&&c.hasAttribute(Tr)}function kt(t){const e=t.target instanceof Element?t.target.closest("[data-callimacus-form]"):void 0;if(!e||!wt())return;t.preventDefault();const n=e.querySelector('input[name="q"]'),o=n?.value.trim()??"";n&&""!==o?("refused"!==K(o,{type:"question",about:g.about})&&(n.value=""),m.matches&&n.blur()):n?.focus()}function St(t){if(!(wt()&&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(),K(n,{type:"relatedQuestion"})))}t.target.closest("[data-callimacus-open]")&&(t.preventDefault(),mt())}function At(t){var e;wt()&&("/"!==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(),mt()))}const xt={ask:t=>"refused"!==K(t,{type:"question"}),get thread(){return[...g.thread].sort((t,e)=>t.index-e.index).map(t=>nt(t))},ctx:T,timings:b,get state(){return g.ui},get storyId(){return g.storyId},reset:function(){dt(),clearTimeout(g.round?.timer),g.round=void 0,g.queue=[];for(const t of g.thread)t.el.remove();g.thread=[],C(void 0),Qo(gr),pt(),ht(),L(!1),S("idle"),A("")}};c.dataset.callimacusState=g.ui;const _t=globalThis;if(_t.callimacus=xt,_t.callimacusTheme={card:n.card,cards:n.cards},void 0!==Yt()||!c.hasAttribute(Tr))return c.removeAttribute(Tr),g.isOff=!0,S("error"),k("callimacus:ready",{designMode:i.designMode,off:!0}),{page:xt,destroy:w};if(n.install?.(),function(t,e){tr(t),document.addEventListener("visitorConsentCollected",()=>{tr(t)},{signal:e})}(Rr,h),g.storyId=Ar(),document.addEventListener("submit",kt,{signal:h}),document.addEventListener("click",St,{signal:h}),document.addEventListener("keydown",At,{signal:h}),document.addEventListener("focusin",t=>{t.target instanceof Element&&t.target.matches('[data-callimacus-form] input[name="q"]')&&vt()},{signal:h}),ut.count?.addEventListener("click",gt,{signal:h}),ut.next?.addEventListener("click",()=>{g.queue.shift(),pt(),A(a.dequeued,{clearAfter:Er}),ut.input?.focus()},{signal:h}),q.dock?.querySelector("[data-callimacus-about-remove]")?.addEventListener("click",()=>{g.about=void 0,ft(),ut.input?.focus()},{signal:h}),function(){const{dock:t}=q;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||at().length>0)&&ot()},{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=_r().filter(n=>!e.has(t(n))),o=Ar();if(void 0!==o&&o!==g.storyId&&(g.storyId=o),0!==n.length){for(const t of n)rt(t);yt(),it(),I()}}()},{signal:h}),ft(),ht(),pt(),i.designMode)return k("callimacus:ready",{designMode:!0,off:!1}),{page:xt,destroy:w};i.product&&lr("viewed",{handle:i.product.handle,title:i.product.title});const{stage:Ct}=$();!function(){for(const t of _r())rt(t);return 0!==g.thread.length&&(it(),!0)}()?void 0!==g.storyId&&(g.hydrateMode="restore",ct()):at().length>0&&(g.hydrateMode="refresh",ct()),"home"===O()&&function(){const t=document.querySelector("[data-callimacus-welcome]");if(!t)return;const e=cr(),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=bt("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})),T):void 0;if(a){const t=bt("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 Et=y(Ct.dataset.askOnLoad);return""!==Et&&Po(g.thread)?.question!==Et&&K(Et,{type:"question"}),k("callimacus:ready",{designMode:!1,off:!1}),{page:xt,destroy:w}}const Lr="callimacus.pending";function Ir(){return document.querySelector("#callimacus-config")??void 0}async function Br(){const t=document.documentElement,n=function(){try{const t=JSON.parse(Ir()?.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(Tr),l=d()?void 0:async function(){const t=Jo();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=Ir();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}=Nr({kit:b,renderers:yt(b),session:c});Object.assign(v,{style:f,embed:{header:m,stage:g,...b.stats}});const w=o("sessionStorage",Lr);i("sessionStorage",Lr),void 0!==w&&""!==w.trim()&&v.ask(w)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Br()},{once:!0}):Br()}();
|
|
21
|
+
const le="chapter-event",ue="story-created",he="cart-command",pe="error",fe="server-response",me="client-ready",ge="user-interaction",ye={debug:0,info:1,warn:2,error:3,silent:4},be=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&&ye[t]>=ye[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 ve(){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 we,ke;!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"}(we||(we={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(ke||(ke={}));const Se={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class Ae{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??Se.minVisibilityRatio;this.config={productSelector:t.productSelector??Se.productSelector,blockSelector:t.blockSelector??Se.blockSelector,maxTrackedElements:t.maxTrackedElements??Se.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 be.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)}}}function _e(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}const xe=t=>"string"==typeof t&&t.length>0,Ce=t=>_e(t)&&xe(t.size)&&xe(t.variantId)&&"boolean"==typeof t.orderable;class Ee{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=Se;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{be.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(me)}),this.socket.on("disconnect",()=>{be.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&&(be.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(pe,t=>{be.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{be.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{be.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{be.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{be.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(fe,t=>{"chapter-event"===t.type&&this.notifyWarningListeners(function(t,e){return(t.warnings??[]).filter(n=>{const o=`${t.id}:${n.block}:${n.content}`;return!e.has(o)&&(e.add(o),!0)})}(t.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){be.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){be.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&&(be.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,be.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){be.error("Error in error listener:",t)}})}notifyWarningListeners(t){for(const e of t)0===this.warningListeners.size&&be.warn(`Block "${e.block}" was not shown: its content "${e.content}" failed (${e.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(t=>{try{t(e)}catch(t){be.error("Error in warning listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return be.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new Ae(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&&(be.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};be.info("Connecting to Thamyr at",o),this.socket=de(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),be.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Se,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 Ae(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void be.error("Socket is not connected. Cannot send interaction.");if(t===we.SUGGEST)return void be.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===we.BACK_FROM_ROUND&&void 0===e.chapterId)return void be.error("BACK_FROM_ROUND requires chapterId.");const n={type:t,payload:this.enrichPayloadWithUiContext(e)},o={id:ve()};this.socket.emit(ge,{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(ge,{type:we.SUGGEST,payload:t}))}catch(t){return be.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}onWarning(t){return this.warningListeners.add(t),()=>{this.warningListeners.delete(t)}}}const Re="callimacus:shopify-cart-commands",Te=new Set(["cart_disabled","cart_unavailable"]);function qe(t,e){const{item:n,quantity:o}=t,r=`${o>1?`${o} × `:""}${n.name}${n.options.length>0?` (${n.options.map(t=>t.value).join(", ")})`:""}`;return void 0===e.error?{...t,outcome:"added",message:e.warnings?.[0]?.message??`${r} is in your bag.`}:"refused"===e.error.code?{...t,outcome:"refused",message:e.error.message}:Te.has(e.error.code)?{...t,outcome:"unavailable",message:"The bag is not available on this site right now."}:{...t,outcome:"failed",message:e.error.message}}const Oe=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,$e=/^[*\-•]\s+(?<text>\S.*)$/u,Ne=/^\d+[).]\s+(?<text>\S.*)$/u,Le=/^#{1,6}\s+(?<text>\S.*)$/u,Ie=/^\s*(?:[*\-•]|\d+[).]|#{1,6})\s*$/u;const Be=new WeakMap;function Me(t,e){Be.get(t)!==e&&(Be.set(t,e),t.replaceChildren(),function(t,e){for(const[n,o]of e.split("**").entries())""!==o&&t.append(n%2==1?s("strong","",o):document.createTextNode(o))}(t,e))}function je(t,e){for(const[n,o]of e.entries()){let e=t.children.item(n);null===e&&(e=s("li"),t.append(e)),Me(e,o)}for(;t.children.length>e.length;)t.lastElementChild?.remove()}const Ue=new WeakMap;function Fe(t,e,n){const o=Ue.get(t)??s("span","cal-caret");Ue.set(t,o),o.setAttribute("aria-hidden","true"),o.remove();const r=function(t,e){const n=t.replaceAll(/\r\n?/gu,"\n").split("\n");!e&&Ie.test(n.at(-1)??"")&&n.pop();const o=[];let r,i;for(const t of n){const e=t.trim();if(""===e){r=void 0,i=void 0;continue}const n=Le.exec(e);if(n){o.push({tag:"h3",text:n.groups?.text??""}),r=void 0,i=void 0;continue}const s=$e.exec(e),a=s??Ne.exec(e);if(a){const t=s?"ul":"ol";i?.tag!==t&&(i={tag:t,items:[]},o.push(i)),i.items.push(a.groups?.text??""),r=void 0;continue}i&&/^\s/u.test(t)?i.items[i.items.length-1]+=` ${e}`:(i=void 0,r?r.text+=` ${e}`:(r={tag:"p",text:e},o.push(r)))}return o}(e,n);for(const[e,n]of r.entries()){let o=t.children.item(e);if(o?.tagName.toLowerCase()!==n.tag){const e=s(n.tag);null===o?t.append(e):o.replaceWith(e),o=e}"items"in n?je(o,n.items):Me(o,n.text)}for(;t.children.length>r.length;)t.lastElementChild?.remove();const i=t.lastElementChild;!n&&i&&(i.matches("ul, ol")?i.lastElementChild??i:i).append(o)}function De(t,e,n=!0,o=""){const r=s("div",`${e} cal-prose ${o}`.trim());return Fe(r,t,n),r}function Pe(t){return Array.isArray(t)?t:[]}function ze(t){return h(t)?t:{}}let We=0;function Ve(t){return We+=1,`cal-${t}-${We}`}function He(){return d("0 0 14 10","M8.537.808a.5.5 0 01.817-.162l4 4a.5.5 0 010 .708l-4 4a.5.5 0 11-.708-.708L11.793 5.5H1a.5.5 0 010-1h10.793L8.646 1.354a.5.5 0 01-.109-.546z","cal-icon cal-icon--arrow")}function Ke(){return d("0 0 10 6","M9.354.646a.5.5 0 00-.708 0L5 4.293 1.354.646a.5.5 0 00-.708.708l4 4a.5.5 0 00.708 0l4-4a.5.5 0 000-.708z","cal-icon cal-icon--caret")}function Je(t,e,n){return`${t} ${1===t?e:n}`}const Ye=["text","message","reply","answer","intro","body"],Ge=["What would you recommend?","Show me what is new","What are your best sellers?","Help me find a gift"];function Xe(t){return Pe(t.fields.images).length>1?1:0}function Ze(t,e,{index:n=0,widths:o,sizes:r,eager:i=!1,className:a=""}){const c=o[Math.floor(o.length/2)]??800,d=t.imageUrl(e,{index:n,width:c});if(""===d)return;const l=s("img",a);return l.srcset=o.map(o=>`${t.imageUrl(e,{index:n,width:o})} ${o}w`).join(", "),l.sizes=r,l.src=d,l.alt=y(e.fields.images?.[n]?.alt,e.fields.title),l.decoding="async",l.loading=i?"eager":"lazy",i&&(l.fetchPriority="high"),function(t){t.classList.add("cal-reveal");const e=()=>{t.classList.add("is-ready")};t.complete&&t.naturalWidth>0?e():(t.addEventListener("load",e,{once:!0}),t.addEventListener("error",e,{once:!0}))}(l),l}const Qe=[360,535,750,1070];function tn(t,e){const n="string"==typeof t?new Date(t):void 0;return!n||Number.isNaN(n.getTime())?"":function(t){let e=en.get(t);if(!e){try{e=new Intl.DateTimeFormat(t,{dateStyle:"medium"})}catch{e=new Intl.DateTimeFormat("en",{dateStyle:"medium"})}en.set(t,e)}return e}(e).format(n)}const en=new Map;function nn(t,e,n){const o=f(t),r=Ze(e,t,{widths:Qe,sizes:n}),i=s("article",`cal-entry cal-entry--${"collection"===o||"article"===o?o:"other"}${r?"":" cal-entry--text"}`);if(r){const t=s("div","cal-entry__media cal-media");t.append(r),i.append(t)}const a=s("div","cal-entry__body"),c=function(t,e){const{fields:n}=t;switch(f(t)){case"collection":{const t=n["shopify-productsCount"];return"number"==typeof t&&t>0?Je(t,"product","products"):""}case"article":return[tn(n["shopify-publishedAt"],e.settings.language),y(n["shopify-author"])].filter(t=>""!==t).join(" · ");default:return""}}(t,e);""!==c&&a.append(s("p","cal-entry__meta",c));const d=y(t.fields.title,t.fields["shopify-handle"].replaceAll("-"," ")),l=s("h3","cal-entry__title"),u=e.url(t);if(""===u)l.textContent=d;else{const t=s("a","cal-entry__link",d);t.href=u,l.append(t)}a.append(l);const h=y(t.fields.descriptionText);return""===h||"collection"===o&&r||a.append(s("p","cal-entry__text",h)),i.append(a),i}function on(t,e,n){const o=s("ul",`cal-entries cal-entries--${n}`);o.setAttribute("role","list");const r=4===n?"(min-width: 990px) 25vw, (min-width: 750px) 33vw, 50vw":"(min-width: 750px) 33vw, 100vw";for(const n of t){const t=s("li","cal-entries__item");t.append(nn(n,e,r)),o.append(t)}return o}const rn=new WeakMap;function sn(t,e){const n=JSON.stringify(ze(t.data),(t,e)=>{const n=h(e)&&h(e.fields)?e.fields["shopify-handle"]:void 0;return"string"==typeof n?n:e});return`${e.chapter.isFirst?1:0}|${e.chapter.question}|${n}`}function an(t,e){return{type:t,render(t,n){const o=e(ze(t.data),n,t);return o&&rn.set(o,sn(t,n)),o},update:(t,e,n)=>rn.get(t)===sn(e,n)}}function cn(t){const{classes:e}=t;function n(t,e="section"){return s(e,`cal-section cal-${t}`)}function o(...t){const n=s("div",`${e.pageWidth} cal-section__inner`);return n.append(...t.filter(t=>void 0!==t)),n}function r(t){return s("p","cal-eyebrow",t)}function i(t,e,n){const o=s("div","cal-head"),r=s("h2","cal-title",e);return r.id=Ve("title"),t.setAttribute("aria-labelledby",r.id),o.append(r),void 0!==n&&o.append(s("p","cal-head__meta",n)),o}function c(t,n,o=""){const r=s("button",`${e.buttonSecondary} cal-chip ${o}`.trim());return r.type="button",r.dataset.callimacusAsk=n,n!==t&&(r.title=n),r.append(s("span","cal-chip__label",t),He()),r}function d(t){const e=s("ul","cal-chips");e.setAttribute("role","list");for(const n of t){const t=s("li");t.append(c(n.label,n.question)),e.append(t)}return e}function l(t,e,n){const o=s("a",n);o.href=e.url(t);const r=y(t.fields.title);return o.append(s("span","",""===r?"Shop now":`Shop ${r}`),He()),o}function u(t,e){const n=y(e).replace(/^Show me .+? — /u,"");if(""===n)return`Show me ${t}`;return`Show me ${t} — ${/^(?:I\b|I'|[A-Z]{2})/u.test(n)?n:n.charAt(0).toLowerCase()+n.slice(1)}`}function h(r,i,s,a=!0){if(""===r&&0===i.length)return;const c=n("note"),d=o();""!==r&&d.append(De(r,e.rte,a,"cal-prose--note"));const l=i.filter(t=>"product"!==f(t)),u=[t.cards(i.filter(t=>"product"===f(t)),s),l.length>0?on(l,s,3):void 0];return d.append(...u.filter(t=>void 0!==t)),c.append(d),c}function p(t,e,n,o){return Ye.map(e=>y(t[e])).find(t=>""!==t)??(e.length>0?"":n.text(o))}function m(t,e){const n=y(ze(t.data).text,e.text(t));return 0===e.chapter.blocks.filter(e=>e.id!==t.id).length&&!e.chapter.addedToCart||/solomei\.ai/iu.test(n)?{kind:"redirect",text:n}:{kind:""!==n&&e.final?"note":"wait",text:n}}function g(t){const e=n("redirect"),r=s("p","cal-redirect__text",`I can help with questions about what ${t.settings.storeName} sells.`),i=(t.settings.starters.length>0?t.settings.starters.slice(0,4):Ge).map(t=>({label:t,question:t}));return e.append(o(r,d(i))),e}const b=[(v="custom:storefrontReply",w=(t,e,n)=>y(t.text,e.text(n)),k=(t,r)=>{const i=n("answer"),a=s("div","cal-answer__body");return a.append(De(t,e.rte,r.final,"cal-prose--answer")),i.append(o(a)),i},{type:v,render(t,e){const n=w(ze(t.data),e,t);return""===n?void 0:k(n,e)},update(t,e,n){const o=t instanceof Element?t.querySelector(".cal-prose"):void 0,r=w(ze(e.data),n,e);return!(!o||""===r||(Fe(o,r,n.final),0))}}),an("custom:editorialHero",(t,i)=>{const a=ze(t.copy),c={eyebrow:y(a.eyebrow),headline:y(a.headline),dek:y(a.dek)},d=i.hits(t.lead).at(0),{isFirst:u}=i.chapter,h=d?Ze(i,d,{index:Xe(d),widths:u?[750,1100,1500,1800,2400]:[200,320,480],sizes:u?"100vw":"(min-width: 750px) 160px, 96px",eager:u}):void 0;if(h||""!==c.eyebrow||""!==c.headline||""!==c.dek)return u?function(t,o,i,a){const c=n("hero");c.classList.add("cal-hero--lead");const d=s("div","cal-hero__banner "+(i?"cal-hero__banner--image":"cal-hero__banner--text"));if(i){const t=s("div","cal-hero__media cal-media");t.append(i),d.append(t)}if(""!==t.eyebrow||""!==t.headline||""!==t.dek){const n=s("div",`cal-hero__content ${e.pageWidth}`),i=s("div","cal-hero__box");if(""!==t.eyebrow&&i.append(r(t.eyebrow)),""!==t.headline&&i.append(s("h2","cal-display cal-hero__headline",t.headline)),""!==t.dek&&i.append(s("p","cal-hero__dek",t.dek)),o){const t=s("div","cal-hero__buttons");t.append(l(o,a,`${e.buttonPrimary} cal-hero__cta`)),i.append(t)}n.append(i),d.append(n)}return c.append(d),c}(c,d,h,i):function(t,i,a,c){const d=n("hero");d.classList.add("cal-hero--compact");const u=s("div","cal-hero__row");if(a&&i){const t=s("a","cal-hero__thumb cal-media");t.href=c.url(i),t.tabIndex=-1,t.setAttribute("aria-hidden","true"),t.append(a),u.append(t)}const h=s("div","cal-hero__text");return""!==t.eyebrow&&h.append(r(t.eyebrow)),""!==t.headline&&h.append(s("h2","cal-title cal-hero__headline",t.headline)),""!==t.dek&&h.append(s("p","cal-hero__dek",t.dek)),i&&h.append(l(i,c,`${e.link} cal-link`)),u.append(h),d.append(o(u)),d}(c,d,h,i)}),an("custom:storefrontPicks",(e,r,s)=>{const a=r.hits(e.picks);return function(e,r,s){if(0===r.length)return;const a=n("picks"),c=i(a,e,Je(r.length,"product","products"));return a.append(o(c,t.cards(r,s))),a}("Picked for you",a.length>0?a:r.picks(s),r)}),an("custom:pageAnswer",(t,i)=>{const a=Pe(t.pages).filter(t=>S(t)).map(t=>({title:y(t.meta?.title,t.name),kind:t.meta?.shopifyKind,text:A(t),url:i.url(t)})).filter(t=>""!==t.title&&t.text.length>0&&""!==t.url).slice(0,2);if(0===a.length)return;const c=n("pages"),d=s("div","cal-pages__list");return d.append(...a.map(t=>function(t,n){const o=s("article","cal-page"),i=s("h2","cal-subtitle cal-page__title",t.title);i.id=Ve("title"),o.setAttribute("aria-labelledby",i.id);const a=s("a",`${e.link} cal-link cal-page__link`);return a.href=t.url,a.append(s("span","","Read the full "+("policy"===t.kind?"policy":"page")),s("span",e.visuallyHidden,`: ${t.title}`),He()),o.append(r("policy"===t.kind?"Store policy":`From ${n.settings.storeName}`),i,De(t.text.join("\n\n"),e.rte,!0,"cal-page__text"),a),o}(t,i))),c.append(o(d)),c}),an("custom:collectionGrid",(t,e)=>{const r=e.hits(t.collections).filter(t=>"collection"===f(t)&&0!==t.fields["shopify-productsCount"]);if(0===r.length)return;const s=n("collections"),a=i(s,"Shop by collection",Je(r.length,"collection","collections"));return s.append(o(a,on(r,e,4))),s}),an("custom:storyCards",(t,e)=>{const r=e.hits(t.stories).filter(t=>"article"===f(t));if(0===r.length)return;const s=n("stories"),a=i(s,"From the journal",Je(r.length,"story","stories"));return s.append(o(a,on(r,e,3))),s}),an("custom:problemGuide",(t,r)=>{const a=ze(t.guide),d=Pe(a.steps).map(t=>ze(t)).map(t=>({title:y(t.title),body:y(t.body),shopFor:y(t.shopFor)})).filter(t=>""!==t.title||""!==t.body);if(0===d.length)return;const l=n("guide"),h=s("ol",`cal-steps cal-steps--${Math.min(d.length,4)}`);h.setAttribute("role","list");for(const[t,n]of d.entries()){const o=s("li","cal-step"),i=s("div","cal-step__card"),a=s("span","cal-step__index",String(t+1).padStart(2,"0"));a.setAttribute("aria-hidden","true");const d=s("div","cal-step__info");""!==n.title&&d.append(s("h3","cal-step__title",n.title)),""!==n.body&&d.append(De(n.body,e.rte,!0,"cal-step__body")),""!==n.shopFor&&d.append(c(`Shop ${n.shopFor}`,u(n.shopFor,r.chapter.question),"cal-chip--compact cal-step__shop")),i.append(a,d),o.append(i),h.append(o)}const p=i(l,y(a.title,"Step by step"),Je(d.length,"step","steps"));return l.append(o(p,h)),l}),an("custom:materialStory",(i,a)=>{const c=ze(i.story),d=y(c.material),l=y(c.headline),u=y(c.body),h=Pe(c.facts).map(t=>y(t)).filter(t=>""!==t),p=a.hits(i.products).slice(0,3);if(""===l&&""===u&&0===h.length&&0===p.length)return;const f=n("material"),m=p.at(0),g=m?Ze(a,m,{index:Xe(m),widths:[535,750,1070,1500],sizes:"(min-width: 1600px) 750px, (min-width: 750px) calc((100vw - 130px) / 2), calc(100vw - 30px)"}):void 0;if(""!==l||""!==u||""!==d||h.length>0){const t=s("div","cal-material__feature"+(g?"":" cal-material__feature--text"));if(g){const e=s("div","cal-material__media cal-media");e.append(g),t.append(e)}const n=s("div","cal-material__content");if(""!==d&&n.append(r(d)),""!==l){const t=s("h2","cal-title cal-material__heading",l);t.id=Ve("title"),f.setAttribute("aria-labelledby",t.id),n.append(t)}if(""!==u&&n.append(De(u,e.rte,!0,"cal-material__body")),h.length>0){const t=s("ul","cal-facts");t.setAttribute("role","list");for(const e of h)t.append(s("li","cal-facts__item",e));n.append(t)}t.append(n),f.append(o(t))}if(p.length>0){const e=s("div","cal-material__products");e.append(s("h3","cal-subtitle",""===d?"Shop the story":`Made with ${d}`));const n=t.cards(p,a,{columns:3});n&&e.append(n),f.append(o(e))}return f}),an("custom:sizeCare",t=>{const i=Pe(t.faq).map(t=>ze(t)).map(t=>({question:y(t.question),answer:y(t.answer)})).filter(t=>""!==t.question&&""!==t.answer);if(0===i.length)return;const a=n("faq"),c=s("div","cal-faq__layout"),d=s("div","cal-faq__header"),l=s("h2","cal-title","Good to know");l.id=Ve("title"),a.setAttribute("aria-labelledby",l.id),d.append(r("Sizes and care"),l);const u=s("div","cal-faq__list");for(const[t,n]of i.entries()){const o=Ve("faq"),r=s("div","cal-faq__item"),i=s("details");i.open=0===t;const a=s("summary","cal-faq__summary");a.id=`${o}-summary`,a.append(s("h3","cal-faq__question",n.question),Ke());const c=s("div","cal-faq__answer");c.id=`${o}-content`,c.setAttribute("role","region"),c.setAttribute("aria-labelledby",a.id),c.append(De(n.answer,e.rte)),i.append(a,c),r.append(i),u.append(r)}return c.append(d,u),a.append(o(c)),a}),an("custom:compareSet",(i,a)=>{const c=ze(i.pair),d=ze(i.verdict),l=a.hits(i.first).at(0),u=a.hits(i.second).at(0),h=Pe(d.rows).map(t=>ze(t)).map(t=>({aspect:y(t.aspect),first:y(t.first),second:y(t.second)})).filter(t=>""!==t.aspect),p=y(d.summary);if(!l&&!u&&""===p&&0===h.length)return;const f=y(l?.fields.title,c.first,"The first"),m=y(u?.fields.title,c.second,"The second"),g=n("compare");l||u||g.classList.add("cal-compare--text");const b=s("div","cal-compare__layout"),v=s("div","cal-compare__intro"),w=s("h2","cal-title",`${f} or ${m}?`);w.id=Ve("title"),g.setAttribute("aria-labelledby",w.id),v.append(r("Side by side"),w),""!==p&&v.append(De(p,e.rte,!0,"cal-compare__summary")),b.append(v);for(const[e,n]of[l,u].entries()){const o=s("div","cal-compare__card cal-compare__card--"+(0===e?"first":"second")),r=n?t.card(n,a):void 0;r&&o.append(r),b.append(o)}return h.length>0&&b.append(function(t,n,o){const r=s("div","cal-compare__table");r.setAttribute("role","table"),r.setAttribute("aria-label",`${t} compared with ${n}`);const i=s("div","cal-compare__row cal-compare__row--head");i.setAttribute("role","row");const a=s("span","cal-compare__aspect");a.setAttribute("role","columnheader"),a.append(s("span",e.visuallyHidden,"Aspect")),i.append(a);for(const e of[t,n]){const t=s("span","cal-compare__value",e);t.setAttribute("role","columnheader"),i.append(t)}r.append(i);for(const t of o){const e=s("div","cal-compare__row");e.setAttribute("role","row");const n=s("span","cal-compare__aspect",t.aspect);n.setAttribute("role","rowheader"),e.append(n);for(const n of[t.first,t.second]){const t=s("span","cal-compare__value",n);t.setAttribute("role","cell"),e.append(t)}r.append(e)}return r}(f,m,h)),g.append(o(b)),g}),an("custom:completeSet",(e,r)=>{const a=Pe(e.companions).map(t=>ze(t)).map(t=>({why:y(t.why),hit:r.hits(t.product).at(0)})).filter(t=>void 0!==t.hit).slice(0,3);if(0===a.length)return;const c=n("set"),d=s("div",`cal-set__collage cal-set__collage--${a.length}`);for(const[e,n]of a.entries()){const o=s("div","cal-set__item cal-set__item--"+(0===e?"lead":"side")),i=s("figure","cal-set__piece"),a=t.card(n.hit,r,0===e?{sizes:"(min-width: 1600px) 780px, (min-width: 750px) calc((100vw - 130px) / 2), calc(100vw - 30px)"}:{});a&&i.append(a),""!==n.why&&i.append(s("figcaption","cal-set__why",n.why)),o.append(i),d.append(o)}return c.append(o(i(c,"Complete the set"),d)),c}),an("custom:followUps",t=>{const e=Pe(t.next).map(t=>ze(t)).map(t=>({label:y(t.label,t.question),question:y(t.question,t.label)})).filter(t=>""!==t.question);if(0===e.length)return;const r=n("next","nav"),i=s("h2","cal-eyebrow cal-next__title","Keep exploring");return i.id=Ve("title"),r.setAttribute("aria-labelledby",i.id),r.append(o(i,d(e))),r}),an("custom:addToCartResult",(t,r,i)=>{const c=function(t){if(!_e(t.data)||!_e(t.data.addToCart))return;const e=t.data.addToCart;return"error"===e.status?{status:"error"}:"resolved"===e.status&&xe(e.variantId)&&xe(e.productName)&&xe(e.size)?{status:"resolved",variantId:e.variantId,productName:e.productName,size:e.size}:"size_selection_needed"===e.status&&xe(e.productSku)&&xe(e.productName)&&Array.isArray(e.availableSizes)&&e.availableSizes.every(Ce)?{status:"size_selection_needed",productSku:e.productSku,productName:e.productName,availableSizes:e.availableSizes}:void 0}(i);if("size_selection_needed"!==c?.status||0===c.availableSizes.length)return;const d=n("choice"),l=s("h2","cal-eyebrow cal-choice__title",c.productName);l.id=Ve("title"),d.setAttribute("aria-labelledby",l.id);const u=s("div","cal-choice__options");u.setAttribute("role","group"),u.setAttribute("aria-labelledby",l.id);const h=s("div","cal-choice__status"),p={isOn:!1};for(const t of c.availableSizes){const n=s("button",`${e.buttonSecondary} cal-choice__option`);n.type="button",n.append(s("span","cal-choice__label",t.size));const o=async()=>{if(p.isOn)return;p.isOn=!0,n.setAttribute("aria-disabled","true");const e=await U(async()=>r.addToCart(t.variantId)),o={id:c.productSku,name:c.productName,options:[{name:"option",value:t.size}]},i=qe({id:r.chapter.id??"",item:o,quantity:1},e);n.dataset.outcome=i.outcome,h.replaceChildren(a(i)),n.removeAttribute("aria-disabled"),p.isOn=!1};t.orderable?n.addEventListener("click",()=>{o()}):(n.disabled=!0,n.append(s("span","cal-choice__sold-out","Sold out"))),u.append(n)}return d.append(o(l,u,h)),d}),{type:"*",render(t,e){const n=e.picks(t);return h(p(ze(t.data),n,e,t),n,e,e.final)},update(t,e,n){const o=t instanceof Element?t.querySelector(".cal-prose"):void 0,r=n.picks(e),i=p(ze(e.data),r,n,e);return!(!o||""===i||r.length>0)&&(Fe(o,i,n.final),!0)}}];var v,w,k;for(const t of["demosthenesResponse","custom:demosthenesResponse"])b.push({type:t,render(t,e){const n=m(t,e);return"redirect"===n.kind?g(e):"wait"===n.kind?void 0:h(n.text,[],e)},update(t,e,n){const o=m(e,n);if("redirect"===o.kind)return t instanceof Element&&t.classList.contains("cal-redirect");const r=t instanceof Element?t.querySelector(".cal-prose"):void 0;return!(!r||"note"!==o.kind)&&(Fe(r,o.text,!0),!0)}});return b}const dn="callimacus.cards",ln=["_pos","_sid","_ss","_psq","_fid"],un=new Set(["TABLE","THEAD","TBODY","TFOOT","TR","TD","TH"]);function hn(t){if(null!==t)try{const e=/\/products\/(?<handle>[^#/?]+)/u.exec(new URL(t,globalThis.location.origin).pathname);return void 0===e?.groups?.handle?void 0:decodeURIComponent(e.groups.handle)}catch{return}}function pn(t,e){return[...t.querySelectorAll('a[href*="/products/"]')].some(t=>{const n=hn(t.getAttribute("href"));return void 0!==n&&n!==e})}function fn(){const t=o("sessionStorage",dn),n={searches:0,sectionId:void 0,borrowed:0,missed:[],styles:0,scripts:[],verdict:"fits"===t||"fails"===t?t:"unknown",why:void 0===t?"":"decided on an earlier page of this tab"},i=new Set;return{stats:n,source:function(t,e){const o=""===t.title?t.handle.replaceAll("-"," "):t.title,r=new URLSearchParams({type:"product",q:o,"options[prefix]":"last"});return void 0!==n.sectionId&&r.set("section_id",n.sectionId),n.searches+=1,`${e}search?${r.toString()}`},extract:function(t,o){const r=document.createElement("template");r.innerHTML=t;const s=function(t,e){const n=[...(t.querySelector("main")??t).querySelectorAll('a[href*="/products/"]')].filter(t=>hn(t.getAttribute("href"))===e&&!t.closest('cart-drawer, cart-drawer-component, cart-notification, cart-items, [id^="CartDrawer"], [id^="cart-notification"], [class*="cart-drawer"], .cart-item'));for(const t of n){let n=t;for(;n.parentElement&&!n.parentElement.matches('main, body, .shopify-section, ul, ol, [role="list"], form, section, slider-component, .grid, [class*="product-grid"]')&&!pn(n.parentElement,e)&&!n.parentElement.querySelector("h1");)n=n.parentElement;if("LI"===n.tagName&&1===n.childElementCount&&n.firstElementChild&&(n=n.firstElementChild),!un.has(n.tagName)&&!n.closest("table")&&n.querySelector("img, picture, svg")&&(n!==t||""!==n.textContent.trim()))return n}}(r.content,o.handle);if(!s)return void n.missed.push({handle:o.handle,why:"not in the search results"});const a=s.closest('[id^="shopify-section-"]');a&&void 0===n.sectionId&&(n.sectionId=a.id.slice(16),e.info(`borrowing cards from the search section ${n.sectionId}`)),a&&function(t){for(const e of t.querySelectorAll("style")){const t=e.textContent;if(i.has(t))continue;i.add(t);const o=document.createElement("style");o.dataset.callimacusBorrowed="",o.textContent=t,document.head.append(o),n.styles+=1}const e=new Set([...document.querySelectorAll('link[rel="stylesheet"], script[src]')].map(t=>(t.getAttribute("href")??t.getAttribute("src")??"").split("?",1)[0]));for(const o of t.querySelectorAll('link[rel="stylesheet"]')){const t=o.getAttribute("href")??"",r=t.split("?",1)[0]??t;""===t||e.has(r)||i.has(r)||(i.add(r),document.head.append(o.cloneNode(!0)),n.styles+=1)}for(const o of t.querySelectorAll("script[src]")){const t=o.getAttribute("src")??"",r=t.split("?",1)[0]??t;if(""===t||e.has(r)||i.has(r))continue;i.add(r);const s=document.createElement("script");s.src=t,s.defer=!0,document.head.append(s),n.scripts.push(r.split("/").pop()??r)}}(a);const c=document.createElement("template");return c.content.append(s),n.borrowed+=1,c},prepare:function(t){!function(t){for(const e of t.querySelectorAll("a[href]")){const t=e.getAttribute("href")??"";try{const n=new URL(t,globalThis.location.origin);if(ln.some(t=>n.searchParams.has(t))){for(const t of ln)n.searchParams.delete(t);const o=n.origin===globalThis.location.origin&&!/^https?:/iu.test(t);e.setAttribute("href",o?`${n.pathname}${n.search}${n.hash}`:n.href)}}catch{}}}(t);for(const e of t.querySelectorAll('dialog, [role="dialog"], quick-add-modal, [class*="modal"][id]')){const t=""===e.id?void 0:document.querySelector(`#${CSS.escape(e.id)}`);t&&t!==e?e.remove():t||document.body.append(e)}},check:function(t){if("unknown"!==n.verdict)return n.verdict;const o=function(t){const e=t.getBoundingClientRect();if(e.width<40||e.height<40)return;const n=t.querySelector("img, picture, svg"),o=n?.getBoundingClientRect();if(!n||!o||0===o.height)return;const r=[...t.querySelectorAll('a[href*="/products/"], h2, h3, h4, p, [class*="title"], [class*="price"]')].filter(t=>!t.contains(n)&&!n.contains(t)&&""!==t.textContent.trim()).map(t=>t.getBoundingClientRect()).find(t=>t.height>=8&&t.width>=8&&!(t.top<=o.top&&t.bottom>=o.bottom));return r?e.height<e.width?{fits:!1,why:`the card is wider than it is tall (${Math.round(e.width)} by ${Math.round(e.height)} px): a list row`}:o.bottom>r.top+4?{fits:!1,why:"the card's text sits beside its picture, not under it"}:{fits:!0,why:"a picture above its text, taller than wide"}:{fits:!1,why:"the card has no text beside its picture"}}(t);return o&&(n.verdict=o.fits?"fits":"fails",n.why=o.why,r("sessionStorage",dn,n.verdict),e.info(`the theme's cards ${o.fits?"fit":"do not fit"}: ${o.why}`)),n.verdict}}}const mn=[240,360,480,640,840,1080],gn={add:"Add to cart",added:"Added",choose:"Choose options",soldOut:"Sold out",failed:"Could not add. Try again"},yn=Object.freeze({pageWidth:"cal-page-width",buttonPrimary:"cal-button",buttonSecondary:"cal-button cal-button--secondary",link:"cal-link",rte:"cal-rte",visuallyHidden:"cal-visually-hidden",grid:t=>`cal-egrid cal-egrid--${t}`,gridItem:"cal-egrid__item"});function bn(){const t=document.querySelector("cart-notification, cart-drawer");return"function"==typeof t?.getSectionsToRender?"dawn":document.querySelector("cart-items-component, cart-drawer-component, cart-icon")?"horizon":"plain"}function vn(t){return[...t.querySelectorAll('a[href$="/cart"], a[href*="/cart?"], a[href$="/cart/"]')].filter(t=>!v(t))}let wn;async function kn(t,n,o,r){const{json:i,failure:a}=await F(o,{headers:{"content-type":"application/json",accept:"application/json","x-requested-with":"XMLHttpRequest"},body:JSON.stringify({items:[{id:Number(t),quantity:n}]})});if(a)throw a;const c=Array.isArray(i.items)&&h(i.items[0])?i.items[0]:{};!function(t,e){document.querySelector(".cal-toast")?.remove(),clearTimeout(wn);const n=s("div","cal-toast");n.setAttribute("role","status"),n.dataset.callimacusUi="",n.append(s("p","cal-toast__text",""===t?"Added to your cart":`Added to your cart: ${t}`));const o=s("a","cal-button cal-toast__action","View cart");o.href=`${q({settings:e})}cart`,n.append(o),document.body.append(n),wn=setTimeout(()=>{n.remove()},5e3)}(y(c.product_title,c.title),o),document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i}));const d=await async function(){const t=vn(document),n=t.at(0);if(void 0===n)return!1;const o=n.closest('[id^="shopify-section-"]')?.id.slice(16)??"";let r="";try{if(""!==o){const t=new URL(globalThis.location.href);t.search=`sections=${encodeURIComponent(o)}`;const e=await fetch(t,{headers:{accept:"application/json"}}),n=await e.json();r=h(n)&&"string"==typeof n[o]?n[o]:""}if(""===r){const t=await fetch(globalThis.location.href,{headers:{accept:"text/html"}});r=await t.text()}}catch(t){return e.warn("could not redraw the cart icon",t),!1}const i=vn((new DOMParser).parseFromString(r,"text/html"));let s=0;for(const[e,n]of t.entries()){const t=(""===n.id?void 0:i.find(t=>t.id===n.id))??i.at(e);void 0!==t&&t.innerHTML!==n.innerHTML&&(n.innerHTML=t.innerHTML,s+=1)}return s>0}();return r.cart[d?"iconRedrawn":"iconMissed"]+=1,{...c,handle:y(c.handle)}}function Sn(t,e){const n=s("div","cal-ecard"),o=s("div","cal-ecard__media"),r=s("div","cal-ecard__info"),i=s("a","cal-ecard__title",t);return i.href=e,r.append(i),n.append(o,r),{root:n,info:r,title:i,media:o}}function An(t,e){const n=s("div","cal-ecard__quick-add cal-card__quick-add");return n.append($(t,e,{className:"cal-button cal-button--secondary cal-ecard__add",labels:gn})),n}function _n(t,e,n={}){const{hit:o}=t,r=e.url(o),i=Sn(t.title,r),a=Ze(e,o,{widths:mn,sizes:n.sizes??"(min-width: 990px) calc((100vw - 160px) / 4), (min-width: 750px) calc((100vw - 120px) / 3), calc((100vw - 40px) / 2)"});if(a){const t=s("a","cal-ecard__image");t.href=r,t.tabIndex=-1,t.setAttribute("aria-hidden","true"),t.append(a),i.media.append(t)}return i.info.append(s("p","cal-ecard__price"+(T(o)?" cal-ecard__price--sold-out":""),function(t,e){const{fields:n}=t,o=h(n.priceRange)?n.priceRange:{},r=Number(o.min),i=Number(o.max);if(Number.isFinite(r)&&Number.isFinite(i)&&r<i){const t=y(o.currency,"object"==typeof n.price?n.price.currency:"");return`From ${e.money(""===t?r:{amount:r,currency:t})}`}return void 0===n.price?"":e.money(n.price)}(o,e))),!1===n.quickAdd||T(o)||i.info.append(An(t,e)),i.root}function xn(t,e){const n=Sn("",`${q(e)}products/${encodeURIComponent(t.handle)}`);return n.root.classList.add("cal-card__skeleton"),n.title.append(s("span","cal-card__line")),n.title.setAttribute("aria-label",""===t.title?"Loading product":t.title),n.root}function Cn(t,e){t.classList.remove("cal-card__skeleton");const n=t.querySelector(":scope .cal-ecard__title");n&&(n.removeAttribute("aria-label"),n.textContent=""===e.title?e.handle.replaceAll("-"," "):e.title)}function En(){const t=new Map;async function e(e,n){let o=t.get(e);return o||(o=fetch(`${q(n)}products/${encodeURIComponent(e)}.js`,{headers:{accept:"application/json"}}).then(async t=>t.ok?t.json():void 0).then(t=>h(t)?function(t){const e=y(t.handle);if(""===e)return;const n=Array.isArray(t.variants)?t.variants.filter(t=>h(t)):[],o=Array.isArray(t.images)?t.images.filter(t=>"string"==typeof t):[],r=t=>Number(t)/100;return{fields:{"shopify-handle":e,title:y(t.title),price:r(t.price),priceRange:{min:r(t.price_min),max:r(t.price_max)},images:o.map(t=>({url:t.startsWith("//")?`https:${t}`:t})),variantTree:{variants:n.map(t=>({id:t.id,orderable:!0===t.available,online:!0}))}}}}(t):void 0).catch(()=>{}),t.set(e,o)),o}function n({host:t,ref:n,ctx:o,options:r}){if(n.hit){const i=_n({...n,hit:n.hit},o,r);return t.replaceChildren(i),void(0===(n.hit.fields.images??[]).length&&e(n.handle,o).then(t=>{if(!t||!i.isConnected)return;const e={...t,fields:{...t.fields,...n.hit?.fields,images:t.fields.images}};i.replaceWith(_n({...n,hit:e},o,r))}))}const i=xn(n,o);t.replaceChildren(i),t.classList.add("cal-card--pending"),e(n.handle,o).then(e=>{t.classList.remove("cal-card--pending"),e?i.replaceWith(_n({handle:n.handle,hit:e,title:y(n.title,e.fields.title)},o,r)):Cn(i,n)})}return{card:function(t,e,o={}){const r=N(t);if(!r)return;const i=s("div","cal-card");return i.dataset.handle=r.handle,n({host:i,ref:r,ctx:e,options:o}),i},draw:n}}function Rn(t){const n=En(),o=fn(),r={cart:{kind:void 0,adds:0,iconRedrawn:0,iconMissed:0},addedButtons:0,borrow:o.stats},i=new Set,a=L(o.source,{extract:o.extract,prepare:o.prepare,placeholder:_n,skeleton:xn,offline:Cn});let c=!1;const d=t=>!t.classList.contains("cal-card--pending")&&null!==t.firstElementChild&&!t.firstElementChild.classList.contains("cal-ecard");function l(t){const e=t.host.firstElementChild;if(null===e||!d(t.host))return;if("fails"===o.check(e))return void function(){for(const t of i)t.host.isConnected?d(t.host)&&(n.draw(t),i.delete(t)):i.delete(t)}();if(function({host:t,ref:e,ctx:n,options:o}){const i=t.firstElementChild;null!==i?.querySelector('button[name="add"], form[action*="/cart/add"], modal-opener, [data-quick-add], quick-add-component, .quick-add, product-form-component')||null!==t.querySelector(":scope > .cal-ecard__quick-add")||null===i||!1===o.quickAdd||!e.hit||T(e.hit)||(t.append(An({...e,hit:e.hit},n)),r.addedButtons+=1)}(t),"unknown"!==o.stats.verdict)return;const s=()=>{l(t)};if(e.querySelector("img")?.addEventListener("load",s,{once:!0}),"function"!=typeof IntersectionObserver)return;const a=new IntersectionObserver(t=>{t.every(t=>!t.isIntersecting)||(a.disconnect(),s())});a.observe(t.host)}function u(e,r,s={}){if("auto"!==t||"fails"===o.stats.verdict)return n.card(e,r,s);!function(){if(c)return;c=!0;const t=B();t&&"function"==typeof I.subscribe&&I.subscribe(t.cartUpdate,t=>{const e=h(t)?t:{};"product-form"===e.source&&a.rememberAdded(e.productVariantId)}),document.addEventListener(P,t=>{const{detail:e}=t,n=h(e)&&h(e.data)?e.data:{};h(e)&&"product-form-component"===n.source&&!0!==n.didError&&a.rememberAdded(e.sourceId)})}();const u=a.card(e,r,s),p=N(e);if(!u||!p)return u;const f={host:u,ref:p,ctx:r,options:s};if(i.add(f),d(u))queueMicrotask(()=>{l(f)});else{const t=new MutationObserver(()=>{u.classList.contains("cal-card--pending")||(t.disconnect(),l(f))});t.observe(u,{childList:!0,attributes:!0,attributeFilter:["class"]})}return u}return Object.freeze({classes:yn,card:u,cards:(t,e,n={})=>function(t,e){if(0===t.length)return;const n=[2,3,4,5].includes(e.columns??4)?e.columns??4:4,o=s("ul",`${yn.grid(n)} cal-grid`);o.setAttribute("role","list");for(const e of t){const t=s("li",yn.gridItem);t.append(e),o.append(t)}return o}(function(t,e){return(Array.isArray(t)?t:[]).map(t=>e(t)).filter(t=>void 0!==t)}(t,t=>u(t,e,n)),n),addToCart:async function(t,n,o){const i=bn();let s;return r.cart.kind=i,s="dawn"===i?await async function(t,n,o){const r=document.querySelector("cart-notification")??document.querySelector("cart-drawer")??void 0,i=new FormData;i.append("id",t),i.append("quantity",String(n)),"function"==typeof r?.getSectionsToRender&&(i.append("sections",r.getSectionsToRender().map(t=>t.id).join(",")),i.append("sections_url",globalThis.location.pathname),r.setActiveElement?.(document.activeElement));const{json:s,failure:a}=await F(o,{headers:M,body:i}),c=B();if(a)throw c&&"function"==typeof I.publish&&I.publish(c.cartError,{source:"callimacus",productVariantId:t,errors:s.description,message:s.message}),a;if(c&&"function"==typeof I.publish&&I.publish(c.cartUpdate,{source:"callimacus",productVariantId:t}),"function"==typeof r?.renderContents&&void 0!==s.sections)try{return r.renderContents(s),r.classList.remove("is-empty"),s}catch(t){e.error("the cart could not redraw itself after adding",t)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:s})),s}(t,n,o):"horizon"===i?await W(t,n,o):await kn(t,n,o,r),r.cart.adds+=1,s},install(){"dawn"===bn()&&"function"!=typeof I.getCurrentSellingPlanId&&(I.getCurrentSellingPlanId=()=>"")},stats:r})}const Tn=["header details-modal summary",'header [class*="search"] summary','header a[href$="/search"]','header a[href*="/search?"]','header button[aria-label*="earch" i]','header summary[aria-label*="earch" i]','header [class*="search-toggle"]',"header search-button button",'header [class*="search"] button','[class*="header"] a[href$="/search"]','[class*="header"] [class*="search-toggle"]','[class*="header"] button[aria-label*="earch" i]'],qn=['header a[href$="/cart"]','[class*="header"] a[href$="/cart"]'],On=/search|js-|drawer|modal|toggle|open|trigger|active/iu,$n="http://www.w3.org/2000/svg";function Nn(t){const e=t.getBoundingClientRect();return e.width>0&&e.height>0}function Ln(t){for(const e of t){const t=[...document.querySelectorAll(e)].find(t=>Nn(t)&&!t.closest("[data-callimacus-ui]"));if(t)return{node:t,selector:e}}}function In(t){const e=Ln(Tn)??Ln(qn);if(!e)return{placed:!1,how:"no search or cart control found in the header"};const n=e.node,o=s("button","cal-header-ask");o.type="button",o.dataset.callimacusOpen="",o.dataset.callimacusUi="",o.setAttribute("aria-label",t);for(const t of n.classList)On.test(t)||o.classList.add(t);const r=Math.round(n.querySelector("svg")?.getBoundingClientRect().width??0);return o.append(function(t){const e=document.createElementNS($n,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width",String(t)),e.setAttribute("height",String(t)),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");const n=document.createElementNS($n,"path");return n.setAttribute("d","M12 3.5l1.6 4.4 4.4 1.6-4.4 1.6L12 15.5l-1.6-4.4L6 9.5l4.4-1.6zM18.5 14l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.4"),n.setAttribute("stroke-linejoin","round"),e.append(n),e}(r>0?r:20)),function(t){let e=t.closest("details-modal, details")??t;for(e.parentElement?.matches("details-modal")&&(e=e.parentElement);1===e.parentElement?.childElementCount&&!e.parentElement.matches('header, nav, [class*="icons"], [class*="actions"]');)e=e.parentElement;return e}(n).before(o),{placed:!0,how:`before ${e.selector}`}}function Bn({template:t,searchTerms:e,assistantLabel:n,entrance:o}){const r=s("div","cal-stage");r.dataset.callimacusUi="";const i=s("div");if(i.dataset.callimacusStage="",i.dataset.stageKind="index"===t?"home":"search"===t?"search":"page","search"===t&&""!==e){const t=s("div","cal-stage__intro cal-page-width");t.append(s("p","cal-stage__lede",`Answering “${e}”`)),r.append(t),i.dataset.askOnLoad=e}if("index"===t&&o&&r.append(function(t,e){const n=s("div","cal-stage__intro cal-entrance cal-page-width");""!==t.heading&&n.append(s("h2","cal-stage__heading",t.heading)),""!==t.subheading&&n.append(s("p","cal-stage__lede",t.subheading));const o=s("form","cal-entrance__form");o.dataset.callimacusForm="";const r=s("input","cal-entrance__input");r.type="text",r.name="q",r.maxLength=200,r.autocomplete="off",r.enterKeyHint="send",r.placeholder=""===t.placeholder?`${e} anything`:t.placeholder,r.setAttribute("aria-label",e);const i=s("button","cal-button",""===t.buttonLabel?"Ask":t.buttonLabel);if(i.type="submit",o.append(r,i),n.append(o),t.starters.length>0){const e=s("div","cal-entrance__starters");for(const n of t.starters){const t=s("button","cal-chip cal-button cal-button--secondary",n);t.type="button",t.dataset.callimacusAsk=n,e.append(t)}n.append(e)}return n}(o,n)),"index"===t){const t=s("div","cal-welcome cal-page-width");t.dataset.callimacusWelcome="",t.hidden=!0,i.append(t)}const a=s("div");a.dataset.callimacusThread="",i.append(a),r.append(i);const c=document.querySelector("#MainContent")??document.querySelector("main")??document.querySelector('[role="main"]')??document.body,d="product"===t?function(t){const e=t.querySelector('form[action*="/cart/add"]'),n=e?.closest('[id^="shopify-section-"]')??void 0;return n&&t.contains(n)?n:void 0}(c):"index"===t?function(t){return t.querySelector(':scope > [id^="shopify-section-"]')??void 0}(c):void 0;return d?(d.after(r),{placed:!0,how:`after ${d.id}`}):(c.prepend(r),{placed:!0,how:`top of ${""===c.id?c.tagName.toLowerCase():`#${c.id}`}`})}const Mn="callimacus.rejected";function jn(t){const e=Number(t);return Number.isSafeInteger(e)?e:0}function Un({status:t,reason:e}){r("sessionStorage",Mn,JSON.stringify({status:t,...void 0!==e&&{reason:e},until:Date.now()+6e5}))}function Fn(){const t=o("sessionStorage",Mn);if(void 0===t)return;let e;try{e=JSON.parse(t)}catch{e=void 0}return h(e)?"number"==typeof e.until&&e.until<=Date.now()?void i("sessionStorage",Mn):{status:jn(e.status),..."string"==typeof e.reason&&{reason:e.reason}}:{status:jn(t)}}const Dn="callimacus.session";function Pn(t){return"string"==typeof t?t:""}function zn(t){return h(t)&&h(t.tokens)&&"string"==typeof t.css?{tokens:t.tokens,css:t.css,readAt:Pn(t.readAt)}:void 0}function Wn(t){if(!h(t))return;const e=Array.isArray(t.starters)?t.starters.filter(t=>"string"==typeof t&&""!==t.trim()):[];return{heading:Pn(t.heading),subheading:Pn(t.subheading),placeholder:Pn(t.placeholder),buttonLabel:Pn(t.buttonLabel),starters:e}}function Vn(t,e){if(h(t)&&""!==Pn(t.token)&&""!==Pn(t.endpoint)&&!Number.isNaN(Date.parse(Pn(t.expiresAt))))return{token:Pn(t.token),endpoint:Pn(t.endpoint),expiresAt:Pn(t.expiresAt),themeId:e,entrance:Wn(t.entrance),look:zn(t.look)}}async function Hn(t){try{const e=await t.json();return h(e)&&"string"==typeof e.reason?e.reason:void 0}catch{return}}function Kn(t,n){const i=t.endsWith("/")?t.slice(0,-1):t;let s,a;function c(t){return s=t,t&&r("sessionStorage",Dn,JSON.stringify(t)),t}async function d(){return a??=(async()=>{try{const t=await fetch(`${i}/session?theme_id=${encodeURIComponent(n)}`,{headers:{accept:"application/json"}});if([401,403,404].includes(t.status))return Un({status:t.status,reason:await Hn(t)}),c(void 0);if(!t.ok)throw new Error(`the storefront session answered ${t.status}`);return c(Vn(await t.json(),n))}finally{a=void 0}})(),a}async function l(){return s??=await async function(){const t=globalThis.callimacusSession;if(Reflect.deleteProperty(globalThis,"callimacusSession"),t)try{return Vn(await t,n)}catch(t){return void e.warn("the loader could not get a storefront session",t)}}()??function(){try{const t=JSON.parse(o("sessionStorage",Dn)??"null");return h(t)&&t.themeId===n?Vn(t,n):void 0}catch{return}}(),s}return{current:async function(){if(void 0!==Fn())return;const t=await l(),e=function(t){return void 0!==t&&Date.parse(t.expiresAt)-Date.now()>3e5}(t)?t:await d();return e?{token:e.token,endpoint:e.endpoint}:void 0},renew:async function(){const t=await d();return t?{token:t.token,endpoint:t.endpoint}:void 0},known:l,keepLook:function(t){s&&c({...s,look:t})}}}const Jn={fg:{property:"--cal-fg",kind:"color"},bg:{property:"--cal-bg",kind:"color"},bodyFont:{property:"--cal-font-body",kind:"font"},bodyWeight:{property:"--cal-font-body-weight",kind:"keyword"},bodyStyle:{property:"--cal-font-body-style",kind:"keyword"},bodySize:{property:"--cal-body-size",kind:"length"},headingFont:{property:"--cal-font-heading",kind:"font"},headingWeight:{property:"--cal-font-heading-weight",kind:"keyword"},headingStyle:{property:"--cal-font-heading-style",kind:"keyword"},headingCase:{property:"--cal-heading-transform",kind:"keyword"},buttonBg:{property:"--cal-button-bg",kind:"color"},buttonFg:{property:"--cal-button-fg",kind:"color"},buttonBorderColor:{property:"--cal-button-border-color",kind:"color"},buttonBorderWidth:{property:"--cal-button-border-width",kind:"length"},buttonRadius:{property:"--cal-radius-button",kind:"length"},buttonCase:{property:"--cal-button-transform",kind:"keyword"},buttonSpacing:{property:"--cal-button-letter-spacing",kind:"length"},buttonFont:{property:"--cal-font-button",kind:"font"},buttonWeight:{property:"--cal-font-button-weight",kind:"keyword"},secondaryFg:{property:"--cal-button2-fg",kind:"color"},mediaRadius:{property:"--cal-radius-media",kind:"length"},cardRadius:{property:"--cal-radius-card",kind:"length"},pageWidth:{property:"--cal-page-width",kind:"length"}},Yn={color:/^(?:#[\da-f]{3,8}|transparent|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([\s\d%+,\-./a-z]{1,80}\))$/iu,font:/^[\p{Letter}\p{Number} "',\-_]{1,200}$/u,length:/^(?:normal|none|-?(?:\d+(?:\.\d*)?|\.\d+)(?:px|rem|em|%|ch|vw)?)$/iu,keyword:/^(?:normal|bold|bolder|lighter|italic|oblique|none|uppercase|lowercase|capitalize|[1-9]\d{0,2}|1000)$/iu};function Gn(t){return Object.entries(t).filter(t=>{return e=t[0],Object.hasOwn(Jn,e)&&"string"==typeof t[1];var e}).map(([t,e])=>`${Jn[t].property}:${e}`).join(";")}const Xn=/^#(?<digits>[\da-f]{3,8})$/u,Zn=/^rgba?\((?<channels>[^)]*)\)$/u;function Qn(t){const e=t.trim().toLowerCase(),n=Xn.exec(e)?.groups?.digits;if(void 0!==n){const t=n.length<=4?[...n].map(t=>t+t).join(""):n;if(6!==t.length&&8!==t.length)return;const e=e=>Number.parseInt(t.slice(e,e+2),16);return[e(0),e(2),e(4),8===t.length?e(6)/255:1]}const o=Zn.exec(e)?.groups?.channels?.split(/[\s,/]+/u).filter(t=>""!==t);if(void 0===o||o.length<3||o.length>4)return;const[r=NaN,i=NaN,s=NaN,a=1]=o.map((t,e)=>function(t,e){const n=Number(t.endsWith("%")?t.slice(0,-1):t);return t.endsWith("%")?3===e?n/100:2.55*n:n}(t,e));return[r,i,s,a].some(t=>Number.isNaN(t))?void 0:[r,i,s,a]}function to([t,e,n]){const o=t=>{const e=t/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4};return.2126*o(t)+.7152*o(e)+.0722*o(n)}function eo(t,e){return(Math.max(to(t),to(e))+.05)/(Math.min(to(t),to(e))+.05)}function no(t){const e=void 0===t.bg?void 0:Qn(t.bg),n=void 0===t.buttonBg?void 0:Qn(t.buttonBg),o=void 0!==n&&n[3]>.5?n:e,r=void 0===t.buttonFg?void 0:Qn(t.buttonFg);if(void 0===o||void 0===r)return t;const i=eo(r,o);if(i>=3)return t;let s;for(const e of[t.fg,t.bg]){const t=void 0===e?void 0:Qn(e),n=void 0===t?0:eo(t,o);void 0!==e&&n>(s?.ratio??i)&&(s={value:e,ratio:n})}return void 0===s?t:{...t,buttonFg:s.value}}const oo="callimacus-look";let ro;function io(){return ro?.isConnected||(ro=document.createElement("div"),ro.setAttribute("aria-hidden","true"),ro.style.cssText="position:absolute;left:-9999px;top:0;width:400px;visibility:hidden;pointer-events:none;",document.body.append(ro)),ro}function so(t,e){const n=document.createElement("span");if(n.style.display="block",n.style[t]=e,""===n.style[t])return"";io().append(n);const o=getComputedStyle(n)[t];return n.remove(),o}function ao(t){const e=t.getBoundingClientRect(),n=getComputedStyle(t);return e.width>4&&e.height>4&&"hidden"!==n.visibility&&"none"!==n.display}function co(t){return"transparent"===t||/^rgba\((?:[^),]*,){3}\s*0(?:\.0+)?\)$/u.test(t)||/\/\s*0(?:\.0+)?\)$/u.test(t)}function lo(t,e=()=>!0){for(const n of t)for(const t of document.querySelectorAll(n))if(!v(t)&&ao(t)&&e(t))return{node:t,selector:n}}function uo(t){const e=[...t.classList].slice(0,2).map(t=>`.${t}`).join("");return`${t.tagName.toLowerCase()}${e}`}const ho=/\b(?:add to (?:cart|bag|basket)|buy now|add)\b/iu,po=['form[action*="/cart/add"] button[type="submit"]','form[action*="/cart/add"] button[name="add"]','form[action*="/cart/add"] input[type="submit"]','form[action*="/cart/add"] button:not([type="button"])'],fo=["main .button:not(.button--secondary):not(.button--tertiary)","main .btn:not(.btn--secondary)",'main a[class*="button"]','main button[class*="button"]',".shopify-section .button",".shopify-section .btn",'main button[type="submit"]'],mo=[".shopify-payment-button__button--unbranded"],go=/secondary|outline|tertiary/iu,yo=["main .button--secondary","main .btn--secondary",'main [class*="button-secondary"]'],bo=["main h1","main h2","h1","h2",".h1",".h2"],vo=['main a[href*="/products/"] img','a[href*="/products/"] img'],wo=[".card","product-card",".product-card",'[class*="product-card"]',".grid-product",".grid-view-item",".product-item"],ko=["main .page-width",".page-width","main .container","main .wrapper",".page-container .page-width","main .grid__item"],So=/banner|hero|slideshow|slider|carousel|video|image-with-text/iu;function Ao(t,e){const n=[];for(let o=t.parentElement;o&&n.length<e;o=o.parentElement)n.push(o);return n}function _o(t){return t.matches('button, a[href], input[type="submit"], input[type="button"]')}function xo(t){const e=[];let n=0,o=0;for(const[r,i]of[...t].entries())n+="("===i?1:")"===i?-1:0,","===i&&0===n&&(e.push(t.slice(o,r)),o=r+1);return e.push(t.slice(o)),e}function Co(t){for(const e of["::after","::before"]){const n=xo(getComputedStyle(t,e).boxShadow);for(const t of n){const n=/^(?<color>rgba?\([^)]*\))\s+0px\s+0px\s+0px\s+(?<width>[\d.]+)px$/u.exec(t.trim());if(void 0!==n?.groups?.color&&!co(n.groups.color))return{width:`${n.groups.width}px`,color:n.groups.color,how:`${e} outline`}}}}function Eo(t){return e=t.borderTopWidth,Number(e.replace(/px$/u,""))>0&&"none"!==t.borderTopStyle&&!co(t.borderTopColor);var e}function Ro(t){const e=t.getBoundingClientRect(),n=getComputedStyle(t);return e.width>=60&&e.height>=28&&!t.closest('header, nav, footer, [role="dialog"], dialog')&&(!co(n.backgroundColor)||Eo(n)||void 0!==Co(t))}function To(t){let e=t.parentElement;for(let t=0;e&&t<8&&!e.matches("main, body");t+=1){if(So.test(e.className)||"none"!==getComputedStyle(e).backgroundImage)return!0;e=e.parentElement}return!1}function qo(t,e){return go.test(t.className)||getComputedStyle(t).backgroundColor===e}function Oo(t,e){const n=t=>e=>_o(e)&&Ro(e)&&To(e)===t,o="product"===t?lo(po,n(!1))??function(){for(const t of document.querySelectorAll('main button, main a[href], main input[type="submit"]')){const e=t instanceof HTMLInputElement?t.value:t.textContent;if(ho.test(e.trim())&&!v(t)&&ao(t)&&Ro(t))return{node:t,selector:"a button labelled add to cart"}}}():void 0,r=(o&&qo(o.node,e)?lo([...mo,...fo],t=>n(!1)(t)&&!qo(t,e)):void 0)??o??lo(fo,n(!1))??("other"===t?lo(fo,n(!0)):void 0);return r?{node:r.node,how:`button ${uo(r.node)}`}:void 0}function $o(t,e,n,o){const r=Eo(e),i=r||!o?void 0:Co(o),s=r||void 0!==i;co(e.backgroundColor)?s&&t("buttonBg","transparent",`${n} (outline)`):t("buttonBg",e.backgroundColor,n),t("buttonFg",e.color,n),i?(t("buttonBorderColor",i.color,`${n} ${i.how}`),t("buttonBorderWidth",i.width,`${n} ${i.how}`)):(t("buttonBorderColor",r?e.borderTopColor:e.backgroundColor,n),t("buttonBorderWidth",r?e.borderTopWidth:"0px",n)),t("buttonRadius",e.borderTopLeftRadius,n),t("buttonCase",e.textTransform,n),t("buttonSpacing","normal"===e.letterSpacing?"0px":e.letterSpacing,n),t("buttonFont",e.fontFamily,n),t("buttonWeight",e.fontWeight,n)}const No=[{name:"Dawn",marker:"--font-body-family",read:{fg:"rgb(var(--color-foreground, var(--color-base-text)))",bg:"rgb(var(--color-background, var(--color-base-background-1)))",bodyFont:"var(--font-body-family)",headingFont:"var(--font-heading-family)",buttonBg:"rgb(var(--color-button, var(--color-base-accent-1)))",buttonFg:"rgb(var(--color-button-text, var(--color-base-solid-button-labels)))",buttonRadius:"var(--buttons-radius)",mediaRadius:"var(--media-radius)",cardRadius:"var(--product-card-corner-radius)",pageWidth:"var(--page-width)"}},{name:"Horizon",marker:"--font-body--family",read:{fg:"var(--color-foreground)",bg:"var(--color-background)",bodyFont:"var(--font-body--family)",headingFont:"var(--font-heading--family)",buttonRadius:"var(--style-border-radius-buttons-primary)"}}];function Lo(t,e){const{kind:n}=Jn[t];return so("color"===n?"color":"length"===n?"pageWidth"===t?"width":"borderTopLeftRadius":"fontFamily",e)}function Io(t){const e={},n=(t,n,o)=>{const r=n.trim();!(""===r||!("buttonBg"===t&&"transparent"===r)&&"color"===Jn[t].kind&&co(r))&&void 0===e[t]&&function(t,e){return e.length<=200&&Yn[t].test(e.trim())}(Jn[t].kind,r)&&(e[t]={value:r,how:o})};return function(t,e){const n=getComputedStyle(document.body);t("fg",n.color,"body text");let o=n.backgroundColor;co(o)&&(o=getComputedStyle(document.documentElement).backgroundColor),t("bg",co(o)?"rgb(255, 255, 255)":o,co(o)?"browser default":"page background"),t("bodyFont",n.fontFamily,"body text"),t("bodyWeight",n.fontWeight,"body text"),t("bodyStyle",n.fontStyle,"body text"),t("bodySize",n.fontSize,"body text");const r=lo(bo,t=>""!==t.textContent.trim());if(r){const e=getComputedStyle(r.node),n=`heading ${uo(r.node)}`;t("headingFont",e.fontFamily,n),t("headingWeight",e.fontWeight,n),t("headingStyle",e.fontStyle,n),t("headingCase",e.textTransform,n)}const i=Oo(e,co(o)?"rgb(255, 255, 255)":o);i&&$o(t,getComputedStyle(i.node),i.how,i.node);const s=lo(yo,t=>_o(t)&&!To(t));s&&t("secondaryFg",getComputedStyle(s.node).color,`button ${uo(s.node)}`);const a=lo(vo);if(a){const e=[a.node,...Ao(a.node,4)].find(t=>!["0px","0",""].includes(getComputedStyle(t).borderTopLeftRadius));t("mediaRadius",e?getComputedStyle(e).borderTopLeftRadius:"0px",e?`product image ${uo(e)}`:`product image ${uo(a.node)} (square)`)}const c=lo(wo);c&&t("cardRadius",getComputedStyle(c.node).borderTopLeftRadius,`card ${uo(c.node)}`);const d=lo(ko,t=>"none"!==getComputedStyle(t).maxWidth&&t.getBoundingClientRect().width>300);d&&t("pageWidth",getComputedStyle(d.node).maxWidth,`content width ${uo(d.node)}`)}(n,t),function(t){const e=getComputedStyle(document.documentElement),n=No.find(t=>""!==e.getPropertyValue(t.marker).trim());for(const[e,o]of Object.entries(n?.read??{}))t(e,Lo(e,o),`${n?.name??""} variable ${o}`)}(n),"other"===t&&void 0===e.buttonFg&&function(t){const e=document.createElement("a");e.className="button button--primary btn btn--primary",e.href="#",e.textContent="Probe",io().append(e);const n=getComputedStyle(e);co(n.backgroundColor)||$o(t,n,"probe .button.btn",void 0)}(n),io().remove(),e}function Bo(t){return Object.fromEntries(Object.entries(t).map(([t,e])=>[t,e.value]))}function Mo(t){let e=document.querySelector(`#${oo}`);e||(e=document.createElement("style"),e.id=oo,document.head.append(e)),e.textContent=`:root{${Gn(t)}}`}function jo(t){return Object.keys(Jn).filter(e=>void 0===t[e])}function Uo(){return"function"==typeof globalThis.matchMedia&&globalThis.matchMedia("(prefers-color-scheme: dark), (forced-colors: active), (prefers-contrast: more)").matches||void 0!==document.documentElement.dataset.darkreaderScheme||null!==document.querySelector('meta[name="darkreader"]')}function Fo(t,e){const n=performance.now();t.readings=Io("product"),t.measureMs=Math.round(performance.now()-n);const o=function(t,e){const n=no({...t,...Bo(e)});return Object.keys(Jn).some(e=>n[e]!==t[e])?n:void 0}(e,t.readings);void 0!==o&&(Mo(o),t.look=o,t.unset=jo(o))}async function Do({page:t,stored:e,post:n,keep:o}){if(e){Mo(e.tokens);const n={source:"stored",page:t,readings:{},look:e.tokens,unset:jo(e.tokens)};return"product"===t&&Uo()&&Fo(n,e.tokens),n}const r=performance.now(),i=Io(t),s=function(t){return no(Bo(t))}(i),a={source:"read",page:t,readings:i,look:s,unset:jo(s),measureMs:Math.round(performance.now()-r)};if(Mo(s),"product"!==t||0===Object.keys(s).length||Uo())return a;const c=await n(s).catch(()=>{});return a.posted=void 0===c?"failed":c.stored?"stored":"kept",c&&o(c.look),c&&!c.stored&&(Mo(c.look.tokens),a.look=c.look.tokens,a.unset=jo(c.look.tokens)),a}const Po=["hero","answer","picks","topic","cross","next","other"],zo=["hero","answer","picks","topic","cross","next"],Wo=new Map([["custom:editorialHero","hero"],["custom:storefrontReply","answer"],["custom:pageAnswer","answer"],["demosthenesResponse","answer"],["custom:demosthenesResponse","answer"],["custom:addToCartResult","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 Vo(t){return"object"==typeof t&&null!==t&&"string"==typeof t.type&&"function"==typeof t.render}function Ho(t){const e=globalThis.callimacusRenderers;if(Array.isArray(e))for(let n=e.length-1;n>=0;n--){const o=e[n];if(Vo(o)&&o.type===t)return o}}function Ko(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 l(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(),l(r,o),0))}}}(n),i=new Set;return t=>{const n=Ho(t)??o.get(t)??Ho("*")??o.get("*");return n||(Wo.has(t)?void(i.has(t)||(i.add(t),e.warn(`no renderer for ${t}, skipped`))):r)}}function Jo(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 Yo(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}`),a=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(c,"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(c,"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")),a.append(d),i.append(a);const u=s("div","cal-chapter__body");u.id=r;const h=new Map;for(const t of Po){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,cart:e.cart,slots:h,el:o,body:u,toggle:d,thumbs:l,timing:void 0}}function Go(t,e){const n=t.slots.get(e);if(!n)throw new Error(`chapter has no ${e} slot`);return n}function Xo(t,e){t.el.dataset.state=e,t.el.setAttribute("aria-busy",String("streaming"===e))}function Zo(t){let e;for(const n of t)(!e||n.index>e.index)&&(e=n);return e}function Qo(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 tr(t,e=""){return"string"==typeof t&&""!==t.trim()?t.trim():e}function er(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 _(t)){if(g(e))return e.trim();if(h(e)&&g(e.text))return e.text.trim()}return""},hits:t=>w(Array.isArray(t)?t:[t]),picks(t){for(const e of _(t)){if(!Array.isArray(e))continue;const t=w(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(!p(t)){const e=h(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(f(t)){case"product":return`/products/${e}`;case"collection":return`/collections/${e}`;case"article":{const n=y(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 nr(){return globalThis.Shopify}function or(){try{const t=nr()?.customerPrivacy?.preferencesProcessingAllowed?.();return void 0===t?"unknown":!0===t?"allowed":"refused"}catch{return"unknown"}}function rr(t){return o("sessionStorage",t)??("allowed"===or()?o("localStorage",t):void 0)}function ir(t){const n=rr(t);if(void 0!==n&&""!==n)try{return JSON.parse(n)}catch{return void e.warn(`ignoring unreadable "${t}"`)}}function sr(t,e){const n=r("sessionStorage",t,e);return"allowed"!==or()||r("localStorage",t,e)||i("localStorage",t),n}function ar(t){i("localStorage",t),i("sessionStorage",t)}function cr(t){const e=or();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 dr="callimacus.memory",lr=6,ur=12,hr=12,pr=new TextEncoder;function fr(t){return Array.isArray(t)?t.filter(t=>h(t)):[]}function mr(t){return"number"==typeof t&&Number.isFinite(t)?t:0}function gr(){const t=ir(dr),e=h(t)?t:{};return{questions:fr(e.questions).filter(t=>"string"==typeof t.q).map(t=>({q:t.q,at:mr(t.at)})),viewed:fr(e.viewed).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,title:"string"==typeof t.title?t.title:"",at:mr(t.at)})),added:fr(e.added).filter(t=>"string"==typeof t.handle).map(t=>({handle:t.handle,at:mr(t.at)}))}}function yr(t){return"string"==typeof t?t:h(t)&&"string"==typeof t.handle?t.handle:""}function br(t,n){const o=gr(),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=yr(n);if(""===t)return;const e=h(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=yr(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}"`)}sr(dr,JSON.stringify(o))}function vr(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,lr).map(t=>n(t)),viewed:t.viewed.filter(t=>o(t.handle)).slice(0,ur).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,hr)};for(;pr.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 wr(t){return s("div",`cal-skeleton__bone cal-skeleton__bone--${t}`)}function kr(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(wr("media"),wr("title"),wr("price")),t.append(o),n.append(t)}return n}function Sr(){const t=s("div","cal-skeleton__lines");return t.append(wr("line"),wr("line"),wr("line")),t}function Ar(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?[wr("hero")]:[wr("lead"),Sr()];case"answer":return[Sr()];case"picks":return[kr(4,n)];case"topic":return[wr("topic")];case"cross":return[kr(3,n)];case"next":{const t=s("div","cal-skeleton__chips");return t.append(wr("chip"),wr("chip"),wr("chip")),[t]}case"other":return[]}}(t,i,n)),r.append(a),o.append(r),o}function _r(t,e){if(!h(t)||"shopify-add"!==t.command||"string"!=typeof t.chapterId||"string"!=typeof t.variantId||!(t=>Oe.test(t))(t.variantId))return;if(void 0!==e&&"string"==typeof t.storyId&&t.storyId!==e)return;const n=h(t.item)?t.item:{},o=(Array.isArray(n.options)?n.options:[]).filter(t=>h(t)&&"string"==typeof t.value).map(t=>{const{name:e,value:n}=t;return{name:"string"==typeof e?e:"",value:n}});return{storyId:"string"==typeof t.storyId?t.storyId:e??"",chapterId:t.chapterId,command:"shopify-add",variantId:t.variantId,quantity:"number"==typeof t.quantity?t.quantity:NaN,item:{id:"string"==typeof n.id?n.id:"",name:"string"==typeof n.name&&""!==n.name?n.name:"This product",options:o}}}function xr(t,e){const n=String(t?.id??"");if(void 0===e||e!==t?.title||!/^\d+$/u.test(n))return{};const{innerWidth:o,innerHeight:r}=globalThis,i={id:`shopify:product:gid://shopify/Product/${n}`,isVisible:!0,visibilityRatio:1,bounds:{x:0,y:0,width:o,height:r,top:0,left:0,right:o,bottom:r}};return{uiSnapshot:{timestamp:Date.now(),viewport:{width:o,height:r},elements:[i],blockIds:[]}}}const Cr="callimacus.thread",Er="callimacus.storyId",Rr=15e5;function Tr(t){return Array.isArray(t)?t.filter(t=>h(t)&&"string"==typeof t.id&&""!==t.id):[]}function qr(t){const e=t.inputEvent;return h(e)&&h(e.data)?b(e.data.value):""}function Or(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 $r(t){const e=Number(t);return Number.isFinite(e)?e:0}function Nr(){return rr(Er)}function Lr(t){void 0===t?ar(Er):sr(Er,t)}const Ir=new Set(["added","refused","unavailable","failed"]);function Br(t){const{notice:e}=t;return h(e)&&"string"==typeof e.outcome&&Ir.has(e.outcome)&&"string"==typeof e.message?{notice:{outcome:e.outcome,message:e.message}}:{}}function Mr(){const t=ir(Cr);return Array.isArray(t)?t.filter(t=>h(t)&&"string"==typeof t.question).map(t=>t).map(t=>{const e=t.question;return{id:""===b(t.id)?void 0:b(t.id),question:e,about:""===b(t.about)?void 0:b(t.about),sent:""===b(t.sent)?e:b(t.sent),index:$r(t.index),status:$r(t.status),blocks:Tr(t.blocks),...h(t.cart)&&{cart:Br(t.cart)}}}).sort((t,e)=>t.index-e.index).slice(-12):[]}function jr(t){return Math.round(performance.now()-t.t0)}const Ur=4e3,Fr=[Cr,Er,dr],Dr="data-callimacus-on",Pr=new Set([401,403]),zr=new Set(["invalid_token","origin_not_allowed","paused"]);function Wr(t){return"function"==typeof globalThis.matchMedia?globalThis.matchMedia(t):{matches:!1}}function Vr(t){const{kit:n}=t,o=t.roundTimeoutMs??45e3,r=t.createTransport??(()=>new Ee),i=function(){let t={};try{const e=JSON.parse(document.querySelector("#callimacus-config")?.textContent??"{}");t=h(e)?e:{}}catch(t){e.error("#callimacus-config is not valid JSON",t)}const n=globalThis.Shopify,o=h(t.product)&&""!==tr(t.product.handle)?Object.freeze({handle:tr(t.product.handle),title:tr(t.product.title),id:"number"==typeof t.product.id||"string"==typeof t.product.id?t.product.id:void 0}):void 0,r=tr(t.storeName,"this store");return Object.freeze({language:tr(t.language,"en"),rootUrl:tr(t.rootUrl,"/"),cartAddUrl:tr(t.cartAddUrl,"/cart/add"),currency:tr(t.currency,"USD"),designMode:!0===t.designMode||Boolean(n?.designMode),template:tr(t.template),product:o,storeName:r,assistantLabel:tr(t.assistantLabel,`Ask ${r}`),starters:Object.freeze(Array.isArray(t.starters)?t.starters.map(t=>tr(t)).filter(t=>""!==t):[])})}(),c=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),d=document.documentElement,l=new AbortController,{signal:p}=l,f=[],m=Wr("(prefers-reduced-motion: reduce)"),g=Wr("(pointer: coarse)"),y={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},v=[],w=Ko(t.renderers,n.classes),k=function(t){const e=new Set;function n(n){const o=function(){try{const e=JSON.parse(t().getItem(Re)??"[]");return Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}catch{return}}();if(o?.includes(n)||e.has(n))return!1;try{t().setItem(Re,JSON.stringify([...o??[],n].slice(-50)))}catch{e.add(n)}return!0}return async(t,e)=>{if(void 0===e||!n(t.chapterId))return;const o=Math.trunc(t.quantity),r=Math.min(Math.max(Number.isFinite(o)?o:1,1),10),i=await e(r);return{notice:qe({id:t.chapterId,item:t.item,quantity:r},i),...i.error&&{code:i.error.code}}}}(()=>sessionStorage);function S(){l.abort();for(const t of f)t.disconnect();clearTimeout(y.refreshTimer),clearTimeout(y.statusTimer),clearTimeout(y.round?.timer)}function A(t,e){document.dispatchEvent(new CustomEvent(t,{detail:e}))}function _(t){y.ui!==t&&(y.ui=t,d.dataset.callimacusState=t,A("callimacus:state",{state:t}))}function E(t,{clearAfter:e=0}={}){clearTimeout(y.statusTimer);for(const e of document.querySelectorAll("[data-callimacus-status]"))e.textContent=t;e>0&&(y.statusTimer=setTimeout(()=>{E("")},e))}function R(t){y.storyId=""===t?void 0:t,Lr(y.storyId)}async function T(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&&br("added",r.handle),r}const q=er(i,{addToCart:T,ask:t=>"refused"!==G(t,{type:"relatedQuestion"}),remember:br});const O={stage:void 0,thread:void 0,earlier:void 0,trimmed:void 0,dock:document.querySelector("[data-callimacus-dock]")??void 0};function $(){return O.stage?.dataset.stageKind??"page"}function N(){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",()=>{I(!1)},{signal:p});const r=s("p",`cal-thread__trimmed ${n.classes.pageWidth}`,c.trimmed);return r.hidden=!0,e.after(o,r),Object.assign(O,{stage:t,thread:e,earlier:o,trimmed:r}),{stage:t,thread:e}}function L(){return O.thread??N().thread}function I(t){O.thread&&(O.thread.toggleAttribute("data-compact",t),B())}function B(){if(!O.earlier||!O.thread||!O.trimmed)return;const t=y.thread.length-1,e=Object.hasOwn(O.thread.dataset,"compact"),n=e&&t>0;O.earlier.hidden=!n,n&&(O.earlier.textContent=`Show ${t} earlier question${1===t?"":"s"}`),O.trimmed.hidden=e||0===y.thread.length||y.thread.some(t=>0===t.index)}function M(){const t=new Set([...y.thread].sort((t,e)=>e.index-t.index).slice(12));for(const e of t)e.el.remove();y.thread=y.thread.filter(e=>!t.has(e))}function j(t){y.nextKey+=1;const e=Yo(y.nextKey,t,n.classes);return e.toggle.addEventListener("click",()=>{D(e,Object.hasOwn(e.el.dataset,"collapsed"))},{signal:p}),e}function F(t){for(const e of zo){const o=Go(t,e);o.querySelector(":scope > .cal-block, :scope > .cal-skeleton")||o.append(Ar(e,t.index,n.classes))}}function D(t,e,{shouldAnimate:n=!0}={}){e!==!Object.hasOwn(t.el.dataset,"collapsed")&&(e||t.thumbs.replaceChildren(...function(t){const e=new Set,n=[],o=Qo(t).flatMap(t=>q.picks(t));for(const t of o){if(4===n.length)break;const o=t.fields["shopify-handle"],r=q.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&&!m.matches&&(t.el.dataset.animating="",setTimeout(()=>{delete t.el.dataset.animating},360)))}function P(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=u(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:m.matches?"auto":"smooth",block:"start"})};"function"==typeof requestAnimationFrame?requestAnimationFrame(n):n()}function z(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?c.interrupted:c.unanswered));const i=s("button","cal-chapter__retry","Ask again");i.type="button",i.addEventListener("click",()=>{G(t.question,{type:"question",about:t.about})},{signal:p}),r.append(i),t.body.append(r)}function W(t,e,n,o){const r=Go(t,Wo.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)??r.querySelector(":scope > .cal-cart-notice");if(a?a.before(i):r.append(i),o.shouldAnimate&&!m.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=jr(c),performance.mark(`callimacus:chapter-${c.chapter}:first-block`)),A("callimacus:block",{chapterId:t.id,blockId:e.id,type:e.type,node:n}),i}function V(t,n,o,r){const i=w(n.type);if(!i||!x(n))return!1;const s=function(t,e){return`${void 0===t.cart?"":"cart|"}${JSON.stringify(e.data)}`}(t,n);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=Jo(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=W(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=Jo(i,n,o);return!1===c?a.isBroken=!0:c&&a.wrap&&(a.wrap.replaceChildren(c),a.node=c),!1}function H(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]),addedToCart:void 0!==t.cart});return Object.freeze({...q,chapter:n,final:e})}(t);let r=0;for(const[i,s]of Qo(t).entries())V(t,s,o,{order:i,stagger:r,hasBecomeDone:e,shouldAnimate:n})&&(r+=1)}const K=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;switch(n.type){case ue:!function(t){if(!h(t)||"string"!=typeof t.id||""===t.id)return;t.id!==y.storyId&&R(t.id);const e=(Array.isArray(t.chapters)?t.chapters:[]).filter(t=>h(t)&&"string"==typeof t.id&&""!==t.id&&!0!==t.deleted).map(t=>t);e.length>0?function(t){const e="restore"===y.hydrateMode;let n=!1;for(const o of t.slice(-12)){const r=t.indexOf(o),i=y.thread.find(t=>t.id===o.id)??et(o);if(i){e&&dt(i,r),nt(i,o,y.round?.rec===i);continue}const s=qr(o);if(!e||""===s)continue;const{question:a,about:c}=Or(s);at({id:o.id,question:a,about:c,sent:s,index:r,status:"number"==typeof o.status?o.status:0,blocks:Tr(o.blocks)}),n=!0}if(n){const e=new Set(t.map(t=>t.id));let n=t.length;for(const t of y.thread)e.has(t.id)||dt(t,n++);wt(),ct(),st()}e&&(y.hydrateMode="refresh")}(e):"restore"===y.hydrateMode&&(y.hydrateMode="refresh")}(n.story);break;case le:!function(t){if(!h(t)||"string"!=typeof t.id||""===t.id||!0===t.deleted)return;const n=y.thread.find(e=>e.id===t.id)??et(t);n?nt(n,t,!0):e.debug("chapter-event for a chapter this page does not show",t.id)}(n.chapter);break;case he:!async function(t){const n=_r(t,y.storyId);if(!n)return void e.debug("cart-command this page does not run");const o=y.thread.find(t=>t.id===n.chapterId)??y.round?.rec,r=await k(n,async t=>(o&&(o.cart={},z(o,!1),H(o,{shouldAnimate:!1}),st()),U(async()=>T(n.variantId,t))));if(!r)return;const{notice:i}=r;if(E(i.message,{clearAfter:8e3}),A("callimacus:cart",{outcome:i.outcome,variantId:n.variantId,quantity:i.quantity,..."added"!==i.outcome&&{message:i.message}}),!o)return;o.cart={notice:{outcome:i.outcome,message:i.message}},J(o),st()}(n.data);break;default: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&&K.didRenew())return;if(function(t){return Pr.has(t.code)&&(!y.isConnected||zr.has(t.reason??""))}(t))return void Y(t);const{round:r}=y;if(404===n&&(R(void 0),ht({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(()=>{tt(r)},o),void Q(r);const i=!y.isConnected;if(i&&"retries_exhausted"!==t.reason&&!(n>=400&&n<500))return void(r&&E(c.reconnecting));i&&K.markFailed();r?(E(i?c.unavailable:c.failed),ot(r.rec,"error")):i&&(_("error"),E(c.unavailable))},onStatus:function(t){y.isConnected=t;const{round:e}=y;if(!t||!e||void 0!==e.rec.timing?.firstEventMs)return;_("asking"),E(c.asking)},isOff:()=>y.isOff,onRefused(){const{status:t,reason:e}=Fn()??{status:401,reason:"invalid_token"};Y({code:t,reason:e})}});function J(t){const e=t.cart?.notice;e&&Go(t,"answer").append(a(e,n.classes.pageWidth))}function Y(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`),y.isOff=!0,Un({status:t.code,reason:t.reason}),ht(),y.queue=[],gt(),y.round&&ot(y.round.rec,"error"),_("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;E(c.unavailable)}else d.removeAttribute(Dr),E("");A("callimacus:off",{code:t.code,reason:t.reason})}function G(t,{type:e="question",about:n}={}){const o=b(t),r=function(t){if(""===t||y.isOff)return"";if(i.designMode)return c.designMode;const e=Date.now();return y.lastAsk?.text===t&&e-y.lastAsk.at<600?"":(y.lastAsk={text:t,at:e},y.round&&y.queue.length>=3?c.queueFull:void 0)}(o);if(void 0!==r)return""!==r&&E(r,{clearAfter:r===c.unavailable?0:Ur}),"refused";const s={display:o,about:n,type:e,sent:void 0===n?o:`${o} (about the ${n})`,visit:vr(gr(),o)};return br("questions",o),A("callimacus:ask",{question:o,type:e,queued:Boolean(y.round)}),y.round?(y.queue.push(s),gt(),E(c.queued(o),{clearAfter:Ur}),"queued"):(X(s),"sent")}function X(t){const e=j({question:t.display,about:t.about,sent:t.sent,index:Z()});for(const t of y.thread)D(t,!1);y.thread.push(e),L().prepend(e.el),M(),Xo(e,"streaming"),F(e),wt(),mt(),B();const n={rec:e,type:t.type,visit:t.visit,timer:void 0,isRetried:!1};var r,i;y.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()}),v.push(e.timing),_(y.isConnected?"asking":"connecting"),E(y.isConnected?c.asking:c.connecting),n.timer=setTimeout(()=>{tt(n)},o),P(e),st(),A("callimacus:chapter",rt(e)),Q(n)}function Z(){let t=0;for(const e of y.thread)t=Math.max(t,e.index+1);return t}function Q(t){try{K.connect()}catch(n){return e.error("could not start the Callimacus client",n),void(y.round===t&&(E(c.unavailable),ot(t.rec,"error")))}if(y.round===t)try{!function(t){const e={visit:t.visit,shopifyCart:!0,...xr(i.product,t.rec.about)},n={...void 0!==y.storyId&&{storyId:y.storyId},language:i.language,inputEvent:{type:t.type,data:{value:t.rec.sent}},context:e};K.send(we.CREATE_ROUND,n)}(t)}catch(n){e.error("could not send the question",n),E(c.failed),ot(t.rec,"error")}}function tt(t){y.round===t&&(e.warn(`no complete answer within ${o/1e3} s for “${t.rec.question}”`),E(c.timeout),ot(t.rec,"timeout"))}function et(t){const e=qr(t),n=""===e?void 0===y.round?.rec.id?y.round?.rec:void 0:y.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 nt(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,Tr(e.blocks)),t.status="number"==typeof e.status?e.status:t.status,y.round?.rec===t&&void 0===t.timing?.firstEventMs&&(r=t.timing,i=t.id,r&&void 0===r.firstEventMs&&(r.firstEventMs=jr(r),r.chapterId=i),_("streaming"),E(c.streaming));const s=!o&&4===t.status;H(t,{hasBecomeDone:s,shouldAnimate:n}),s&&ot(t,"done")}function ot(t,n){const o="done"!==n;Xo(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),z(t,o&&!y.isOff&&void 0===t.cart),function(t,n,o){if("pending"!==t?.outcome)return;t.outcome=o,t.chapterId=n,t.doneMs=jr(t),performance.mark(`callimacus:chapter-${t.chapter}:${o}`);const{t0:r,...i}=t;e.debug("timing",i)}(t.timing,t.id,n),st(),A("callimacus:chapter",rt(t));const r=y.round?.rec===t?y.round:void 0;r&&(clearTimeout(r.timer),y.round=void 0,o?_("error"):(_("idle"),E(c.done,{clearAfter:Ur})),function(){if(void 0!==y.round||y.isOff)return;const t=y.queue.shift();if(!t)return;gt(),X(t)}())}function rt(t){return{id:t.id,index:t.index,question:t.question,state:t.el.dataset.state}}function it(t){return{id:t.id,question:t.question,about:t.about,sent:t.sent,index:t.index,status:t.status,blocks:t.blocks,...t.cart&&{cart:t.cart}}}function st(){!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>Rr){for(const t of e)t.blocks=C(t.blocks);n=JSON.stringify(e)}for(;e.length>0;){if(n.length<=Rr&&sr(Cr,n))return;e.shift(),n=JSON.stringify(e)}ar(Cr)}(y.thread.map(t=>it(t))),Lr(y.storyId)}function at(t){const e=j(t);y.thread.push(e);const n=4===e.status,o=!n&&void 0!==e.id&&void 0!==y.storyId;return Xo(e,n?"done":o?"streaming":"error"),o&&F(e),H(e,{shouldAnimate:!1}),J(e),n||o||void 0!==e.cart||z(e,!0),e}function ct(){M();const t=Zo(y.thread),e="home"===$();for(const n of y.thread)D(n,e&&n===t||y.round?.rec===n,{shouldAnimate:!1});!function(){const t=[...y.thread].sort((t,e)=>e.index-t.index);L().append(...t.map(t=>t.el))}(),I(!e),mt()}function dt(t,e){t.index=e,t.el.dataset.chapterIndex=String(e)}function lt(){return y.thread.filter(t=>void 0!==t.id&&4!==t.status&&y.round?.rec!==t&&"streaming"===t.el.dataset.state)}function ut(t=0){clearTimeout(y.refreshTimer);const{storyId:n}=y;if(!(void 0===n||y.isOff||t>0&&"restore"!==y.hydrateMode&&0===lt().length))if(t>=6)ht({shouldFailPending:!0});else{try{K.send(we.GET_STORY,{storyId:n})}catch(t){e.error("could not start the Callimacus client",t)}y.refreshTimer=setTimeout(()=>{ut(t+1)},3e3)}}function ht({shouldFailPending:t=!1}={}){if(clearTimeout(y.refreshTimer),y.hydrateMode=void 0,t)for(const t of lt())ot(t,"error")}const pt=t=>O.dock?.querySelector(t)??void 0,ft={input:pt('input[name="q"]'),chips:pt("[data-callimacus-dock-chips]"),count:pt("[data-callimacus-thread-count]"),countLabel:pt("[data-callimacus-thread-count-label]"),next:pt("[data-callimacus-next]"),nextLabel:pt("[data-callimacus-next-label]"),about:pt("[data-callimacus-about]"),aboutLabel:pt("[data-callimacus-about-label]")};function mt(){if(!ft.count)return;const t=y.thread.length;ft.count.hidden=0===t;const e=`${t} question${1===t?"":"s"}`;ft.countLabel&&(ft.countLabel.textContent=String(t)),ft.count.title=e,ft.count.setAttribute("aria-label",`${e} in this conversation. Show the conversation`)}function gt(){if(!ft.next)return;const[t]=y.queue;if(ft.next.hidden=void 0===t,void 0!==t){const e=y.queue.length>1?` (+${y.queue.length-1})`:"";ft.nextLabel&&(ft.nextLabel.textContent=`Next: ${t.display}${e}`),ft.next.setAttribute("aria-label",`Next question: ${t.display}. Remove it from the queue`)}ft.chips&&(ft.chips.hidden=[...ft.chips.children].every(t=>t instanceof HTMLElement&&!0===t.hidden))}function yt(){const t=y.about;ft.about&&(ft.about.hidden=void 0===t),void 0!==t&&ft.aboutLabel&&(ft.aboutLabel.textContent=`About: ${t}`),ft.input&&(ft.input.placeholder=void 0===t?ft.input.dataset.placeholder??ft.input.placeholder:"Ask anything about it")}function bt(){ft.input&&(ft.input.focus(),St())}function vt(){I(!1);const t=Zo(y.thread);t&&(D(t,!0),P(t))}function wt(){const t=document.querySelector("[data-callimacus-welcome]");t&&(t.hidden=!0)}function kt(t){const e=s("section","cal-welcome__group");return e.append(s("h2","cal-welcome__title",t)),e}function St(){if(!i.designMode&&!y.isOff)try{K.connect()}catch(t){e.error("could not start the Callimacus client",t)}}function At(){return!y.isOff&&d.hasAttribute(Dr)}function _t(t){const e=t.target instanceof Element?t.target.closest("[data-callimacus-form]"):void 0;if(!e||!At())return;t.preventDefault();const n=e.querySelector('input[name="q"]'),o=n?.value.trim()??"";n&&""!==o?("refused"!==G(o,{type:"question",about:y.about})&&(n.value=""),g.matches&&n.blur()):n?.focus()}function xt(t){if(!(At()&&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(),G(n,{type:"relatedQuestion"})))}t.target.closest("[data-callimacus-open]")&&(t.preventDefault(),bt())}function Ct(t){var e;At()&&("/"!==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(),bt()))}const Et={ask:t=>"refused"!==G(t,{type:"question"}),get thread(){return[...y.thread].sort((t,e)=>t.index-e.index).map(t=>it(t))},ctx:q,timings:v,get state(){return y.ui},get storyId(){return y.storyId},reset:function(){ht(),clearTimeout(y.round?.timer),y.round=void 0,y.queue=[];for(const t of y.thread)t.el.remove();y.thread=[],R(void 0),ar(Cr),gt(),mt(),I(!1),_("idle"),E("")}};d.dataset.callimacusState=y.ui;const Rt=globalThis;if(Rt.callimacus=Et,Rt.callimacusTheme={card:n.card,cards:n.cards},void 0!==Fn()||!d.hasAttribute(Dr))return d.removeAttribute(Dr),y.isOff=!0,_("error"),A("callimacus:ready",{designMode:i.designMode,off:!0}),{page:Et,destroy:S};if(n.install?.(),function(t,e){cr(t),document.addEventListener("visitorConsentCollected",()=>{cr(t)},{signal:e})}(Fr,p),y.storyId=Nr(),document.addEventListener("submit",_t,{signal:p}),document.addEventListener("click",xt,{signal:p}),document.addEventListener("keydown",Ct,{signal:p}),document.addEventListener("focusin",t=>{t.target instanceof Element&&t.target.matches('[data-callimacus-form] input[name="q"]')&&St()},{signal:p}),ft.count?.addEventListener("click",vt,{signal:p}),ft.next?.addEventListener("click",()=>{y.queue.shift(),gt(),E(c.dequeued,{clearAfter:Ur}),ft.input?.focus()},{signal:p}),O.dock?.querySelector("[data-callimacus-about-remove]")?.addEventListener("click",()=>{y.about=void 0,yt(),ft.input?.focus()},{signal:p}),function(){const{dock:t}=O;if(!t||"function"!=typeof ResizeObserver)return;const e=new ResizeObserver(()=>{d.style.setProperty("--cal-dock-space",`${Math.ceil(t.offsetHeight)}px`)});e.observe(t),f.push(e)}(),globalThis.addEventListener("pagehide",()=>{(void 0!==y.round||lt().length>0)&&st()},{signal:p}),globalThis.addEventListener("pageshow",t=>{t.persisted&&function(){const t=t=>t.id??`${t.index}:${t.sent}`,e=new Set(y.thread.map(e=>t(e))),n=Mr().filter(n=>!e.has(t(n))),o=Nr();if(void 0!==o&&o!==y.storyId&&(y.storyId=o),0!==n.length){for(const t of n)at(t);wt(),ct(),B()}}()},{signal:p}),yt(),mt(),gt(),i.designMode)return A("callimacus:ready",{designMode:!0,off:!1}),{page:Et,destroy:S};i.product&&br("viewed",{handle:i.product.handle,title:i.product.title});const{stage:Tt}=N();!function(){for(const t of Mr())at(t);return 0!==y.thread.length&&(ct(),!0)}()?void 0!==y.storyId&&(y.hydrateMode="restore",ut()):lt().length>0&&(y.hydrateMode="refresh",ut()),"home"===$()&&function(){const t=document.querySelector("[data-callimacus-welcome]");if(!t)return;const e=gr(),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===y.thread.length&&o.length>0){const t=kt("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===y.thread.length&&r.length>0?n.cards(r.map(t=>({handle:t.handle,title:t.title})),q):void 0;if(a){const t=kt("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 qt=b(Tt.dataset.askOnLoad);return""!==qt&&Zo(y.thread)?.question!==qt&&G(qt,{type:"question"}),A("callimacus:ready",{designMode:!1,off:!1}),{page:Et,destroy:S}}const Hr="callimacus.pending";function Kr(){return document.querySelector("#callimacus-config")??void 0}async function Jr(){const t=document.documentElement,n=function(){try{const t=JSON.parse(Kr()?.textContent??"{}");return h(t)?t:{}}catch{return{}}}(),r=function(t){return{cards:"own"===t.cards?"own":"auto",proxyBase:""===b(t.proxyBase)?"/apps/callimacus":b(t.proxyBase),searchTerms:b(t.searchTerms),template:b(t.template),starters:Array.isArray(t.starters)?t.starters.map(t=>b(t)).filter(t=>""!==t):[],designMode:!0===t.designMode,assistantLabel:""===b(t.assistantLabel)?"Ask":b(t.assistantLabel)}}(n),s=globalThis.Shopify?.theme?.id,a="number"==typeof s||"string"==typeof s?String(s):"",c=Kn(r.proxyBase,a),d=()=>void 0!==Fn()||!t.hasAttribute(Dr),l=d()?void 0:async function(){const t=nr();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()}})}(),u=d()?void 0:await c.known(),p=u?.entrance&&{...u.entrance,starters:r.starters.length>0?r.starters:u.entrance.starters.slice(0,4)};let f;p&&0===r.starters.length&&p.starters.length>0&&function(t,e){const n=Kr();n&&(n.textContent=JSON.stringify({...t,...e}))}(n,{starters:p.starters}),t.dataset.callimacusTemplate=r.template,d()||(f=await Do({page:"product"!==r.template||r.designMode?"other":"product",stored:u?.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(!h(i))return;const s=zn(i.look);return s&&{stored:!0===i.stored,look:s}}(r.proxyBase,a,t),keep(t){c.keepLook(t)}}));const m=In(r.assistantLabel),g=Bn({template:r.template,searchTerms:r.searchTerms,assistantLabel:r.assistantLabel,entrance:p}),y=Rn(r.cards);await l;const{page:v}=Vr({kit:y,renderers:cn(y),session:c});Object.assign(v,{style:f,embed:{header:m,stage:g,...y.stats}});const w=o("sessionStorage",Hr);i("sessionStorage",Hr),void 0!==w&&""!==w.trim()&&v.ask(w)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Jr()},{once:!0}):Jr()}();
|
|
22
22
|
//# sourceMappingURL=callimacus.min.js.map
|