@occluze/tether 0.6.1 → 0.6.3

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.
Files changed (43) hide show
  1. package/README.md +15 -1
  2. package/dist/esm/astro.js +2 -2
  3. package/dist/esm/chunks/account-NVHPA7AX.js +1 -0
  4. package/dist/esm/chunks/{analytics-22NMIVBV.js → analytics-SLATWPLC.js} +1 -1
  5. package/dist/esm/chunks/{chunk-YZMBXS6Y.js → chunk-64TUD3QR.js} +1 -1
  6. package/dist/esm/chunks/{chunk-YXCXIPQV.js → chunk-AJLPU2JC.js} +1 -1
  7. package/dist/esm/chunks/{chunk-ZVUPVSLF.js → chunk-FIOZPPC5.js} +1 -1
  8. package/dist/esm/chunks/chunk-K2YEQAIH.js +1 -0
  9. package/dist/esm/chunks/chunk-L2TRRKYV.js +1 -0
  10. package/dist/esm/chunks/{chunk-4UR45XTC.js → chunk-RREHGH4A.js} +1 -1
  11. package/dist/esm/chunks/chunk-VCPI7MJ2.js +1 -0
  12. package/dist/esm/chunks/{chunk-6R752OYZ.js → chunk-ZIUIWEON.js} +1 -1
  13. package/dist/esm/chunks/diagnose-4JHU6RTC.js +11 -0
  14. package/dist/esm/chunks/{extras-QDCSW6VU.js → extras-R4X34VQL.js} +1 -1
  15. package/dist/esm/chunks/{markets-ui-HJCVLCKJ.js → markets-ui-F3R5T5EL.js} +1 -1
  16. package/dist/esm/chunks/{search-LN2H6SXS.js → search-NILMGYXG.js} +1 -1
  17. package/dist/esm/index.js +1 -1
  18. package/dist/esm/server.js +1 -1
  19. package/dist/tether.account.js +28 -2
  20. package/dist/tether.account.min.js +1 -1
  21. package/dist/tether.diagnose.js +139 -40
  22. package/dist/tether.diagnose.min.js +11 -1
  23. package/dist/tether.js +31 -9
  24. package/dist/tether.min.js +2 -2
  25. package/dist/tether.min.js.map +3 -3
  26. package/package.json +1 -1
  27. package/src/account.js +25 -4
  28. package/src/astro.js +29 -4
  29. package/src/cart.js +15 -2
  30. package/src/client.js +12 -3
  31. package/src/collection.js +5 -1
  32. package/src/config.js +1 -1
  33. package/src/diagnose.js +79 -20
  34. package/src/dom.js +2 -1
  35. package/src/index.js +1 -1
  36. package/src/server.js +7 -6
  37. package/types/astro.d.ts +2 -0
  38. package/types/server.d.ts +16 -8
  39. package/dist/esm/chunks/account-JBZJN7X7.js +0 -1
  40. package/dist/esm/chunks/chunk-BGIKQY6H.js +0 -1
  41. package/dist/esm/chunks/chunk-CISGFYOF.js +0 -1
  42. package/dist/esm/chunks/chunk-KARKXC6G.js +0 -1
  43. package/dist/esm/chunks/diagnose-6ZSK5DGE.js +0 -1
package/README.md CHANGED
@@ -25,6 +25,20 @@ MIT licensed · 20 KB gzipped · no dependencies · TypeScript types · [full re
25
25
 
26
26
  ---
27
27
 
28
+ ## Three ways to install
29
+
30
+ | | Pick it when | How |
31
+ |---|---|---|
32
+ | **Script tag** (jsDelivr) | a static site or Webflow, no build step, no login needed | `<script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.6/dist/tether.min.js" defer></script>` ([steps below](#2-add-the-script-to-webflow)) |
33
+ | **npm** | Astro, Vite or another bundler or framework | `npm install @occluze/tether` ([Astro guide](docs/astro.md), [other frameworks](docs/frameworks.md)) |
34
+ | **With the Worker** | you also want the CMS sync, rebuilds when products change, or secure customer accounts | either of the above, plus your own free Cloudflare Worker ([Worker](server/README.md), [accounts](docs/accounts.md)) |
35
+
36
+ The script tag pinned to one release: `…/tether@v0.6.3/dist/tether.min.js`. Its optional parts
37
+ (search, accounts, markets, analytics) load from the same folder when a page uses them; host the
38
+ files yourself and set `partsUrl` if they live somewhere else. Customer accounts without the Worker
39
+ run in browser mode; [server mode](docs/accounts.md#server-mode) (recommended for live shops)
40
+ needs the Worker.
41
+
28
42
  ## 1. Connect Shopify (5 minutes)
29
43
 
30
44
  1. Shopify admin → install the free **Headless** channel → Create storefront → copy the
@@ -50,7 +64,7 @@ Site settings → Custom code → **Head**:
50
64
  <script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.6/dist/tether.min.js" defer></script>
51
65
  ```
52
66
 
53
- **Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.1` pins one release,
67
+ **Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.3` pins one release,
54
68
  `@latest` always takes the newest. Hosting the file yourself? Put the optional parts next to it (`tether.markets.min.js`,
55
69
  `tether.search.min.js`, `tether.account.min.js`, `tether.analytics.min.js`, `tether.extras.min.js`,
56
70
  `tether.diagnose.min.js`): each loads only when a page uses it.
package/dist/esm/astro.js CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunks/chunk-VC46IEJQ.js";var I={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};async function _(O,f){let e=O==="dev"?"development":"production",o={};try{let{readFile:T}=await import("node:fs/promises"),{join:i}=await import("node:path");for(let c of[".env",".env.local",`.env.${e}`,`.env.${e}.local`]){let r;try{r=await T(i(f,c),"utf8")}catch{continue}for(let a of r.split(/\r?\n/)){let n=/^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*?)\s*$/.exec(a);if(!n||a.trim().startsWith("#"))continue;let t=n[2],s=/^(["'])(.*?)\1/.exec(t);t=s?s[2]:t.replace(/\s+#.*$/,""),o[n[1]]=t}}}catch{}return{...o,...process.env}}function d(O={}){let{inject:f=!0,...e}=O;return{name:"@occluze/tether",hooks:{"astro:config:setup":async({injectScript:o,command:T,config:i,logger:c})=>{let r=i?.root?decodeURIComponent(new URL(i.root).pathname):process.cwd(),a=await _(T,r);for(let[t,s]of Object.entries(I))e[t]||(e[t]=s.map(u=>a[u]).find(Boolean));let n=Object.entries(e).filter(([,t])=>typeof t=="function").map(([t])=>t);n.forEach(t=>delete e[t]),n.length&&c.warn(`${n.join(", ")}: functions can't be passed here. Set them in window.TETHER_CONFIG in your layout.`),(!e.domain||!e.token)&&c.warn("No Shopify store configured: set PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN in .env (the public Storefront API token)."),f&&(o("head-inline",'window.TETHER_INTEGRATION="astro";'),o("page",["import Tether from '@occluze/tether';",`window.TETHER_CONFIG = { ...${JSON.stringify({autoMount:!1,...e})}, ...(window.TETHER_CONFIG || {}) };`,"Tether.init().then(() => Tether.mount(document));"].join(`
2
- `)))}}}}export{d as default};
1
+ import"./chunks/chunk-VC46IEJQ.js";var l={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};function T(a,o=process.argv){let n=o.findIndex(t=>t==="--mode"||t.startsWith("--mode="));return n>=0?o[n].includes("=")?o[n].split("=")[1]:o[n+1]:a==="dev"?"development":"production"}async function m(a,o){let n=T(a),t={};try{let{readFile:I}=await import("node:fs/promises"),{join:p}=await import("node:path");for(let u of[".env",".env.local",`.env.${n}`,`.env.${n}.local`]){let f;try{f=await I(p(o,u),"utf8")}catch{continue}for(let O of f.split(/\r?\n/)){let s=/^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*?)\s*$/.exec(O);if(!s||O.trim().startsWith("#"))continue;let i=s[2],_=/^(["'])(.*?)\1/.exec(i);i=_?_[2]:i.replace(/\s+#.*$/,""),t[s[1]]=i}}}catch{}return{...t,...process.env}}function h(a={}){let{inject:o=!0,watch:n=["src/shop.config.js","src/shop.config.mjs","src/shop.config.ts"],...t}=a;return{name:"@occluze/tether",hooks:{"astro:config:setup":async({injectScript:I,command:p,config:u,logger:f,addWatchFile:O,updateConfig:s})=>{let i=u?.root?decodeURIComponent(new URL(u.root).pathname):process.cwd();if(p==="dev"&&O){let{existsSync:e}=await import("node:fs"),{resolve:r}=await import("node:path");[].concat(n||[]).map(c=>r(i,c)).filter(c=>e(c)).forEach(c=>O(c))}if(s)try{let{envField:e}=await import("astro/config");if(e){let r=()=>e.string({context:"client",access:"public",optional:!0});s({env:{schema:{PUBLIC_SHOPIFY_DOMAIN:r(),PUBLIC_SHOPIFY_STOREFRONT_TOKEN:r()}}})}}catch{}let _=await m(p,i);for(let[e,r]of Object.entries(l))t[e]||(t[e]=r.map(c=>_[c]).find(Boolean));let d=Object.entries(t).filter(([,e])=>typeof e=="function").map(([e])=>e);d.forEach(e=>delete t[e]),d.length&&f.warn(`${d.join(", ")}: functions can't be passed here. Set them in window.TETHER_CONFIG in your layout.`),(!t.domain||!t.token)&&f.warn("No Shopify store configured: set PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN in .env (the public Storefront API token)."),o&&(I("head-inline",'window.TETHER_INTEGRATION="astro";'),I("page",["import Tether from '@occluze/tether';",`window.TETHER_CONFIG = { ...${JSON.stringify({autoMount:!1,...t})}, ...(window.TETHER_CONFIG || {}) };`,"Tether.init().then(() => Tether.mount(document));"].join(`
2
+ `)))}}}}export{h as default};
@@ -0,0 +1 @@
1
+ import{b as f}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{A as R,B as x,D as E,G as j,b as a,e as W,g as I,h as S,o as m,p as k,s as _,u as A,w as X}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var O=()=>`${a.prefix}:account:${a.domain}`,G=()=>`${a.prefix}:account-login:${a.domain}`,D=()=>a.account?.remember?window.localStorage:window.sessionStorage,Z=t=>btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=()=>Z(crypto.getRandomValues(new Uint8Array(32))),at=async t=>Z(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),N=t=>(a.account?.navigate||(e=>window.location.assign(e)))(t),M=(t,e)=>{try{return JSON.parse(t.getItem(e)||"null")}catch{return null}},L=(t,e,n)=>{try{n?t.setItem(e,JSON.stringify(n)):t.removeItem(e)}catch{}},C=null,c=null,J=null,U=null,g=()=>a.account?.server?new URL(String(a.account.server),window.location.href).href.replace(/\/$/,""):"",z=()=>`${a.prefix}:account-hint:${a.domain}`,$=null;async function q(t,{method:e="GET",body:n}={}){let o=await fetch(`${g()}${t}`,{method:e,credentials:"include",headers:e==="POST"?{"Content-Type":"application/json","X-Tether-Account":"1"}:{},body:n?JSON.stringify(n):void 0}),s=await o.json().catch(()=>({}));if(!o.ok&&o.status!==401)throw new S(`Customer accounts: ${s.error||o.status}`,{status:o.status});return s}async function H(){$||($=await q("/me"));try{$.loggedIn?window.localStorage.setItem(z(),"1"):window.localStorage.removeItem(z())}catch{}return $}async function P(){if(C)return C;let t=a.account?.shopDomain||a.domain,e=s=>fetch(`https://${t}/.well-known/${s}`).then(r=>{if(!r.ok)throw new S(`Customer accounts: ${s} answered ${r.status}`,{status:r.status});return r.json()}),[n,o]=await Promise.all([e("openid-configuration"),e("customer-account-api")]);return C={...n,graphql:o.graphql_api},C}var st=()=>a.account?.callbackUrl||`${window.location.origin}${window.location.pathname}`;function tt(){return g()?!!$?.loggedIn:!!(c?.refresh||c?.access&&c.expiresAt>Date.now())}async function ct({returnTo:t=window.location.href,locale:e}={}){if(g()){let d=new URL(`${g()}/login`);d.searchParams.set("returnTo",t);let h=e||a.account.locale||(a.locale||"").split("-")[0];h&&d.searchParams.set("locale",h),a.country&&d.searchParams.set("country",String(a.country).toUpperCase()),N(d.toString());return}if(!a.account?.clientId)throw new S("Customer accounts: set account.clientId",{code:"NOT_CONFIGURED"});let n=await P(),o=B(),s=B(),r=B(),u=st();L(window.sessionStorage,G(),{state:o,nonce:s,verifier:r,redirect:u,returnTo:t,at:Date.now()});let i=new URL(n.authorization_endpoint),w={client_id:a.account.clientId,scope:"openid email customer-account-api:full",response_type:"code",redirect_uri:u,state:o,nonce:s,code_challenge:await at(r),code_challenge_method:"S256"},l=e||a.account.locale||(a.locale||"").split("-")[0];l&&(w.locale=l),a.country&&(w.region_country=String(a.country).toUpperCase()),Object.entries(w).forEach(([d,h])=>i.searchParams.set(d,h)),N(i.toString())}async function et(t){let e=await P(),n=await fetch(a.account.tokenUrl||e.token_endpoint,{method:"POST",body:new URLSearchParams(t)}),o=await n.json().catch(()=>({}));if(!n.ok||!o.access_token)throw new S(`Customer accounts: token ${n.status} ${o.error||""}`.trim(),{status:n.status,code:n.status===400||n.status===401?"SESSION_ENDED":"TOKEN_FAILED"});return o}function it(t){try{return JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function nt(t,e=c){c={access:t.access_token,expiresAt:Date.now()+Math.max(0,(Number(t.expires_in)||3600)-120)*1e3,refresh:t.refresh_token||e?.refresh,idToken:t.id_token||e?.idToken},L(D(),O(),c)}async function lt(){let t=new URLSearchParams(window.location.search),e=M(window.sessionStorage,G());if(!e||!t.has("code")&&!t.has("error")||t.get("state")!==e.state)return!1;L(window.sessionStorage,G(),null);let n=new URL(window.location.href);if(["code","state","iss","error","error_description"].forEach(w=>n.searchParams.delete(w)),window.history.replaceState(window.history.state,"",n),t.has("error"))return A("account-error",{error:t.get("error")}),!1;if(Date.now()-e.at>10*6e4)throw new S("Customer accounts: the login took too long, please try again");let o=await et({grant_type:"authorization_code",client_id:a.account.clientId,redirect_uri:e.redirect,code:t.get("code"),code_verifier:e.verifier}),s=await P(),r=it(o.id_token||""),u=[].concat(r?.aud||[]);if(!r||r.nonce!==e.nonce||r.iss!==s.issuer||!u.includes(a.account.clientId)||r.exp*1e3<Date.now())throw new S("Customer accounts: the login answer did not check out (nonce/issuer/audience)");nt(o,null),await ot(),A("account-login",{});let i=e.returnTo&&new URL(e.returnTo,window.location.href);return i&&i.origin===window.location.origin&&i.href!==n.href&&N(i.href),!0}async function v(){return g()||(c||(c=M(D(),O())),!c)?null:c.access&&c.expiresAt>Date.now()?c.access:c.refresh?(J||(J=(async()=>{try{nt(await et({grant_type:"refresh_token",client_id:a.account.clientId,refresh_token:c.refresh})),await ot()}catch(t){if(t.code==="SESSION_ENDED")F();else throw t}finally{J=null}})()),await J,c?.access||null):(F(),null)}function F(){c=null,U=null,L(D(),O(),null),f.customerAccessToken=null}async function ot(){f.customerAccessToken=c?.access||null,f.id()&&c?.access&&await f.setBuyerIdentity({customerAccessToken:c.access},{create:!1}).catch(t=>I(t,"account cart"))}async function rt(t,e={}){if(g())throw new S("Customer accounts in server mode only answer customer() and orders()",{code:"NOT_ALLOWED"});let n=await v();if(!n)throw new S("Not logged in",{code:"NOT_LOGGED_IN"});let o=await P(),s=i=>fetch(o.graphql,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:JSON.stringify({query:t,variables:e})}),r=await s(n);r.status===401&&c?.refresh&&(c.expiresAt=0,r=await s(await v()));let u=await r.json().catch(()=>({}));if(!r.ok||u.errors?.length)throw new S(u.errors?.map(i=>i.message).join(" | ")||`Customer accounts: ${r.status}`,{status:r.status});return u.data}async function ut(){if(g()){let e=await H();return e.loggedIn?{...e.customer,emailAddress:{emailAddress:e.customer.email},defaultAddress:{formatted:e.customer.address}}:null}return U||(U=(await rt("query TetherCustomer{customer{id firstName lastName displayName emailAddress{emailAddress}defaultAddress{formatted}}}")).customer,U)}async function dt({first:t=10}={}){return g()?(await q(`/orders?first=${t}`)).orders||[]:(await rt("query TetherOrders($first:Int!){customer{orders(first:$first,sortKey:PROCESSED_AT,reverse:true){nodes{id name processedAt financialStatus fulfillmentStatus statusPageUrl totalPrice{amount currencyCode}lineItems(first:20){nodes{title variantTitle quantity image{url altText}}}}}}}",{first:t})).customer?.orders?.nodes||[]}async function ft({returnTo:t=a.account?.logoutUrl||`${window.location.origin}/`}={}){if(g()){let s=await q("/logout",{method:"POST",body:{returnTo:t,cartId:f.id()}});$={loggedIn:!1};try{window.localStorage.removeItem(z())}catch{}A("account-logout",{}),s.logoutUrl?N(s.logoutUrl):K(document);return}let e=c?.idToken||M(D(),O())?.idToken;if(f.id()&&await f.setBuyerIdentity({customerAccessToken:null},{create:!1}).catch(()=>{}),F(),A("account-logout",{}),!e){K(document);return}let n=await P(),o=new URL(n.end_session_endpoint);o.searchParams.set("id_token_hint",e),o.searchParams.set("post_logout_redirect_uri",t),N(o.toString())}var Y=t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},wt=t=>{try{return new Date(t).toLocaleDateString(a.locale||void 0)}catch{return t}};async function K(t=document){let e=g()?!!(await H().catch(()=>({loggedIn:!1}))).loggedIn:tt()||!!await v().catch(()=>null);if(_(t,m("show")).forEach(s=>{let r=k(s,"show");r==="logged-in"&&E(s,e),r==="logged-out"&&E(s,!e)}),!e)return;let n=_(t,m("account-bind"));if(n.length){let s=await ut().catch(r=>(I(r,"account"),null));n.forEach(r=>{let u={"first-name":s?.firstName,"last-name":s?.lastName,name:s?.displayName,email:s?.emailAddress?.emailAddress,address:s?.defaultAddress?.formatted?.join(", ")}[k(r,"account-bind")];u!=null&&x(r,u)})}let o=_(t,m("orders"));if(o.length){let s=(i,w)=>_(t,m("show")).forEach(l=>{let d=k(l,"show");d==="orders-loading"&&E(l,i),d==="orders-empty"&&E(l,w)});s(!0,!1);let r=!1,u=await dt({first:parseInt(k(o[0],"limit")||"10",10)}).catch(i=>(I(i,"orders"),r=!0,[]));s(!1,!r&&u.length===0),o.forEach(i=>j(i,u,(w,l)=>{let d=l.lineItems?.nodes||[];_(w,m("order-bind")).forEach(h=>{let T=k(h,"order-bind");if(T==="url"){Y(l.statusPageUrl)&&h.setAttribute("href",l.statusPageUrl);return}if(T==="image"){let y=d.find(b=>b.image)?.image;y&&R(h,y.url,y.altText||d[0]?.title||"");return}let p={name:l.name,date:wt(l.processedAt),total:X(l.totalPrice),status:l.financialStatus?.toLowerCase(),fulfillment:l.fulfillmentStatus?.toLowerCase(),items:d.map(y=>`${y.quantity}\xD7 ${y.title}`).join(", ")}[T];p!=null&&x(h,p)}),_(w,m("order-lines")).forEach(h=>j(h,d,(T,p)=>{_(T,m("order-line")).concat(T.matches(m("order-line"))?[T]:[]).forEach(y=>{let b=k(y,"order-line");if(b==="image"){p.image&&R(y,p.image.url,p.image.altText||p.title);return}let V={title:p.title,"variant-title":p.variantTitle||"",quantity:String(p.quantity)}[b];V!=null&&x(y,V)})})),k(w,"order-bind")==="url"&&Y(l.statusPageUrl)&&w.setAttribute("href",l.statusPageUrl)}))}}var Q=!1;async function yt(t=document){if(!Q){if(Q=!0,document.addEventListener("click",e=>{let n=e.target;n.closest?.(m("account-login"))?(e.preventDefault(),ct().catch(o=>I(o,"login"))):n.closest?.(m("account-logout"))&&(e.preventDefault(),ft().catch(o=>I(o,"logout")))}),g()){let e=new URL(window.location.href);e.searchParams.get("account")&&(e.searchParams.delete("account"),window.history.replaceState(window.history.state,"",e),A("account-login",{})),f.beforeCheckout=async()=>{if(!(await H()).loggedIn||!f.id())return null;let n=await q("/cart",{method:"POST",body:{cartId:f.id()}}).catch(()=>null);return n?.checkoutUrl?`${n.checkoutUrl}${n.checkoutUrl.includes("?")?"&":"?"}logged_in=true`:null}}else{try{await lt()}catch(e){I(e,"login")}!f.customerAccessToken&&await v().catch(()=>null)&&(f.customerAccessToken=c.access)}W("account",tt()?"logged in":"logged out")}await K(t)}export{ut as customer,v as getToken,lt as handleCallback,tt as isLoggedIn,ct as login,ft as logout,yt as mountAccount,dt as orders,rt as query,K as render};
@@ -1 +1 @@
1
- import{b}from"./chunk-BGIKQY6H.js";import"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{b as s,e as T,g as m,l as x,o as g}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var j=n=>n?parseFloat(n.amount):0,L=n=>String(n||"").split("/").pop();function S(n,t,e=1,o){return{item_id:t?.sku||L(t?.id)||L(n.id),item_name:n.title,item_variant:t?.title==="Default Title"?void 0:t?.title,item_brand:n.vendor||void 0,item_category:n.productType||void 0,price:j(t?.price||n.priceRange?.minVariantPrice),quantity:e,...o!=null?{index:o}:{}}}function v(n,t=n.quantity){let e=n.merchandise||{};return S({...e.product||{},title:e.product?.title},e,t)}var w=n=>Math.round(n.reduce((t,e)=>t+(e.price||0)*(e.quantity||1),0)*100)/100;function F(n,t){let e=typeof s.analytics.dataLayer=="string"?s.analytics.dataLayer:"dataLayer",o=window[e]=window[e]||[];t&&o.push({ecommerce:null}),o.push(t?{event:n,ecommerce:t}:{event:n})}var p=null;function V(n){let t=[],e=[],o=()=>window.Shopify?.customerPrivacy,a=()=>{try{let i=o();return i?.consentStatus==="loaded"&&i.currentVisitorConsent?.()?.analytics!=="no"&&!!i.analyticsProcessingAllowed?.()}catch{return!1}},c={shop:{shopId:n,channel:"headless"},consent:{mode:s.analytics.shopify?.consent||"no-banner"}},d=()=>{a()&&t.forEach(i=>{for(;i.next<e.length;){let{event:l,payload:u}=e[i.next++];(i.subs.get(l)||[]).forEach(_=>{try{_(u,i.context)}catch(r){m(r,`analytics ${i.name}`)}})}})},f={getConfig:()=>c,publish(i,l={}){e.push({event:i,payload:{shop:c.shop,url:window.location.href,...l}}),e.length>500&&(e.shift(),t.forEach(u=>{u.next=Math.max(0,u.next-1)})),d()},addDestination(i){let l=`hydrogen:${i.name}`,u={name:i.name,next:0,subs:new Map,context:{getTrackingValues:()=>{let r=a()?o()?.__internal:null;return{uniqueToken:r?.uniqueToken?.({generateFallback:!0,tag:l})??"",visitToken:r?.visitToken?.({generateFallback:!0,tag:l})??""}}}},_=(r,C)=>(u.subs.has(r)||u.subs.set(r,new Set),u.subs.get(r).add(C),()=>u.subs.get(r)?.delete(C));return Promise.resolve(i.setup?.({subscribe:_,getConfig:f.getConfig})).then(()=>{t.push(u),d()}).catch(r=>m(r,`analytics ${i.name}`)),()=>{let r=t.indexOf(u);r>=0&&t.splice(r,1)}}};return document.addEventListener("consentTrackingApiLoaded",d),document.addEventListener("visitorConsentCollected",d),f}function q(n){let t=document.createElement("script");t.src=n,t.async=!0,document.head.appendChild(t)}async function D(){if(window.Shopify?.analytics){p=window.Shopify.analytics;return}let n=await x("query TetherShopId { shop { id } }",{},{context:!1}),t=String(s.country||"US").toUpperCase(),e=window.Shopify=window.Shopify||{};Object.assign(e,{country:t,locale:(s.locale||"en").split("-")[0].toLowerCase(),shop:s.domain,routes:{root:"/",match:()=>({pageTemplateName:$()?"product":"page"}),...e.routes||{}}});let o=s.analytics.shopify?.proxy;e.customerPrivacy={...e.customerPrivacy||{},config:o?{isHeadless:!0,asyncConsent:!0,asyncVisitorState:!0,consentDomain:window.location.host}:{isHeadless:!0,storefrontAccessToken:s.token,checkoutRootDomain:s.domain}},p=V(n.shop.id),e.analytics=p,q(s.analytics.shopify?.consent==="default-banner"?"https://cdn.shopify.com/shopifycloud/privacy-banner/storefront-banner.js":"https://cdn.shopify.com/shopifycloud/consent-tracking-api/v0.2/consent-tracking-api.js"),q("https://cdn.shopify.com/storefront/analytics/shopify.js"),T("shopify analytics ready",n.shop.id)}var M=(n,t,e=1)=>({id:n.id,title:n.title,price:t.price,vendor:n.vendor||"",variantId:t.id,variantTitle:t.title,quantity:e,sku:t.sku||void 0,productType:n.productType||void 0});function E(n){let t=n.merchandise||{};return{id:n.id,quantity:n.quantity,merchandise:{id:t.id,title:t.title,price:t.price,sku:t.sku,product:{id:t.product?.id,title:t.product?.title,vendor:t.product?.vendor||"",handle:t.product?.handle}}}}function $(){let n=document.querySelector(g("product"));return n&&!n.closest(`${g("collection")},${g("products")},${g("recommendations")}`)?window.Tether?.getScope(n):null}var y=(n,t,e,o)=>{s.analytics.dataLayer&&F(n,t),p&&e&&p.publish(e,o);try{s.analytics.onEvent?.(n,t)}catch(a){m(a,"analytics onEvent")}},h=null,k=new WeakSet;function P(n){let t=n.type.slice(s.prefix.length+1),e=n.detail||{};if(t==="product-ready"){let o=e.scope;if(!o||k.has(o.root)||$()!==o)return;k.add(o.root);let a=o.variant||e.product.variants.nodes[0],c=[S(e.product,a)];y("view_item",{currency:a?.price?.currencyCode,value:w(c),items:c},"product_viewed",{products:[M(e.product,a)]})}else if(t==="list-ready"){let o=(e.products||[]).slice(0,200).map((c,d)=>S(c,c.variants?.nodes?.[0],1,d)),a={item_list_id:e.collection?.handle||"products",item_list_name:e.collection?.title||"Products"};y("view_item_list",{...a,items:o},e.collection?"collection_viewed":null,e.collection?{collection:{id:e.collection.id,handle:e.collection.handle}}:null)}else if(t==="cart-updated"){let o=e.cart,a=new Map((o?.lines?.nodes||[]).map(c=>[c.merchandise?.id,c]));if(h&&e.reason!=="load"&&e.reason!=="pending"){let c=o?.cost?.totalAmount?.currencyCode;a.forEach((d,f)=>{let i=d.quantity-(h.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("add_to_cart",{currency:c,value:w(l),items:l},"product_added_to_cart",{cart:o,prevCart:A,currentLine:E(d),prevLine:h.get(f)?E(h.get(f)):void 0})}}),h.forEach((d,f)=>{let i=d.quantity-(a.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("remove_from_cart",{currency:c,value:w(l),items:l})}})}h=a,A=o}else if(t==="cart-toggled"&&e.open){let o=b.lines.map(a=>v(a));y("view_cart",{currency:b.state?.cost?.totalAmount?.currencyCode,value:w(o),items:o})}else if(t==="checkout"){let o=(e.cart?.lines?.nodes||[]).map(c=>v(c)),a=(e.cart?.discountCodes||[]).filter(c=>c.applicable).map(c=>c.code).join(",")||void 0;y("begin_checkout",{currency:e.cart?.cost?.totalAmount?.currencyCode,value:w(o),coupon:a,items:o})}else t==="search"&&e.term?y("search",{search_term:e.term},"search_viewed",{searchTerm:e.term}):t==="page"&&(k=new WeakSet,p&&p.publish("page_viewed",{}))}var A=null;async function R(n){s.analytics.shopify&&await D().catch(t=>m(t,"shopify analytics")),p&&p.publish("page_viewed",{}),n.splice(0).forEach(P),n.push=t=>(P(t),0)}export{R as startAnalytics};
1
+ import{b}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{b as s,e as T,g as m,l as x,o as g}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var j=n=>n?parseFloat(n.amount):0,L=n=>String(n||"").split("/").pop();function S(n,t,e=1,o){return{item_id:t?.sku||L(t?.id)||L(n.id),item_name:n.title,item_variant:t?.title==="Default Title"?void 0:t?.title,item_brand:n.vendor||void 0,item_category:n.productType||void 0,price:j(t?.price||n.priceRange?.minVariantPrice),quantity:e,...o!=null?{index:o}:{}}}function v(n,t=n.quantity){let e=n.merchandise||{};return S({...e.product||{},title:e.product?.title},e,t)}var w=n=>Math.round(n.reduce((t,e)=>t+(e.price||0)*(e.quantity||1),0)*100)/100;function F(n,t){let e=typeof s.analytics.dataLayer=="string"?s.analytics.dataLayer:"dataLayer",o=window[e]=window[e]||[];t&&o.push({ecommerce:null}),o.push(t?{event:n,ecommerce:t}:{event:n})}var p=null;function V(n){let t=[],e=[],o=()=>window.Shopify?.customerPrivacy,a=()=>{try{let i=o();return i?.consentStatus==="loaded"&&i.currentVisitorConsent?.()?.analytics!=="no"&&!!i.analyticsProcessingAllowed?.()}catch{return!1}},c={shop:{shopId:n,channel:"headless"},consent:{mode:s.analytics.shopify?.consent||"no-banner"}},d=()=>{a()&&t.forEach(i=>{for(;i.next<e.length;){let{event:l,payload:u}=e[i.next++];(i.subs.get(l)||[]).forEach(_=>{try{_(u,i.context)}catch(r){m(r,`analytics ${i.name}`)}})}})},f={getConfig:()=>c,publish(i,l={}){e.push({event:i,payload:{shop:c.shop,url:window.location.href,...l}}),e.length>500&&(e.shift(),t.forEach(u=>{u.next=Math.max(0,u.next-1)})),d()},addDestination(i){let l=`hydrogen:${i.name}`,u={name:i.name,next:0,subs:new Map,context:{getTrackingValues:()=>{let r=a()?o()?.__internal:null;return{uniqueToken:r?.uniqueToken?.({generateFallback:!0,tag:l})??"",visitToken:r?.visitToken?.({generateFallback:!0,tag:l})??""}}}},_=(r,C)=>(u.subs.has(r)||u.subs.set(r,new Set),u.subs.get(r).add(C),()=>u.subs.get(r)?.delete(C));return Promise.resolve(i.setup?.({subscribe:_,getConfig:f.getConfig})).then(()=>{t.push(u),d()}).catch(r=>m(r,`analytics ${i.name}`)),()=>{let r=t.indexOf(u);r>=0&&t.splice(r,1)}}};return document.addEventListener("consentTrackingApiLoaded",d),document.addEventListener("visitorConsentCollected",d),f}function q(n){let t=document.createElement("script");t.src=n,t.async=!0,document.head.appendChild(t)}async function D(){if(window.Shopify?.analytics){p=window.Shopify.analytics;return}let n=await x("query TetherShopId { shop { id } }",{},{context:!1}),t=String(s.country||"US").toUpperCase(),e=window.Shopify=window.Shopify||{};Object.assign(e,{country:t,locale:(s.locale||"en").split("-")[0].toLowerCase(),shop:s.domain,routes:{root:"/",match:()=>({pageTemplateName:$()?"product":"page"}),...e.routes||{}}});let o=s.analytics.shopify?.proxy;e.customerPrivacy={...e.customerPrivacy||{},config:o?{isHeadless:!0,asyncConsent:!0,asyncVisitorState:!0,consentDomain:window.location.host}:{isHeadless:!0,storefrontAccessToken:s.token,checkoutRootDomain:s.domain}},p=V(n.shop.id),e.analytics=p,q(s.analytics.shopify?.consent==="default-banner"?"https://cdn.shopify.com/shopifycloud/privacy-banner/storefront-banner.js":"https://cdn.shopify.com/shopifycloud/consent-tracking-api/v0.2/consent-tracking-api.js"),q("https://cdn.shopify.com/storefront/analytics/shopify.js"),T("shopify analytics ready",n.shop.id)}var M=(n,t,e=1)=>({id:n.id,title:n.title,price:t.price,vendor:n.vendor||"",variantId:t.id,variantTitle:t.title,quantity:e,sku:t.sku||void 0,productType:n.productType||void 0});function E(n){let t=n.merchandise||{};return{id:n.id,quantity:n.quantity,merchandise:{id:t.id,title:t.title,price:t.price,sku:t.sku,product:{id:t.product?.id,title:t.product?.title,vendor:t.product?.vendor||"",handle:t.product?.handle}}}}function $(){let n=document.querySelector(g("product"));return n&&!n.closest(`${g("collection")},${g("products")},${g("recommendations")}`)?window.Tether?.getScope(n):null}var y=(n,t,e,o)=>{s.analytics.dataLayer&&F(n,t),p&&e&&p.publish(e,o);try{s.analytics.onEvent?.(n,t)}catch(a){m(a,"analytics onEvent")}},h=null,k=new WeakSet;function P(n){let t=n.type.slice(s.prefix.length+1),e=n.detail||{};if(t==="product-ready"){let o=e.scope;if(!o||k.has(o.root)||$()!==o)return;k.add(o.root);let a=o.variant||e.product.variants.nodes[0],c=[S(e.product,a)];y("view_item",{currency:a?.price?.currencyCode,value:w(c),items:c},"product_viewed",{products:[M(e.product,a)]})}else if(t==="list-ready"){let o=(e.products||[]).slice(0,200).map((c,d)=>S(c,c.variants?.nodes?.[0],1,d)),a={item_list_id:e.collection?.handle||"products",item_list_name:e.collection?.title||"Products"};y("view_item_list",{...a,items:o},e.collection?"collection_viewed":null,e.collection?{collection:{id:e.collection.id,handle:e.collection.handle}}:null)}else if(t==="cart-updated"){let o=e.cart,a=new Map((o?.lines?.nodes||[]).map(c=>[c.merchandise?.id,c]));if(h&&e.reason!=="load"&&e.reason!=="pending"){let c=o?.cost?.totalAmount?.currencyCode;a.forEach((d,f)=>{let i=d.quantity-(h.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("add_to_cart",{currency:c,value:w(l),items:l},"product_added_to_cart",{cart:o,prevCart:A,currentLine:E(d),prevLine:h.get(f)?E(h.get(f)):void 0})}}),h.forEach((d,f)=>{let i=d.quantity-(a.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("remove_from_cart",{currency:c,value:w(l),items:l})}})}h=a,A=o}else if(t==="cart-toggled"&&e.open){let o=b.lines.map(a=>v(a));y("view_cart",{currency:b.state?.cost?.totalAmount?.currencyCode,value:w(o),items:o})}else if(t==="checkout"){let o=(e.cart?.lines?.nodes||[]).map(c=>v(c)),a=(e.cart?.discountCodes||[]).filter(c=>c.applicable).map(c=>c.code).join(",")||void 0;y("begin_checkout",{currency:e.cart?.cost?.totalAmount?.currencyCode,value:w(o),coupon:a,items:o})}else t==="search"&&e.term?y("search",{search_term:e.term},"search_viewed",{searchTerm:e.term}):t==="page"&&(k=new WeakSet,p&&p.publish("page_viewed",{}))}var A=null;async function R(n){s.analytics.shopify&&await D().catch(t=>m(t,"shopify analytics")),p&&p.publish("page_viewed",{}),n.splice(0).forEach(P),n.push=t=>(P(t),0)}export{R as startAnalytics};
@@ -1 +1 @@
1
- import{b as c,l as g}from"./chunk-KARKXC6G.js";var p=/^[A-Z]{2}$/,y=new Set(["PT_BR","PT_PT","ZH_CN","ZH_TW"]),d=()=>`${c.prefix}:market:${c.domain}`,h=()=>({document:typeof document<"u"?document:null,location:typeof window<"u"?window.location:null,storage:(()=>{try{return window.localStorage}catch{return null}})(),global:typeof window<"u"?window:{}});function w(t){let e=String(t||"").trim().toUpperCase();return p.test(e)&&e!=="XX"&&e!=="T1"?e:null}function C(t){let e=String(t||"").trim().replace("-","_").toUpperCase();if(!e)return null;if(y.has(e))return e;let n=e.split("_")[0];return/^[A-Z]{2,3}$/.test(n)?n:null}function b(t,e){if(!t||!e)return null;let n=String(t.cookie||"").split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?decodeURIComponent(n.slice(e.length+1)):null}var s=(t,e)=>{if(!t||!e)return null;let n=String(e).toLowerCase(),r=Object.keys(t).find(o=>o.toLowerCase()===n);return r?t[r]:null},T={saved(t,e){if(t.remember===!1||!e.storage)return null;try{return JSON.parse(e.storage.getItem(d())||"null")}catch{return null}},server(t,e){let n=a=>e.document?.querySelector?.(`meta[name="${a}"]`)?.getAttribute("content"),r=e.global.TETHER_COUNTRY||n("tether-country")||b(e.document,t.cookie||"tether_country"),o=e.global.TETHER_LANGUAGE||n("tether-language");return{country:r,language:o}},webflow(t,e){let n=(e.location?.pathname||"/").split("/").filter(Boolean)[0],r=s(t.locales,n);if(r)return r;let o=e.document?.documentElement?.getAttribute("lang");if(!o)return null;let a=s(t.locales,o)||s(t.locales,o.split("-")[0]);if(a)return{locale:o,...a};if(t.locales&&t.strict)return null;let l=o.split("-")[1];return{language:o,country:l&&l.length===2?l:null,locale:o}}};function L(t=c.markets,e=h()){let n=t||{};if(n.detect===!1)return{};let r=n.detect?n.detect===!0?["saved","server","webflow"]:[].concat(n.detect):["saved"];t=n;let o={sources:{}};return r.forEach(a=>{let l=T[a]?.(t,e);if(!l)return;let m={country:w(l.country),language:C(l.language),locale:l.locale||null};Object.entries(m).forEach(([i,f])=>{f&&!o[i]&&(o[i]=f,o.sources[i]=a)})}),o}function _(t){if(c.markets?.remember!==!1)try{localStorage.setItem(d(),JSON.stringify({country:t.country,language:t.language||void 0,locale:t.locale||void 0}))}catch{}}var u=null;function A(){u=null}function x(){return u||(u=g("query TetherLocalization{localization{country{isoCode name currency{isoCode symbol}}language{isoCode name}availableCountries{isoCode name currency{isoCode symbol}availableLanguages{isoCode name}}}}").then(t=>t.localization).catch(t=>{throw u=null,t})),u}export{w as a,C as b,L as c,_ as d,A as e,x as f};
1
+ import{b as c,l as g}from"./chunk-K2YEQAIH.js";var p=/^[A-Z]{2}$/,y=new Set(["PT_BR","PT_PT","ZH_CN","ZH_TW"]),d=()=>`${c.prefix}:market:${c.domain}`,h=()=>({document:typeof document<"u"?document:null,location:typeof window<"u"?window.location:null,storage:(()=>{try{return window.localStorage}catch{return null}})(),global:typeof window<"u"?window:{}});function w(t){let e=String(t||"").trim().toUpperCase();return p.test(e)&&e!=="XX"&&e!=="T1"?e:null}function C(t){let e=String(t||"").trim().replace("-","_").toUpperCase();if(!e)return null;if(y.has(e))return e;let n=e.split("_")[0];return/^[A-Z]{2,3}$/.test(n)?n:null}function b(t,e){if(!t||!e)return null;let n=String(t.cookie||"").split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?decodeURIComponent(n.slice(e.length+1)):null}var s=(t,e)=>{if(!t||!e)return null;let n=String(e).toLowerCase(),r=Object.keys(t).find(o=>o.toLowerCase()===n);return r?t[r]:null},T={saved(t,e){if(t.remember===!1||!e.storage)return null;try{return JSON.parse(e.storage.getItem(d())||"null")}catch{return null}},server(t,e){let n=a=>e.document?.querySelector?.(`meta[name="${a}"]`)?.getAttribute("content"),r=e.global.TETHER_COUNTRY||n("tether-country")||b(e.document,t.cookie||"tether_country"),o=e.global.TETHER_LANGUAGE||n("tether-language");return{country:r,language:o}},webflow(t,e){let n=(e.location?.pathname||"/").split("/").filter(Boolean)[0],r=s(t.locales,n);if(r)return r;let o=e.document?.documentElement?.getAttribute("lang");if(!o)return null;let a=s(t.locales,o)||s(t.locales,o.split("-")[0]);if(a)return{locale:o,...a};if(t.locales&&t.strict)return null;let l=o.split("-")[1];return{language:o,country:l&&l.length===2?l:null,locale:o}}};function L(t=c.markets,e=h()){let n=t||{};if(n.detect===!1)return{};let r=n.detect?n.detect===!0?["saved","server","webflow"]:[].concat(n.detect):["saved"];t=n;let o={sources:{}};return r.forEach(a=>{let l=T[a]?.(t,e);if(!l)return;let m={country:w(l.country),language:C(l.language),locale:l.locale||null};Object.entries(m).forEach(([i,f])=>{f&&!o[i]&&(o[i]=f,o.sources[i]=a)})}),o}function _(t){if(c.markets?.remember!==!1)try{localStorage.setItem(d(),JSON.stringify({country:t.country,language:t.language||void 0,locale:t.locale||void 0}))}catch{}}var u=null;function A(){u=null}function x(){return u||(u=g("query TetherLocalization{localization{country{isoCode name currency{isoCode symbol}}language{isoCode name}availableCountries{isoCode name currency{isoCode symbol}availableLanguages{isoCode name}}}}").then(t=>t.localization).catch(t=>{throw u=null,t})),u}export{w as a,C as b,L as c,_ as d,A as e,x as f};
@@ -1,4 +1,4 @@
1
- import{b as l}from"./chunk-KARKXC6G.js";import{a as P}from"./chunk-VC46IEJQ.js";var i="amount currencyCode",a="url altText width height";function f(e=l){return(e.metafields||[]).map(t=>{if(typeof t=="string"){let n=t.indexOf(".");return{namespace:t.slice(0,n),key:t.slice(n+1)}}return t}).filter(t=>t.namespace&&t.key)}function $(e=l){let t=f(e);return t.length?`metafields(identifiers:[${t.map(r=>`{namespace: ${JSON.stringify(r.namespace)}, key: ${JSON.stringify(r.key)}}`).join(", ")}]){namespace key type value reference{... on MediaImage{image{${a}}}}}`:""}var A=` id name description recurringDeliveries options{name value}priceAdjustments{orderCount adjustmentValue{__typename ... on SellingPlanPercentagePriceAdjustment{adjustmentPercentage}... on SellingPlanFixedAmountPriceAdjustment{adjustmentAmount{${i}}}... on SellingPlanFixedPriceAdjustment{price{${i}}}}}`,y=` sellingPlan{id}checkoutChargeAmount{${i}}remainingBalanceChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}unitPrice{${i}}}`;function k(e=l){return` fragment TetherProduct on Product{id handle title description descriptionHtml productType vendor tags availableForSale publishedAt onlineStoreUrl requiresSellingPlan seo{title description}featuredImage{${a}}images(first:${e.imagesFirst}){nodes{${a}}}options{name optionValues{name swatch{color image{previewImage{${a}}}}}}priceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}compareAtPriceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}${$(e)} sellingPlanGroups(first:${e.sellingPlanGroupsFirst}){nodes{name appName options{name values}sellingPlans(first:${e.sellingPlansFirst}){nodes{${A}}}}}variants(first:${e.variantsFirst}){nodes{id title availableForSale currentlyNotInStock quantityAvailable sku barcode selectedOptions{name value}image{${a}}price{${i}}compareAtPrice{${i}}unitPrice{${i}}sellingPlanAllocations(first:${e.sellingPlansFirst}){nodes{${y}}}}}}`}function I(){return` fragment TetherCart on Cart{id checkoutUrl totalQuantity note createdAt updatedAt attributes{key value}buyerIdentity{countryCode email}discountCodes{code applicable}cost{subtotalAmount{${i}}totalAmount{${i}}checkoutChargeAmount{${i}}}lines(first:100){nodes{id quantity attributes{key value}cost{totalAmount{${i}}subtotalAmount{${i}}amountPerQuantity{${i}}compareAtAmountPerQuantity{${i}}}discountAllocations{discountedAmount{${i}}}sellingPlanAllocation{sellingPlan{id name description recurringDeliveries options{name value}}checkoutChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}}}merchandise{... on ProductVariant{id title sku availableForSale requiresShipping quantityAvailable image{${a}}price{${i}}compareAtPrice{${i}}selectedOptions{name value}product{id title handle vendor featuredImage{${a}}}}}... on ComponentizableCartLine{lineComponents{id quantity merchandise{... on ProductVariant{id title product{title handle}}}}}}}}`}function L(){return`
1
+ import{b as l}from"./chunk-K2YEQAIH.js";import{a as P}from"./chunk-VC46IEJQ.js";var i="amount currencyCode",a="url altText width height";function f(e=l){return(e.metafields||[]).map(t=>{if(typeof t=="string"){let n=t.indexOf(".");return{namespace:t.slice(0,n),key:t.slice(n+1)}}return t}).filter(t=>t.namespace&&t.key)}function $(e=l){let t=f(e);return t.length?`metafields(identifiers:[${t.map(r=>`{namespace: ${JSON.stringify(r.namespace)}, key: ${JSON.stringify(r.key)}}`).join(", ")}]){namespace key type value reference{... on MediaImage{image{${a}}}}}`:""}var A=` id name description recurringDeliveries options{name value}priceAdjustments{orderCount adjustmentValue{__typename ... on SellingPlanPercentagePriceAdjustment{adjustmentPercentage}... on SellingPlanFixedAmountPriceAdjustment{adjustmentAmount{${i}}}... on SellingPlanFixedPriceAdjustment{price{${i}}}}}`,y=` sellingPlan{id}checkoutChargeAmount{${i}}remainingBalanceChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}unitPrice{${i}}}`;function k(e=l){return` fragment TetherProduct on Product{id handle title description descriptionHtml productType vendor tags availableForSale publishedAt onlineStoreUrl requiresSellingPlan seo{title description}featuredImage{${a}}images(first:${e.imagesFirst}){nodes{${a}}}options{name optionValues{name swatch{color image{previewImage{${a}}}}}}priceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}compareAtPriceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}${$(e)} sellingPlanGroups(first:${e.sellingPlanGroupsFirst}){nodes{name appName options{name values}sellingPlans(first:${e.sellingPlansFirst}){nodes{${A}}}}}variants(first:${e.variantsFirst}){nodes{id title availableForSale currentlyNotInStock quantityAvailable sku barcode selectedOptions{name value}image{${a}}price{${i}}compareAtPrice{${i}}unitPrice{${i}}sellingPlanAllocations(first:${e.sellingPlansFirst}){nodes{${y}}}}}}`}function I(){return` fragment TetherCart on Cart{id checkoutUrl totalQuantity note createdAt updatedAt attributes{key value}buyerIdentity{countryCode email}discountCodes{code applicable}cost{subtotalAmount{${i}}totalAmount{${i}}checkoutChargeAmount{${i}}}lines(first:100){nodes{id quantity attributes{key value}cost{totalAmount{${i}}subtotalAmount{${i}}amountPerQuantity{${i}}compareAtAmountPerQuantity{${i}}}discountAllocations{discountedAmount{${i}}}sellingPlanAllocation{sellingPlan{id name description recurringDeliveries options{name value}}checkoutChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}}}merchandise{... on ProductVariant{id title sku availableForSale requiresShipping quantityAvailable image{${a}}price{${i}}compareAtPrice{${i}}selectedOptions{name value}product{id title handle vendor featuredImage{${a}}}}}... on ComponentizableCartLine{lineComponents{id quantity merchandise{... on ProductVariant{id title product{title handle}}}}}}}}`}function L(){return`
2
2
  id handle title description descriptionHtml
3
3
  image { ${a} }
4
4
  seo { title description }`}var j={};P(j,{GID:()=>p,allPlans:()=>u,allocationFor:()=>c,findPlan:()=>C,hasPlans:()=>h,planAdjustment:()=>S,planCheckoutCharge:()=>x,planPrice:()=>m,planSavings:()=>F,plansForVariant:()=>v,toGid:()=>s});var p={product:e=>s(e,"Product"),variant:e=>s(e,"ProductVariant"),sellingPlan:e=>s(e,"SellingPlan")};function s(e,t){let n=String(e??"").trim();return n?n.startsWith("gid://")?n:/^\d+$/.test(n)?`gid://shopify/${t}/${n}`:n:null}function u(e){return(e?.sellingPlanGroups?.nodes||[]).flatMap(n=>(n.sellingPlans?.nodes||[]).map(r=>({...r,group:n})))}function h(e){return u(e).length>0}function c(e,t){return!e||!t?null:(e.sellingPlanAllocations?.nodes||[]).find(n=>n.sellingPlan?.id===t)||null}function v(e,t){return u(e).filter(n=>c(t,n.id))}function m(e,t){let r=c(e,t)?.priceAdjustments?.[0];return r?.perDeliveryPrice||r?.price||e?.price||null}function x(e,t){let n=c(e,t);return n?.checkoutChargeAmount||n?.priceAdjustments?.[0]?.price||e?.price||null}function F(e,t){let n=parseFloat(e?.price?.amount),r=parseFloat(m(e,t)?.amount);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r>=n?{amount:null,percentage:0}:{amount:{amount:(n-r).toFixed(2),currencyCode:e.price.currencyCode},percentage:Math.round((1-r/n)*100)}}function S(e){let t=e?.priceAdjustments?.[0]?.adjustmentValue;if(!t)return null;switch(t.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:t.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"amount",value:t.adjustmentAmount};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:t.price};default:return null}}function C(e,t){if(!t)return null;let n=u(e),r=p.sellingPlan(t),d=String(t).trim().toLowerCase();return n.find(o=>o.id===r)||n.find(o=>o.name.toLowerCase()===d)||n.find(o=>(o.options||[]).some(g=>String(g.value).toLowerCase()===d))||null}export{k as a,I as b,L as c,p as d,u as e,c as f,m as g,x as h,F as i,S as j,C as k,j as l};
@@ -1 +1 @@
1
- import{a as w,c as v}from"./chunk-YXCXIPQV.js";import{b as x,e as K,h as P,l as p}from"./chunk-KARKXC6G.js";var d=new Map,D=[],E=new Map,S=!1,g=0,q=t=>typeof t=="string"&&t.startsWith("gid://");function I(t){let e=String(t??"").trim();if(!e)return null;if(q(e))return e;if(/^\d+$/.test(e))return`gid://shopify/Product/${e}`;let n=e.match(/\/products\/([^/?#]+)/);return n?n[1]:e}function y(t){if(!t)return;let e=Promise.resolve(t);d.set(t.handle,e),d.set(t.id,e)}function F(t){let e=I(t);if(!e)return Promise.reject(new P("empty product key",{code:"NOT_FOUND"}));if(d.has(e))return d.get(e);let n=new Promise((c,i)=>{E.set(e,{resolve:c,reject:i}),D.push(e),S||(S=!0,setTimeout(N,0))});return d.set(e,n),n}async function N(){S=!1;let t=g,e=D.splice(0);if(!e.length)return;let n=e.filter(q),c=e.filter(s=>!q(s)),i=[],a=[],h={};n.length&&(i.push("$ids: [ID!]!"),h.ids=n,a.push("byId: nodes(ids: $ids) { ... on Product { ...TetherProduct } }")),c.forEach((s,o)=>{i.push(`$h${o}: String!`),h[`h${o}`]=s,a.push(`h${o}: product(handle: $h${o}) { ...TetherProduct }`)});let m=`query TetherProducts(${i.join(",")}){${a.join(" ")}}${w()}`;K("fetch products",e);let f=(s,o)=>{let r=E.get(s);E.delete(s),r&&o(r)};try{let s=await p(m,h),o=new Map;(s.byId||[]).forEach(r=>{r&&o.set(r.id,r)}),c.forEach((r,$)=>{s[`h${$}`]&&o.set(r,s[`h${$}`])}),e.forEach(r=>f(r,$=>{if(o.has(r)){let l=o.get(r);t===g&&(y(l),T.set(l.handle,Date.now()),T.set(l.id,Date.now())),$.resolve(l)}else{let l=d.get(r);t===g&&setTimeout(()=>{d.get(r)===l&&d.delete(r)},1e4),$.reject(new P(`Product not found: ${r}`,{code:"NOT_FOUND"}))}}))}catch(s){e.forEach(o=>f(o,r=>{t===g&&d.delete(o),r.reject(s)}))}}function M(){d.clear(),g++,u.clear(),T.clear()}var u=new Set,T=new Map,C=6e4;function b(t){(t||[]).forEach(e=>{!e?.id||!e.handle||Date.now()-(T.get(e.handle)||0)<C&&d.has(e.handle)||(y(e),u.add(e.handle),u.add(e.id))})}function _(t){let e=I(t);if(!u.has(e))return!1;let n=d.get(e);return u.delete(e),n?.then?.(c=>{u.delete(c.handle),u.delete(c.id)}),!0}function U(t){return t.forEach(e=>d.delete(I(e))),t.map(e=>F(e))}async function A({collection:t,query:e,first:n=x.collectionFirst,after:c=null,sortKey:i,reverse:a=!1,filters:h}={}){let m=w();if(t){let s=await p(`query TetherCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${v()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${m}`,{handle:t,first:n,after:c,sortKey:i||void 0,reverse:a,filters:h||void 0});if(!s.collection)throw new P(`Collection not found: ${t}`,{code:"NOT_FOUND"});let{products:o,...r}=s.collection;return o.nodes.forEach(y),{collection:r,products:o.nodes,pageInfo:o.pageInfo}}let f=await p(`query TetherSearch($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${m}`,{first:n,after:c,query:e||void 0,sortKey:i||void 0,reverse:a});return f.products.nodes.forEach(y),{collection:null,products:f.products.nodes,pageInfo:f.products.pageInfo}}async function B(t,e="RELATED"){let n=I(typeof t=="object"?t?.id:t),c=n?.startsWith("gid://"),a=(await p(`query TetherRecs(${c?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${c?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${w()}`,c?{id:n,intent:e}:{handle:n,intent:e})).productRecommendations||[];return a.forEach(y),a}export{I as a,y as b,F as c,M as d,b as e,_ as f,U as g,A as h,B as i};
1
+ import{a as w,c as v}from"./chunk-AJLPU2JC.js";import{b as x,e as K,h as P,l as p}from"./chunk-K2YEQAIH.js";var d=new Map,D=[],E=new Map,S=!1,g=0,q=t=>typeof t=="string"&&t.startsWith("gid://");function I(t){let e=String(t??"").trim();if(!e)return null;if(q(e))return e;if(/^\d+$/.test(e))return`gid://shopify/Product/${e}`;let n=e.match(/\/products\/([^/?#]+)/);return n?n[1]:e}function y(t){if(!t)return;let e=Promise.resolve(t);d.set(t.handle,e),d.set(t.id,e)}function F(t){let e=I(t);if(!e)return Promise.reject(new P("empty product key",{code:"NOT_FOUND"}));if(d.has(e))return d.get(e);let n=new Promise((c,i)=>{E.set(e,{resolve:c,reject:i}),D.push(e),S||(S=!0,setTimeout(N,0))});return d.set(e,n),n}async function N(){S=!1;let t=g,e=D.splice(0);if(!e.length)return;let n=e.filter(q),c=e.filter(s=>!q(s)),i=[],a=[],h={};n.length&&(i.push("$ids: [ID!]!"),h.ids=n,a.push("byId: nodes(ids: $ids) { ... on Product { ...TetherProduct } }")),c.forEach((s,o)=>{i.push(`$h${o}: String!`),h[`h${o}`]=s,a.push(`h${o}: product(handle: $h${o}) { ...TetherProduct }`)});let m=`query TetherProducts(${i.join(",")}){${a.join(" ")}}${w()}`;K("fetch products",e);let f=(s,o)=>{let r=E.get(s);E.delete(s),r&&o(r)};try{let s=await p(m,h),o=new Map;(s.byId||[]).forEach(r=>{r&&o.set(r.id,r)}),c.forEach((r,$)=>{s[`h${$}`]&&o.set(r,s[`h${$}`])}),e.forEach(r=>f(r,$=>{if(o.has(r)){let l=o.get(r);t===g&&(y(l),T.set(l.handle,Date.now()),T.set(l.id,Date.now())),$.resolve(l)}else{let l=d.get(r);t===g&&setTimeout(()=>{d.get(r)===l&&d.delete(r)},1e4),$.reject(new P(`Product not found: ${r}`,{code:"NOT_FOUND"}))}}))}catch(s){e.forEach(o=>f(o,r=>{t===g&&d.delete(o),r.reject(s)}))}}function M(){d.clear(),g++,u.clear(),T.clear()}var u=new Set,T=new Map,C=6e4;function b(t){(t||[]).forEach(e=>{!e?.id||!e.handle||Date.now()-(T.get(e.handle)||0)<C&&d.has(e.handle)||(y(e),u.add(e.handle),u.add(e.id))})}function _(t){let e=I(t);if(!u.has(e))return!1;let n=d.get(e);return u.delete(e),n?.then?.(c=>{u.delete(c.handle),u.delete(c.id)}),!0}function U(t){return t.forEach(e=>d.delete(I(e))),t.map(e=>F(e))}async function A({collection:t,query:e,first:n=x.collectionFirst,after:c=null,sortKey:i,reverse:a=!1,filters:h}={}){let m=w();if(t){let s=await p(`query TetherCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${v()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${m}`,{handle:t,first:n,after:c,sortKey:i||void 0,reverse:a,filters:h||void 0});if(!s.collection)throw new P(`Collection not found: ${t}`,{code:"NOT_FOUND"});let{products:o,...r}=s.collection;return o.nodes.forEach(y),{collection:r,products:o.nodes,pageInfo:o.pageInfo}}let f=await p(`query TetherSearch($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${m}`,{first:n,after:c,query:e||void 0,sortKey:i||void 0,reverse:a});return f.products.nodes.forEach(y),{collection:null,products:f.products.nodes,pageInfo:f.products.pageInfo}}async function B(t,e="RELATED"){let n=I(typeof t=="object"?t?.id:t),c=n?.startsWith("gid://"),a=(await p(`query TetherRecs(${c?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${c?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${w()}`,c?{id:n,intent:e}:{handle:n,intent:e})).productRecommendations||[];return a.forEach(y),a}export{I as a,y as b,F as c,M as d,b as e,_ as f,U as g,A as h,B as i};
@@ -0,0 +1 @@
1
+ var C={domain:"",token:"",apiVersion:"2026-07",country:void 0,language:void 0,locale:void 0,markets:null,prefix:"tether",productPath:"/product",collectionPath:"/collection",metafields:[],imagesFirst:25,variantsFirst:100,sellingPlanGroupsFirst:10,sellingPlansFirst:25,collectionFirst:24,retries:2,revalidate:!0,storageKey:null,cartDrawerOpenClass:"is-open",openCartOnAdd:!0,cartFocus:!0,checkoutTarget:"_self",defaultPurchase:"one-time",variantUrl:!1,maxAge:60,lowStock:5,autoMount:!0,observe:!1,astro:!0,partsUrl:null,formatMoney:null,onLayoutChange:null,onCartOpen:null,onCartClose:null,onLineEnter:null,onLineLeave:null,onValueChange:null,onError:null,debug:!1},n={...C};function _(t={}){return Object.keys(n).forEach(e=>delete n[e]),Object.assign(n,C,t),n.domain&&(n.domain=String(n.domain).replace(/^https?:\/\//,"").replace(/\/.*$/,"")),n.storageKey||(n.storageKey=`${n.prefix}:cart:${n.domain}`),n.apiVersion==="unstable"&&w('apiVersion "unstable" changes without notice. Pin a dated version (e.g. 2026-07).'),n}var G=()=>!!(n.domain&&n.token);function T(...t){n.debug&&console.log(`[${n.prefix}]`,...t)}function w(...t){console.warn(`[${n.prefix}]`,...t)}function B(t,e){if(w(e,t&&(t.message||t.code)?t.message||t.code:t),typeof n.onError=="function")try{n.onError(t,e)}catch{}}var d=class extends Error{constructor(e,{status:r,errors:o,userErrors:a,code:u}={}){super(e),this.name="TetherError",this.code=u||(r?`HTTP_${r}`:"ERROR"),this.status=r,this.errors=o,this.userErrors=a}};function L(t=n){return`https://${t.domain}/api/${t.apiVersion}/graphql.json`}function U(t,e=n){let r=[];if(e.country&&r.push(`country: ${String(e.country).toUpperCase()}`),e.language&&r.push(`language: ${String(e.language).toUpperCase().replace("-","_")}`),!r.length||/@inContext/.test(t))return t;let o=`@inContext(${r.join(", ")})`;return/^\s*\{/.test(t)?`query ${o} ${t.trimStart()}`:t.replace(/^(\s*(?:query|mutation)(?:\s+\w+)?\s*(?:\([^)]*\))?)/,`$1 ${o}`)}var v=t=>new Promise(e=>setTimeout(e,t));function E(t,e){return t===401||t===403?`Shopify rejected the Storefront token for ${e.domain} (${t}): use the public Storefront API token (Headless channel)${/^shpat_/.test(e.token)?", not an Admin API token (shpat_\u2026)":""}`:t===404?`Store or API version not found (404): check domain ${e.domain} and apiVersion ${e.apiVersion}`:`HTTP ${t} from ${e.domain}`}async function k(t,e,r={},{context:o=!0}={}){if(!t.domain||!t.token)throw new d("Tether is not configured: domain and token are required",{code:"NOT_CONFIGURED"});let a=o?U(e,t):e,u=t.maxAge??60;u>0&&!/^\s*mutation\b/.test(a)&&(a+=` #${Math.floor(Date.now()/(u*1e3))}`);let g=JSON.stringify({query:a,variables:r}),l=0;for(;;){let s;try{s=await(t.fetch||fetch)(L(t),{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t.token},body:g})}catch(h){if(l++<t.retries){await v(300*2**l);continue}throw new d(`Network error: ${h.message}`,{code:"NETWORK"})}if(s.status===430)throw new d("Shopify security rejection (430)",{status:430});if((s.status===429||s.status>=500)&&l++<t.retries){T("retry",s.status,l),await v(300*2**l);continue}let c;try{c=await s.json()}catch{throw new d(s.ok?`Invalid response (${s.status})`:E(s.status,t),{status:s.status})}if(c.errors?.length){if(c.errors.some(p=>/quantityAvailable/.test(p.message||""))&&/\bquantityAvailable\b/.test(g))return T("no inventory permission, retrying without quantityAvailable"),k(t,e.replace(/\bquantityAvailable\b/g,""),r,{context:o});if(c.errors.some(p=>/'warnings'/.test(p.message||""))&&/warnings \{ code message target \}/.test(e))return k(t,e.replace(/ warnings \{ code message target \}/g,""),r,{context:o});if(c.errors.some(p=>p.extensions?.code==="THROTTLED")&&l++<t.retries){await v(500*2**l);continue}let m=c.errors.map(p=>p.message).filter(Boolean).join(" | ");throw new d(s.ok?m||"Storefront API error":s.status===401||s.status===403||!m?E(s.status,t):m,{status:s.status,errors:c.errors})}if(!s.ok)throw new d(E(s.status,t),{status:s.status});return c.data}}var z=(t,e,r)=>k(n,t,e,r);function W(t,e){if(!t)throw new d(`${e}: empty response`);let r=t.userErrors||[];if(r.length)throw new d(r.map(o=>o.message).join(" | "),{userErrors:r});return t}var A=t=>`${n.prefix}-${t}`,Z=(t,e)=>e===void 0?`[${A(t)}]`:`[${A(t)}="${e}"]`,F=(t,e)=>t.getAttribute(A(e)),tt=(t,e)=>t.hasAttribute(A(e)),D=()=>`data-${n.prefix}-key`;function et(t,e){let r=n.productPath||"/product";if(!/\{(handle|id)\}/.test(r))return`${r.replace(/\/$/,"")}/${t}`;let o=e?String(e).split("/").pop():"";return r.replace(/\{handle\}/g,encodeURIComponent(t||"")).replace(/\{id\}/g,encodeURIComponent(o))}var I=(t,e)=>t?[...t.querySelectorAll(e)]:[],rt=(t,e,r)=>I(t,e).filter(o=>o.closest(r)===t);function M(t,e,r=document){r.dispatchEvent(new CustomEvent(`${n.prefix}:${t}`,{detail:e,bubbles:!0}))}function nt(t,e=n.locale){if(!t)return"";try{return new Intl.NumberFormat(e||void 0,{style:"percent",maximumFractionDigits:0}).format(t/100)}catch{return`${t}%`}}function ot(t){if(!t)return"";if(typeof n.formatMoney=="function")return n.formatMoney(t,n.locale);let e=parseFloat(t.amount);if(Number.isNaN(e))return"";try{return new Intl.NumberFormat(n.locale||void 0,{style:"currency",currency:t.currencyCode}).format(e)}catch{return`${t.currencyCode} ${e.toFixed(2)}`}}function it(t){if(!t)return"";try{return new Date(t).toLocaleDateString(n.locale||void 0)}catch{return""}}function R(t,{width:e,height:r,crop:o}={}){if(!t)return t;try{let a=new URL(t);return e&&a.searchParams.set("width",String(e)),r&&a.searchParams.set("height",String(r)),o&&a.searchParams.set("crop",o),a.toString()}catch{return t}}function V(t,e){if(!t||!e)return t;let r=o=>e.getAttribute(o)??e.getAttribute(`${n.prefix}-${o}`)??e.getAttribute(`data-${o}`);return R(t,{width:r("max-width"),height:r("max-height"),crop:r("max-width")||r("max-height")?r("crop"):null})}var j=(t,e)=>!!(t&&e)&&t.split("?")[0]===e.split("?")[0];function st(t,e,r){if(!e)return;let o=V(e,t);if(t.tagName==="IMG"&&j(t.getAttribute("src"),o)){r!=null&&!t.getAttribute("alt")&&t.setAttribute("alt",r);return}t.tagName==="IMG"?(t.removeAttribute("srcset"),t.removeAttribute("sizes"),t.setAttribute("src",o),r!=null&&t.setAttribute("alt",r),t.getAttribute("loading")||t.setAttribute("loading","lazy")):t.style.backgroundImage=`url("${o}")`}function K(t,e){let r=e==null?"":String(e);t.tagName==="INPUT"||t.tagName==="TEXTAREA"?t.value=r:t.textContent=r}var N=t=>t.tagName==="INPUT"||t.tagName==="TEXTAREA"?t.value:t.textContent;function at(t,e){let r=N(t);K(t,e);let o=N(t);if(r!==o&&t.dataset.tetherSeen&&typeof n.onValueChange=="function")try{n.onValueChange(t,r)}catch{}t.dataset.tetherSeen="1"}function ut(t,e){let r="tetherPrevDisplay";if(e){if(t.dataset.tetherShown!==void 0)return;t.dataset.tetherShown="",t.removeAttribute("hidden"),t.dataset[r]!==void 0?(t.style.display=t.dataset[r],delete t.dataset[r]):t.style.display==="none"&&(t.style.display=""),typeof getComputedStyle=="function"&&getComputedStyle(t).display==="none"&&(t.style.display=t.getAttribute(`${n.prefix}-display`)||"block")}else delete t.dataset.tetherShown,t.dataset[r]===void 0&&t.style.display!=="none"&&(t.dataset[r]=t.style.display||""),t.style.display="none"}function ct(t,e){t.classList.toggle("is-selected",e),t.setAttribute("aria-pressed",e?"true":"false"),t.tagName==="INPUT"&&(t.type==="radio"||t.type==="checkbox")&&(t.checked=e);let r=t.querySelector?.('input[type="radio"],input[type="checkbox"]');r&&(r.checked=e)}var $=new WeakMap,lt=t=>!!$.get(t);function O(t){if(!$.has(t)){let e=t.firstElementChild?.cloneNode(!0)??null;$.set(t,e),t.innerHTML=""}return $.get(t)}function pt(t,e,r){let o=O(t);if(!o){e.length&&w("repeater without a template child",t);return}t.innerHTML="",e.forEach((a,u)=>{let g=o.cloneNode(!0);r(g,a,u),t.appendChild(g)})}function ft(t,e,r,o,{onEnter:a,onLeave:u}={}){let g=O(t);if(!g){w("repeater without a template child",t);return}let l=D(),s=`data-${n.prefix}-leaving`,S=()=>[...t.children].filter(i=>i.hasAttribute(l)&&!i.hasAttribute(s)),c=new Map(S().map(i=>[i.getAttribute(l),i])),h=[],b=new Set;e.forEach((i,f)=>{let y=String(r(i,f)),x=c.get(y);x?c.delete(y):(x=g.cloneNode(!0),x.setAttribute(l,y),b.add(x)),o(x,i,f,b.has(x)),h.push(x)});let m=h.filter(i=>!b.has(i)),p=S().filter(i=>m.includes(i));if(!(p.length===m.length&&p.every((i,f)=>i===m[f]))){c.forEach(i=>i.remove()),h.forEach(i=>t.appendChild(i));return}h.forEach((i,f)=>{if(!b.has(i))return;let y=h[f-1];if(y&&y.parentNode===t?y.after(i):t.prepend(i),a)try{a(i)}catch{}}),c.forEach(i=>{i.setAttribute(s,""),i.removeAttribute(l),i.style.pointerEvents="none",i.inert=!0;let f=()=>i.remove();if(u)try{u(i,f)}catch{f()}else f()})}var P=null;function q(t){clearTimeout(P),P=setTimeout(()=>{typeof n.onLayoutChange=="function"?n.onLayoutChange(t):window.ScrollTrigger?.refresh&&window.ScrollTrigger.refresh(),M("layout-changed",{reason:t})},120)}function dt(t,e){let r=I(t,"img").filter(u=>!u.complete);if(!r.length)return;let o=r.length,a=()=>{--o===0&&q(`${e}:images`)};r.forEach(u=>{u.addEventListener("load",a,{once:!0}),u.addEventListener("error",a,{once:!0})})}function gt(t,e){return t.getAttribute("aria-busy")==="true"?Promise.resolve():(t.setAttribute("aria-busy","true"),Promise.resolve().then(e).finally(()=>t.removeAttribute("aria-busy")))}function ht(t,e){let r=t&&F(t,e);if(!r)return null;try{return JSON.parse(r)}catch{return w(`invalid JSON in ${A(e)}`,t),null}}function mt(t){return t?Array.isArray(t)?t.map(e=>({key:String(e.key),value:String(e.value??"")})):Object.entries(t).map(([e,r])=>({key:e,value:String(r??"")})):[]}export{C as a,n as b,_ as c,G as d,T as e,w as f,B as g,d as h,L as i,U as j,k,z as l,W as m,A as n,Z as o,F as p,tt as q,et as r,I as s,rt as t,M as u,nt as v,ot as w,it as x,R as y,j as z,st as A,K as B,at as C,ut as D,ct as E,lt as F,pt as G,ft as H,q as I,dt as J,gt as K,ht as L,mt as M};
@@ -0,0 +1 @@
1
+ import{c as Q}from"./chunk-FIOZPPC5.js";import{b as S,d as I,e as B}from"./chunk-AJLPU2JC.js";import{A as M,B as j,C as m,D as L,G as K,H as N,I as R,M as q,b as c,e as O,g as A,h as v,l as $,m as U,n as E,o as u,p as g,r as F,s as l,u as h,w as b}from"./chunk-K2YEQAIH.js";function G(t,e=1,n={}){let a=typeof t=="object"&&t!==null?t:{variantId:t,quantity:e,...n},s=I.variant(a.merchandiseId||a.variantId||a.id);if(!s)throw new v("add(): variantId is required");let r={merchandiseId:s,quantity:Math.max(1,parseInt(a.quantity??1,10)||1)},o=a.sellingPlanId||a.sellingPlan;o&&(r.sellingPlanId=I.sellingPlan(o));let i=q(a.attributes);return i.length&&(r.attributes=i),r}function V(t,e,n){return`mutation Tether_${t}(${e}){${t}(${n}){cart{...TetherCart}userErrors{field message}warnings{code message target}}}${S()}`}var H='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',k=null,W=t=>l(t,H).filter(e=>e.offsetParent!==null||e===document.activeElement);function x(t){l(document,u("cart-open")).forEach(e=>e.setAttribute("aria-expanded",String(t))),l(document,u("cart-drawer")).forEach(e=>{e.hasAttribute("role")||e.setAttribute("role","dialog"),!e.hasAttribute("aria-label")&&!e.hasAttribute("aria-labelledby")&&e.setAttribute("aria-label",g(e,"cart-label")||"Cart"),e.setAttribute("aria-modal",String(t)),e.classList.contains(c.cartDrawerOpenClass)||(e.setAttribute("aria-hidden","true"),c.cartFocus!==!1&&(e.inert=!0))})}var T=t=>/does not exist|not found|invalid id/i.test(t?.message||""),D={state:null,_chain:Promise.resolve(),id(){try{return localStorage.getItem(c.storageKey)}catch{return null}},_setId(t){try{t?localStorage.setItem(c.storageKey,t):localStorage.removeItem(c.storageKey)}catch{}},get lines(){return this.state?.lines?.nodes||[]},get count(){return this.state?.totalQuantity||0},lastError:null,customerAccessToken:null,pendingQty:new Map,warnings:[],loaded:!1,_take(t,e){let n=U(t,e);return this.warnings=(n.warnings||[]).filter((a,s,r)=>r.findIndex(o=>o.message===a.message)===s).map(a=>({...a,message:typeof c.warningText=="function"&&c.warningText(a)||a.message})),this.warnings.length&&h("cart-warning",{warnings:this.warnings}),n.cart},_queue(t){let e=this._chain.then(t,t).then(n=>(this.lastError&&(this.lastError=null,this.render()),n),n=>{throw this.lastError=n,this.render(),h("cart-error",{error:n}),n});return this._chain=e.catch(()=>{}),e},_commit(t,e){this.state=t,t?.id&&this._setId(t.id);try{localStorage.setItem(`${c.storageKey}:seen`,`${Date.now()}|${t?.totalQuantity||0}`)}catch{}return this.render(),h("cart-updated",{cart:t,reason:e}),t},async init(){let t=this.id();if(!t)return this.state=null,this.loaded=!0,this.render(),h("cart-updated",{cart:null,reason:"load"}),null;if(!this.loaded)try{let e=(localStorage.getItem(`${c.storageKey}:seen`)||"").split("|")[1];e&&l(document,u("cart-count")).forEach(n=>{/^\s*0?\s*$/.test(n.textContent)&&(n.textContent=e)})}catch{}try{let e=await $(`query TetherCart($id:ID!){cart(id:$id){...TetherCart}}${S()}`,{id:t});e.cart?this.state=e.cart:(this._setId(null),this.state=null)}catch(e){A(e,"cart load failed"),this.lastError=e,T(e)&&this._setId(null),this.state=null}return this.loaded=!0,this.render(),h("cart-updated",{cart:this.state,reason:"load"}),this.state},async _create(t={}){let e=c.country||this.customerAccessToken?{...c.country?{countryCode:String(c.country).toUpperCase()}:{},...this.customerAccessToken?{customerAccessToken:this.customerAccessToken}:{}}:void 0,n=await $(V("cartCreate","$input: CartInput!","input: $input"),{input:{buyerIdentity:e,...t}});return this._take(n.cartCreate,"cartCreate")},async _mutate(t,e,n,a,s){let r=this.id();if(!r)return s?this._create(s):null;try{let o=await $(V(t,`$cartId: ID!, ${e}`,`cartId: $cartId, ${n}`),{...a,cartId:r});return this._take(o[t],t)}catch(o){if(s&&T(o))return O("cart expired, creating a new one"),this._setId(null),this._create(s);throw o}},add(t,e=1,n={}){let a=(Array.isArray(t)?t:[t]).map(s=>G(s,e,n));return this._queue(async()=>{let s=await this._mutate("cartLinesAdd","$lines: [CartLineInput!]!","lines: $lines",{lines:a},{lines:a});return this._commit(s,"add"),h("added",{cart:s,lines:a}),c.openCartOnAdd&&this.open(),s})},updateLine(t,e){let n=typeof e=="number"?{quantity:e}:{...e};if(n.quantity!==void 0&&n.quantity<=0)return this.removeLine(t);let a={id:t};return n.quantity!==void 0&&(a.quantity=n.quantity),"sellingPlanId"in n&&(a.sellingPlanId=n.sellingPlanId?I.sellingPlan(n.sellingPlanId):null),n.attributes&&(a.attributes=q(n.attributes)),(n.merchandiseId||n.variantId)&&(a.merchandiseId=I.variant(n.merchandiseId||n.variantId)),this._queue(async()=>this._commit(await this._mutate("cartLinesUpdate","$lines: [CartLineUpdateInput!]!","lines: $lines",{lines:[a]}),"update"))},changeQuantity(t,e){let n=this.lines.find(o=>o.id===t);if(!n)return Promise.resolve(this.state);let a=Math.max(0,(this.pendingQty.get(t)?.qty??n.quantity)+e),s={qty:a,done:!1};this.pendingQty.set(t,s),this.render(),h("cart-updated",{cart:this.state,reason:"pending"});let r=()=>this.pendingQty.get(t)===s;return this._queue(async()=>{if(!r())return this.state;let o=this.lines.find(d=>d.id===t);if(o&&o.quantity===a)return this.state;let i=a>0?await this._mutate("cartLinesUpdate","$lines: [CartLineUpdateInput!]!","lines: $lines",{lines:[{id:t,quantity:a}]}):await this._mutate("cartLinesRemove","$lineIds: [ID!]!","lineIds: $lineIds",{lineIds:[t]});return r()?this._commit(i,a>0?"update":"remove"):(this.state=i,i?.id&&this._setId(i.id),i)}).finally(()=>{r()&&(this.pendingQty.delete(t),this.render(),h("cart-updated",{cart:this.state,reason:"settled"}))})},quantityOf(t){return this.pendingQty.get(t.id)?.qty??t.quantity},removeLine(t){let e=Array.isArray(t)?t:[t];return this._queue(async()=>this._commit(await this._mutate("cartLinesRemove","$lineIds: [ID!]!","lineIds: $lineIds",{lineIds:e}),"remove"))},clear(){let t=this.lines.map(e=>e.id);return t.length?this.removeLine(t):Promise.resolve(this.state)},setNote(t){return this._queue(async()=>this._commit(await this._mutate("cartNoteUpdate","$note: String!","note: $note",{note:t??""},{note:t??""}),"note"))},setAttributes(t){let e=new Map((this.state?.attributes||[]).map(a=>[a.key,a.value]));q(t).forEach(a=>e.set(a.key,a.value));let n=[...e].filter(([,a])=>a!=="").map(([a,s])=>({key:a,value:s}));return this._queue(async()=>this._commit(await this._mutate("cartAttributesUpdate","$attributes: [AttributeInput!]!","attributes: $attributes",{attributes:n},{attributes:n}),"attributes"))},setDiscountCodes(t){let e=(Array.isArray(t)?t:[t]).map(n=>String(n).trim()).filter(Boolean);return this._queue(async()=>this._commit(await this._mutate("cartDiscountCodesUpdate","$discountCodes: [String!]!","discountCodes: $discountCodes",{discountCodes:e},{discountCodes:e}),"discount"))},async applyDiscount(t){let e=(this.state?.discountCodes||[]).map(s=>s.code),n=await this.setDiscountCodes([...new Set([...e,t])]);if((n?.discountCodes||[]).find(s=>s.code.toLowerCase()===String(t).toLowerCase())?.applicable)return n;throw await this.removeDiscount(t).catch(()=>{}),new v(`Discount code not valid: ${t}`,{code:"INVALID_DISCOUNT"})},removeDiscount(t){let e=String(t).toLowerCase();return this.setDiscountCodes((this.state?.discountCodes||[]).map(n=>n.code).filter(n=>n.toLowerCase()!==e))},setBuyerIdentity(t,{create:e=!0}={}){return this._queue(async()=>{let n=await this._mutate("cartBuyerIdentityUpdate","$buyerIdentity: CartBuyerIdentityInput!","buyerIdentity: $buyerIdentity",{buyerIdentity:t},e?{buyerIdentity:t}:null).catch(a=>{if(e||!T(a))throw a;return this._setId(null),null});return this._commit(n,"buyer-identity")})},async checkout(t=c.checkoutTarget){let e=this.id();if(!e||this.state&&!this.count)return null;let n=t==="_blank"?window.open("","_blank"):null;if(n)try{n.opener=null}catch{}try{let a=await $("query TetherCheckout($id: ID!) { cart(id: $id) { checkoutUrl } }",{id:e}),s=this.beforeCheckout&&await this.beforeCheckout().catch(()=>null)||a.cart?.checkoutUrl;if(s&&this.customerAccessToken&&(s+=`${s.includes("?")?"&":"?"}logged_in=true`),!s)throw new v("No checkoutUrl (cart empty or expired)");return h("checkout",{url:s,cart:this.state}),n&&!n.closed?n.location.href=s:window.location.href=s,s}catch(a){return n&&n.close(),A(a,"checkout failed"),null}},drawers(){return l(document,u("cart-drawer"))},_open:!1,isOpen(){let t=this.drawers();return t.length?t.some(e=>e.classList.contains(c.cartDrawerOpenClass)):this._open},open(){if(this.isOpen())return;this._open=!0;let t=this.drawers().filter(e=>g(e,"cart-drawer")!=="manual");t.forEach(e=>{e.inert=!1,e.classList.add(c.cartDrawerOpenClass),e.setAttribute("aria-hidden","false")}),x(!0),c.cartFocus!==!1&&t[0]&&(k=document.activeElement,setTimeout(()=>{let e=W(t[0])[0]||t[0];e===t[0]&&!t[0].hasAttribute("tabindex")&&(t[0].tabIndex=-1),e.focus?.({preventScroll:!0})},60)),typeof c.onCartOpen=="function"&&c.onCartOpen(t),h("cart-toggled",{open:!0})},close(){if(!this.isOpen())return;this._open=!1;let t=this.drawers(),e=t.some(n=>n.contains(document.activeElement));t.forEach(n=>{n.classList.remove(c.cartDrawerOpenClass),n.setAttribute("aria-hidden","true"),c.cartFocus!==!1&&(n.inert=!0)}),x(!1),e&&k?.isConnected&&k.focus({preventScroll:!0}),k=null,typeof c.onCartClose=="function"&&c.onCartClose(t),h("cart-toggled",{open:!1})},toggle(){this.isOpen()?this.close():this.open()},subscribe(t){let e=()=>t(this.state,{open:this.isOpen(),count:this.count,loaded:this.loaded,warnings:this.warnings}),n=()=>e();return["cart-updated","cart-toggled"].forEach(a=>document.addEventListener(`${c.prefix}:${a}`,n)),e(),()=>["cart-updated","cart-toggled"].forEach(a=>document.removeEventListener(`${c.prefix}:${a}`,n))},render(){let t=this.state,e=t?t.totalQuantity:0,n=r=>t?b(t.cost?.[r]):"";x(this.isOpen()),l(document,u("cart-count")).forEach(r=>m(r,e)),l(document,u("cart-subtotal")).forEach(r=>m(r,n("subtotalAmount"))),l(document,u("cart-total")).forEach(r=>m(r,n("totalAmount"))),l(document,u("cart-checkout-charge")).forEach(r=>m(r,n("checkoutChargeAmount")));let a=this.lines.some(r=>r.sellingPlanAllocation),s={"cart-empty":e===0,"cart-filled":e>0,"cart-has-subscription":a,"cart-no-subscription":!a,"cart-has-discount":(t?.discountCodes||[]).some(r=>r.applicable),"cart-error":!!this.lastError,"cart-warning":this.warnings.length>0};l(document,u("cart-warning")).forEach(r=>m(r,[...new Set(this.warnings.map(o=>o.message))].join(" "))),l(document,u("show")).forEach(r=>{let o=g(r,"show");o in s&&!r.closest(u("product"))&&L(r,s[o])}),l(document,u("checkout")).forEach(r=>{r.classList.toggle("is-disabled",!e),r.setAttribute("aria-disabled",String(!e))}),l(document,`textarea${u("cart-note")},input${u("cart-note")}`).forEach(r=>{document.activeElement!==r&&(r.value=t?.note||"")}),l(document,u("cart-discounts")).forEach(r=>{K(r,t?.discountCodes||[],(o,i)=>{o.setAttribute(E("discount-code"),i.code);let d=o.querySelector(u("discount","code"))||(o.firstElementChild?null:o);d&&j(d,i.code),o.classList.toggle("is-inapplicable",!i.applicable)})}),l(document,u("cart-lines")).forEach(r=>{N(r,this.lines,o=>o.id,(o,i)=>J(o,i),{onEnter:c.onLineEnter,onLeave:c.onLineLeave})}),t&&R("cart")}};function z(t,e){let n=t.merchandise||{},a=t.sellingPlanAllocation?.sellingPlan;switch(e){case"title":return n.product?.title;case"product-title":return n.product?.title;case"variant-title":return n.title==="Default Title"?"":n.title;case"options":return(n.selectedOptions||[]).filter(s=>s.value!=="Default Title").map(s=>`${s.name}: ${s.value}`).join(", ");case"vendor":return n.product?.vendor;case"sku":return n.sku;case"price":return b(t.cost?.amountPerQuantity||n.price);case"compare-at-price":return b(t.cost?.compareAtAmountPerQuantity||n.compareAtPrice);case"line-total":return b(t.cost?.totalAmount);case"line-subtotal":return b(t.cost?.subtotalAmount);case"quantity":return D.quantityOf(t);case"plan":return a?.name||"";case"plan-description":return a?.description||"";case"components":return(t.lineComponents||[]).map(s=>`${s.quantity} \xD7 ${s.merchandise?.product?.title||""}`).join(", ");default:if(e.startsWith("attribute:")){let s=e.slice(10);return(t.attributes||[]).find(r=>r.key===s)?.value||""}return}}function J(t,e){let n=e.merchandise||{},a=!!e.sellingPlanAllocation;t.setAttribute(E("line-id"),e.id),t.classList.toggle("is-subscription",a),l(t,u("line")).forEach(i=>{let d=g(i,"line");if(d==="image")return M(i,n.image?.url||n.product?.featuredImage?.url,n.product?.title);if(d==="url"){let y=F(n.product?.handle,n.product?.id),_=new URLSearchParams;n.id&&_.set("variant",String(n.id).split("/").pop());let w=e.sellingPlanAllocation?.sellingPlan?.id;w&&_.set("selling_plan",w.split("/").pop());let C=_.toString();return i.setAttribute("href",C?`${y}${y.includes("?")?"&":"?"}${C}`:y)}let p=z(e,d);p!==void 0&&m(i,p)});let s=D.warnings.find(i=>i.target===e.id);t.classList.toggle("is-warning",!!s);let r=D.pendingQty.has(e.id);t.classList.toggle("is-busy",r),r?t.setAttribute("aria-busy","true"):t.removeAttribute("aria-busy"),l(t,u("line","warning")).forEach(i=>m(i,s?.message||""));let o={subscription:a,"one-time":!a,"on-sale":parseFloat(e.cost?.compareAtAmountPerQuantity?.amount)>parseFloat(e.cost?.amountPerQuantity?.amount),"has-components":(e.lineComponents||[]).length>0,warning:!!s};l(t,u("line-show")).forEach(i=>{let d=g(i,"line-show");d in o&&L(i,o[d])}),l(t,`select${u("line-plan")}`).forEach(i=>{let d=n.product?.handle;d&&Q(d).then(p=>{let y=B(p),w=[...!p.requiresSellingPlan&&g(i,"line-plan")!=="subscription-only"?[{value:"",label:i.getAttribute(E("one-time-label"))||"One-time purchase"}]:[],...y.map(f=>({value:f.id,label:f.name}))],C=w.map(f=>f.value).join("|");i.dataset.tetherSig!==C&&(i.innerHTML="",w.forEach(f=>{let P=document.createElement("option");P.value=f.value,P.textContent=f.label,i.appendChild(P)}),i.dataset.tetherSig=C),i.value=e.sellingPlanAllocation?.sellingPlan?.id||"",L(i,y.length>0)}).catch(p=>A(p,"line plan options"))})}export{W as a,D as b};
@@ -1 +1 @@
1
- import{D as f,n as s,o as i,p as d,t as l}from"./chunk-KARKXC6G.js";function w(e,r=window.location,c="product"){let t=(d(e,c)||"").trim();if(!t.toLowerCase().startsWith("url:"))return{key:t||null,fromUrl:!1,raw:t};let o=t.slice(4).trim(),n=null;if(o.toLowerCase()==="path"){let a=r.pathname.split("/").filter(Boolean);n=a.length?p(a[a.length-1]):null}else n=new URLSearchParams(r.search).get(o||"handle");return n=n&&n.trim()?n.trim():null,{key:n,fromUrl:!0,raw:t}}function p(e){try{return decodeURIComponent(e)}catch{return e}}var m=["loading","ready","error","not-found"],y=e=>e?.code==="NOT_FOUND",u=()=>["product","collection","products","recommendations"].map(e=>i(e)).join(","),b=(e,r)=>e===r||e.parentElement?.closest(u())===r;function x(e,r,c){let t=r==="not-found";e.setAttribute(s("state"),t?"error":r),r==="error"||t?e.setAttribute(s("error"),t?"not-found":c?.code||"error"):e.removeAttribute(s("error")),l(e,i("show"),u()).forEach(o=>{let n=d(o,"show");m.includes(n)&&f(o,n===r)}),(r==="error"||t)&&l(e,i("add-to-cart"),u()).forEach(o=>{o.classList.add("is-disabled"),o.setAttribute("aria-disabled","true"),"disabled"in o&&(o.disabled=!0)})}export{w as a,m as b,y as c,u as d,b as e,x as f};
1
+ import{D as f,n as s,o as i,p as d,t as l}from"./chunk-K2YEQAIH.js";function w(e,r=window.location,c="product"){let t=(d(e,c)||"").trim();if(!t.toLowerCase().startsWith("url:"))return{key:t||null,fromUrl:!1,raw:t};let o=t.slice(4).trim(),n=null;if(o.toLowerCase()==="path"){let a=r.pathname.split("/").filter(Boolean);n=a.length?p(a[a.length-1]):null}else n=new URLSearchParams(r.search).get(o||"handle");return n=n&&n.trim()?n.trim():null,{key:n,fromUrl:!0,raw:t}}function p(e){try{return decodeURIComponent(e)}catch{return e}}var m=["loading","ready","error","not-found"],y=e=>e?.code==="NOT_FOUND",u=()=>["product","collection","products","recommendations"].map(e=>i(e)).join(","),b=(e,r)=>e===r||e.parentElement?.closest(u())===r;function x(e,r,c){let t=r==="not-found";e.setAttribute(s("state"),t?"error":r),r==="error"||t?e.setAttribute(s("error"),t?"not-found":c?.code||"error"):e.removeAttribute(s("error")),l(e,i("show"),u()).forEach(o=>{let n=d(o,"show");m.includes(n)&&f(o,n===r)}),(r==="error"||t)&&l(e,i("add-to-cart"),u()).forEach(o=>{o.classList.add("is-disabled"),o.setAttribute("aria-disabled","true"),"disabled"in o&&(o.disabled=!0)})}export{w as a,m as b,y as c,u as d,b as e,x as f};
@@ -0,0 +1 @@
1
+ import{a as E,b as K,c as z}from"./chunk-ZIUIWEON.js";import{a as g,c as w,f as p}from"./chunk-RREHGH4A.js";import{c as I,e as A,f as F,g as O,h as R,i as U}from"./chunk-FIOZPPC5.js";import{A as q,B as L,D as x,G as D,I as M,K as J,b as h,e as T,f as b,g as m,h as C,n as l,o as a,p as c,q as S,s as N,t as W,u as f}from"./chunk-K2YEQAIH.js";var P=()=>`${a("collection")},${a("products")},${a("recommendations")}`,B=class{constructor(e){this.root=e,this.products=[],this.pageInfo=null,this.collection=null,p(e,"loading"),e.addEventListener("click",n=>{let o=n.target.closest?.(a("load-more"));o&&o.closest(P())===e&&(n.preventDefault(),J(o,()=>this.load(!0)))})}$(e){return W(this.root,e,P())}options(){let e=this.root,n={first:parseInt(c(e,"limit")||"",10)||void 0,sortKey:c(e,"sort")||void 0,reverse:c(e,"reverse")==="true"};if(S(e,"collection"))n.collection=c(e,"collection");else{let o=c(e,"products")||"";n.query=o.startsWith("url:")?new URL(window.location.href).searchParams.get(o.slice(4))||"":o}return n}async load(e=!1){let n=this.loadToken=(this.loadToken||0)+1,o=()=>n!==this.loadToken;try{if(S(this.root,"recommendations")){let{key:r}=g(this.root,window.location,"recommendations"),s=this.root.closest(a("product"));if(!r&&s&&({key:r}=g(s)),!r)throw new C("No product for recommendations",{code:"NOT_FOUND"});let u=await U(r,c(this.root,"intent")||"RELATED");if(o())return;let i=parseInt(c(this.root,"limit")||"",10);this.products=i?u.slice(0,i):u}else{let r=await R({...this.options(),after:e?this.pageInfo?.endCursor:null});if(o())return;this.collection=r.collection,this.pageInfo=r.pageInfo,this.products=e?[...this.products,...r.products]:r.products}this.render(),p(this.root,"ready"),f("list-ready",{products:this.products,collection:this.collection},this.root)}catch(r){if(o())return;e||p(this.root,w(r)?"not-found":"error",r),w(r)&&S(this.root,"recommendations")||m(r,"list load failed"),f("error",{error:r,context:"list"},this.root)}}render(){let e=this.collection;this.$(a("collection-bind")).forEach(o=>{switch(c(o,"collection-bind")){case"title":return L(o,e?.title||"");case"description":o.innerHTML=e?.descriptionHtml||"";return;case"image":return q(o,e?.image?.url,e?.image?.altText||e?.title);case"count":return L(o,this.products.length);default:return}}),this.$(a("list")).forEach(o=>{D(o,this.products,(r,s)=>{r.setAttribute(l("product"),s.handle),r.removeAttribute(l("state"))}),f("list-rendered",{container:o},this.root)});let n=this.products.length===0;this.$(a("show")).forEach(o=>{let r=c(o,"show");r==="list-empty"&&x(o,n),r==="list-filled"&&x(o,!n)}),this.$(a("load-more")).forEach(o=>x(o,!!this.pageInfo?.hasNextPage)),M("list")}};var v=new WeakSet,ft=new WeakSet,k=new Set,H=new Set,j=new WeakMap;function _(){k.forEach(t=>{t.isConnected||k.delete(t)}),H.forEach(t=>{t.root.isConnected||H.delete(t)})}function pt(t,e){return[...t.matches?.(e)?[t]:[],...N(t,e)]}function G(t){if(v.has(t))return!1;let{key:e,fromUrl:n,raw:o}=g(t);if(!e)return n?(v.add(t),p(t,"not-found"),f("product-not-found",{key:null,source:o},t)):t.closest(P())||b(`[${l("product")}] without a value. Bind it to the Shopify handle field, or use "url:handle".`,t),!1;v.add(t),k.add(t);let r={};j.set(t,r);let s=()=>j.get(t)===r;E.get(t)?t.setAttribute(l("state"),"updating"):p(t,"loading");let u=I(e);return d?.add(u),u.then(i=>{if(!s())return;let y=E.get(t);y?y.update(i):new z(t,i),V(t,i),h.revalidate!==!1&&F(e)&&X(e)}).catch(i=>{if(!s())return;let y=w(i);p(t,y?"not-found":"error",i),y?(f("product-not-found",{key:e,source:o},t),n?T(`product not found: ${e}`):m(i,`product ${e}`)):(m(i,`product ${e}`),f("error",{error:i,context:"product",key:e},t))}),!0}function V(t,e){let n=c(t,"page-title");!n||typeof document>"u"||(document.title=n.replace(/\{title\}/g,e.title).replace(/\{vendor\}/g,e.vendor||"").replace(/\{type\}/g,e.productType||""))}function ht(){_(),k.forEach(t=>{t.getAttribute(l("state"))!=="error"||t.getAttribute(l("error"))==="not-found"||(v.delete(t),G(t))})}var $=new Set;function X(t){$.size||setTimeout(Y,0),$.add(t)}function Y(){let t=[...$];$=new Set,O(t).forEach((e,n)=>e.then(o=>{k.forEach(r=>{let s=E.get(r);if(!s||!r.isConnected)return;let u=g(r).key;u!==t[n]&&u!==o.handle&&u!==o.id||JSON.stringify(s.product)!==JSON.stringify(o)&&s.update(o)})}).catch(o=>m(o,`refresh ${t[n]}`)))}var Q=new WeakSet,d=null,mt=t=>(d?.add(t),t);function Z(){if(!d)return;let t=[...d];Promise.allSettled(t).then(()=>{!d||t.some(e=>!d.has(e))||(t.length===d.size?(d=null,document.documentElement.classList.remove(`${h.prefix}-market-pending`)):Z())})}function gt(t=document){N(t.ownerDocument||t,'script[type="application/json"][data-tether-hydrate]').forEach(e=>{if(!Q.has(e)){Q.add(e);try{let n=JSON.parse(e.textContent);K(n.products);let o=(r,s)=>String(r||"").toUpperCase()===String(s||"").toUpperCase();o(n.country,h.country)&&o(n.language,h.language)?A(n.products):(T("hydration skipped: other market"),d||(d=new Set,document.documentElement.classList.add(`${h.prefix}-market-pending`)))}catch(n){b("bad data-tether-hydrate",n)}}})}export{P as a,B as b,v as c,ft as d,k as e,H as f,_ as g,pt as h,G as i,ht as j,mt as k,Z as l,gt as m};
@@ -1 +1 @@
1
- import{b as rt,e as ot}from"./chunk-4UR45XTC.js";import{b as nt}from"./chunk-BGIKQY6H.js";import{d as V,e as F,f as S,g as N,h as W,i as M,j as Y,k as E}from"./chunk-YXCXIPQV.js";import{A as I,B as d,D as q,E as k,F as tt,G as A,I as D,J as et,K as it,L as st,M as at,b as T,g as G,n as g,o as l,p as c,q as P,r as J,s as B,t as K,u as x,v as z,w as $,x as X,z as Z}from"./chunk-KARKXC6G.js";var pt=new WeakMap,lt=()=>l("product");function mt(w,i){let t=i.indexOf("."),e=i.slice(0,t),s=i.slice(t+1);return(w.metafields||[]).find(a=>a&&a.namespace===e&&a.key===s)||null}var C=new Map;function ft(w){(w||[]).forEach(i=>{i?.handle&&!C.has(i.handle)&&C.set(i.handle,(i.options||[]).map(t=>t.name))})}var ct=class{constructor(i,t){this.root=i,this.product=t,this.selected={},this.variant=null,this.quantity=Math.max(0,parseInt(c(i,"quantity")??"1",10)||(P(i,"quantity")?0:1)),this.plans=F(t),this.purchase="one-time",this.planId=null,pt.set(i,this),i.setAttribute(g("state"),"ready"),i.removeAttribute(g("error")),this.initSelection(),this.initPurchase(),this.renderProduct(),this.bind(),this.renderVariant(),et(i,"product"),D("product"),x("product-ready",{product:t,scope:this},i)}update(i){let t=this.variant?.id;this.product=i,this.plans=F(i),this.planId&&!this.plans.some(s=>s.id===this.planId)&&(this.planId=this.plans[0]?.id||null),!this.plans.length&&this.purchase==="subscription"&&(this.purchase="one-time");let e=i.variants.nodes.find(s=>s.id===t);e&&(this.selected={},e.selectedOptions.forEach(s=>{this.selected[s.name]=s.value})),this.root.setAttribute(g("state"),"ready"),this.root.removeAttribute(g("error")),this.renderProduct(),this.renderVariant(),D("product"),x("product-updated",{product:i,scope:this},this.root)}$(i){let t=K(this.root,i,lt());return this.root.matches(i)?[this.root,...t]:t}optName(i){let t=this.product?.options||[];if(!i||t.some(s=>s.name===i))return i;let e=(C.get(this.product.handle)||[]).indexOf(i);return e>=0&&t[e]?t[e].name:i}initSelection(){let i=this.product.variants.nodes,t=i.find(s=>s.availableForSale)||i[0];t&&t.selectedOptions.forEach(s=>{this.selected[s.name]=s.value});let e=new URLSearchParams(window.location.search).get("variant")||c(this.root,"variant");if(e){let s=V.variant(e),o=i.find(a=>a.id===s);o&&(this.selected={},o.selectedOptions.forEach(a=>{this.selected[a.name]=a.value}))}}initPurchase(){if(!this.plans.length)return;let i=new URLSearchParams(window.location.search),t=E(this.product,i.get("selling_plan")),e=E(this.product,c(this.root,"default-plan"));this.planId=(t||e||this.plans[0]).id;let s=t?"subscription":c(this.root,"default-purchase")||T.defaultPurchase;this.purchase=this.product.requiresSellingPlan||s==="subscription"?"subscription":"one-time"}findVariant(){return this.product.variants.nodes.find(i=>i.selectedOptions.every(t=>this.selected[t.name]===t.value))||null}isValueAvailable(i,t){return this.product.variants.nodes.some(e=>e.availableForSale&&e.selectedOptions.every(s=>s.name===i?s.value===t:this.selected[s.name]===s.value))}get plan(){return this.plans.find(i=>i.id===this.planId)||null}get subscriptionAvailable(){return!!(this.variant&&this.plans.some(i=>S(this.variant,i.id)))}get isSubscription(){return this.purchase==="subscription"&&!!S(this.variant,this.planId)}getLine(){if(!this.variant)return null;let i={merchandiseId:this.variant.id,quantity:this.quantity};this.isSubscription&&(i.sellingPlanId=this.planId);let t=this.collectAttributes();return t.length&&(i.attributes=t),i}collectAttributes(){let i=at(st(this.root,"line-attributes")),t=this.$(l("line-attribute")).map(e=>{let s=c(e,"line-attribute"),o;return e.type==="checkbox"?o=e.checked?e.value&&e.value!=="on"?e.value:"Yes":"":e.type==="radio"?o=e.checked?e.value:null:o=e.value,o==null||o===""?null:{key:s,value:String(o)}}).filter(Boolean);return[...i,...t]}select(i,t){if(this.selected[i]===t)return;let e=this.product.variants.nodes.filter(o=>o.selectedOptions.some(a=>a.name===i&&a.value===t));if(!e.length)return;let s={...this.selected,[i]:t};if(!e.some(o=>o.selectedOptions.every(a=>s[a.name]===a.value))){let o=r=>r.selectedOptions.filter(u=>u.name!==i&&this.selected[u.name]===u.value).length*2+(r.availableForSale?1:0);e.reduce((r,u)=>o(u)>o(r)?u:r).selectedOptions.forEach(r=>{s[r.name]=r.value})}this.selected=s,this.renderVariant()}selectVariant(i){let t=this.product.variants.nodes.find(e=>e.id===V.variant(i));t&&(this.selected={},t.selectedOptions.forEach(e=>{this.selected[e.name]=e.value}),this.renderVariant())}setPurchase(i){let t=i==="subscription"?"subscription":"one-time";t==="one-time"&&this.product.requiresSellingPlan||this.purchase!==t&&(this.purchase=t,this.renderVariant())}selectPlan(i){let t=E(this.product,i);t&&(this.planId=t.id,this.purchase="subscription",this.renderVariant())}setQuantity(i){let t=P(this.root,"quantity")?0:1;this.quantity=Math.max(t,parseInt(i,10)||0),this.$(l("qty")).forEach(e=>d(e,this.quantity)),this.renderVariant()}async addToCart(){if(!this.variant?.availableForSale)return null;let i=this.getLine();if(!i||i.quantity<1)return null;let t=await nt.add(i);return x("product-added",{product:this.product,variant:this.variant,line:i},this.root),t}bind(){let i=t=>t&&t.closest(lt())===this.root;this.root.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;let s=e.closest(l("option-value"));if(i(s)&&s.closest(l("option-list"))){t.preventDefault(),this.select(this.optName(c(s.closest(l("option-list")),"option-list")),c(s,"option-value"));return}let o=e.closest(l("plan-value"));if(i(o)){t.preventDefault(),this.selectPlan(c(o,"plan-value"));return}let a=e.closest(`${l("purchase")}:not(select)`);if(i(a)){a.tagName!=="INPUT"&&t.preventDefault(),this.setPurchase(c(a,"purchase"));return}let r=e.closest(l("qty-plus"));if(i(r)){t.preventDefault(),this.setQuantity(this.quantity+1);return}let u=e.closest(l("qty-minus"));if(i(u)){t.preventDefault(),this.setQuantity(this.quantity-1);return}let v=e.closest(l("add-to-cart"));i(v)&&(t.preventDefault(),this.onAddClick(v))}),this.root.addEventListener("change",t=>{let e=t.target;i(e)&&(e.matches(`select${l("option")}`)?this.select(this.optName(c(e,"option")),e.value):e.matches(`select${l("variant-select")}`)?this.selectVariant(e.value):e.matches(`select${l("plan")}`)?e.value?this.selectPlan(e.value):this.setPurchase("one-time"):e.matches(`select${l("purchase")}`)?this.setPurchase(e.value):e.matches(l("qty"))&&this.setQuantity(e.value))})}onAddClick(i){let t=i.querySelector(l("add-label"))||i,e=c(i,"adding-text"),s=o=>d(t,o);t.dataset.tetherLabel===void 0&&(t.dataset.tetherLabel=t.tagName==="INPUT"?t.value:t.textContent),it(i,async()=>{e&&s(e);try{await this.addToCart()}catch(o){G(o,"add to cart failed"),x("error",{error:o,context:"add-to-cart"},this.root)}finally{e&&s(t.dataset.tetherLabel)}}).then(()=>{this.renderVariant()})}renderProduct(){let i=this.product;C.has(i.handle)||this.$(`${l("option-list")},select${l("option")}`).map(s=>c(s,"option-list")||c(s,"option")).some(s=>i.options.some(o=>o.name===s))&&ft([i]);let t=this.product;this.$(l("bind")).forEach(e=>{let s=c(e,"bind")||"",o={title:t.title,"description-text":t.description,vendor:t.vendor,type:t.productType,handle:t.handle}[s];if(o!==void 0)return d(e,o);switch(s){case"description":e.innerHTML=t.descriptionHtml||"";return;case"published-at":return d(e,X(t.publishedAt));case"min-price":return d(e,$(t.priceRange.minVariantPrice));case"max-price":return d(e,$(t.priceRange.maxVariantPrice));case"featured-image":return I(e,t.featuredImage?.url,t.featuredImage?.altText||t.title);case"url":case"link":e.setAttribute("href",J(t.handle,t.id)),s==="url"&&!e.firstElementChild&&!e.textContent.trim()&&d(e,t.title);return;case"images":{let a=[...e.children].map(r=>r.tagName==="IMG"?r:r.querySelector("img"));if(!tt(e)&&a.length===t.images.nodes.length&&a.every((r,u)=>Z(r?.getAttribute("src"),t.images.nodes[u].url)))return}return A(e,t.images.nodes,(a,r)=>{let u=a.matches(`img,${l("bind","image")}`)?a:a.querySelector("img")||a;I(u,r.url,r.altText||t.title)});case"tags":{let a=(e.getAttribute("exclude")||"").split(",").map(r=>r.trim()).filter(Boolean);return A(e,t.tags.filter(r=>!a.includes(r)),(r,u)=>d(r,u))}default:if(/^image:\d+$/.test(s)){let a=t.images.nodes[s.slice(6)-1]||t.featuredImage;return I(e,a?.url,a?.altText||t.title)}if(s.startsWith("metafield:")){let a=mt(t,s.slice(10));return a?a.reference?.image?I(e,a.reference.image.url,a.reference.image.altText):(/^(rich_text|multi_line_text)_field$/.test(a.type)&&(e.style.whiteSpace="pre-line"),d(e,a.value)):d(e,"")}return}}),this.$(l("option-list")).forEach(e=>{let s=this.optName(c(e,"option-list")),o=t.options.find(a=>a.name===s);return!o||o.optionValues.length<=1&&P(e,"hide-single")?q(e,!1):A(e,o.optionValues,(a,r)=>{a.setAttribute(g("option-value"),r.name);let u=a.querySelector(l("bind","option-value"));u?d(u,r.name):a.firstElementChild||d(a,r.name);let v=a.querySelector(l("bind","swatch"));v&&r.swatch?.color&&(v.style.backgroundColor=r.swatch.color),v&&r.swatch?.image?.previewImage&&I(v,r.swatch.image.previewImage.url,r.name)})}),this.$(`select${l("option")}`).forEach(e=>{let s=t.options.find(o=>o.name===this.optName(c(e,"option")));if(!s)return q(e,!1);e.innerHTML="",s.optionValues.forEach(o=>e.appendChild(new Option(o.name,o.name)))}),this.$(`select${l("variant-select")}`).forEach(e=>{e.innerHTML="",t.variants.nodes.forEach(s=>e.appendChild(new Option(s.title,s.id)))}),this.$(l("plan-list")).forEach(e=>{let s=(c(e,"plan-list")||"").trim(),o=["","true","all","*"].includes(s.toLowerCase())?null:s,a=this.plans.filter(r=>!o||r.group.name===o);A(e,a,(r,u)=>{r.setAttribute(g("plan-value"),u.id),!r.firstElementChild&&!r.querySelector(l("plan-bind"))&&d(r,u.name)})}),this.$(`select${l("plan")}`).forEach(e=>{e.innerHTML="",!t.requiresSellingPlan&&c(e,"plan")!=="subscription-only"&&e.appendChild(new Option(e.getAttribute(g("one-time-label"))||"One-time purchase","")),this.plans.forEach(s=>e.appendChild(new Option(s.name,s.id)))})}renderVariant(){let i=this.product,t=this.findVariant();if(t||([t]=i.variants.nodes,t&&(this.selected={},t.selectedOptions.forEach(n=>{this.selected[n.name]=n.value}))),this.variant=t,!t)return;if(this.plans.length&&!S(t,this.planId)){let n=this.plans.find(h=>S(t,h.id));n&&(this.planId=n.id)}let e=this.isSubscription,s=t.price,o=this.planId?N(t,this.planId):null,a=e?o:s,r=e&&S(t,this.planId)?.priceAdjustments?.[0]?.compareAtPrice||t.compareAtPrice,u=r&&parseFloat(r.amount)>parseFloat(a.amount),v=u?Math.round((1-parseFloat(a.amount)/parseFloat(r.amount))*100):0,L=this.planId?M(t,this.planId):{amount:null,percentage:0},O=this.plan,ut={amount:(parseFloat(a.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:a.currencyCode},f=$,U=n=>z(n),j={price:()=>f(a),"total-price":()=>f(ut),"one-time-price":()=>f(s),"subscription-price":()=>f(o),"subscription-savings":()=>U(L.percentage),"subscription-savings-amount":()=>f(L.amount),"checkout-charge":()=>{let n=e?W(t,this.planId):a;return n&&f({amount:(parseFloat(n.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:n.currencyCode})},"plan-name":()=>O?.name,"plan-description":()=>O?.description,"plan-group":()=>O?.group?.name,"compare-at-price":()=>u?f(r):"","unit-price":()=>f(t.unitPrice),"discount-percentage":()=>`${v}%`,"discount-amount":()=>u?f({amount:String(parseFloat(r.amount)-parseFloat(a.amount)),currencyCode:a.currencyCode}):"","variant-title":()=>t.title,"variant-id":()=>t.id,sku:()=>t.sku,barcode:()=>t.barcode,stock:()=>t.quantityAvailable,quantity:()=>this.quantity};this.$(l("bind")).forEach(n=>{let h=c(n,"bind");h==="variant-image"?I(n,t.image?.url||i.featuredImage?.url,t.image?.altText||i.title):j[h]&&d(n,j[h]())}),this.$(l("option-selected")).forEach(n=>d(n,this.selected[this.optName(c(n,"option-selected"))]||"")),this.$(l("option-list")).forEach(n=>{let h=this.optName(c(n,"option-list"));B(n,l("option-value")).forEach(p=>{let b=c(p,"option-value");k(p,this.selected[h]===b);let m=!this.isValueAvailable(h,b);p.classList.toggle("is-unavailable",m),p.setAttribute("data-unavailable",m?"true":"false")})}),this.$(`select${l("option")}`).forEach(n=>{n.value=this.selected[this.optName(c(n,"option"))]||""}),this.$(`select${l("variant-select")}`).forEach(n=>{n.value=t.id}),this.$(l("purchase")).forEach(n=>{if(n.tagName==="SELECT"){n.value=this.purchase;return}let h=c(n,"purchase");k(n,h===this.purchase);let p=h==="subscription"?!this.subscriptionAvailable:i.requiresSellingPlan;n.classList.toggle("is-unavailable",p)}),this.$(l("plan-value")).forEach(n=>{let h=c(n,"plan-value"),p=this.plans.find(m=>m.id===h),b=!!S(t,h);k(n,e&&h===this.planId),n.classList.toggle("is-unavailable",!b),B(n,l("plan-bind")).forEach(m=>{let y=Y(p),Q=M(t,h),ht=c(m,"plan-bind"),R={name:()=>p?.name,option:()=>(p?.options||[]).map(dt=>dt.value).join(", "),description:()=>p?.description,price:()=>f(N(t,h)),savings:()=>U(Q.percentage),"savings-amount":()=>f(Q.amount),adjustment:()=>y?y.type==="percentage"?`${y.value}%`:f(y.value):""}[ht];R&&d(m,R())})}),this.$(`select${l("plan")}`).forEach(n=>{n.value=e?this.planId:""});let _=t.quantityAvailable!=null&&t.quantityAvailable>0&&t.quantityAvailable<=(T.lowStock??5),H={"in-stock":t.availableForSale,"out-of-stock":!t.availableForSale,backorder:t.availableForSale&&t.currentlyNotInStock,"on-sale":!!u,"not-on-sale":!u,"has-variants":i.variants.nodes.length>1,"single-variant":i.variants.nodes.length===1,"low-stock":_,"plenty-in-stock":t.availableForSale&&!_,"subscription-available":this.subscriptionAvailable,"subscription-unavailable":!this.subscriptionAvailable,"subscription-only":!!i.requiresSellingPlan,"one-time-available":!i.requiresSellingPlan,"subscription-selected":e,"one-time-selected":!e,"has-savings":e?L.percentage>0:!!u,loading:!1,ready:!0,error:!1,"not-found":!1};this.$(l("show")).forEach(n=>{let h=c(n,"show");h in H&&(rt.includes(h)&&!ot(n,this.root)||q(n,H[h]))}),this.root.classList.toggle("is-subscription",e),this.root.setAttribute(g("purchase-mode"),e?"subscription":"one-time"),this.$(l("add-to-cart")).forEach(n=>{let h=!t.availableForSale;n.classList.toggle("is-disabled",h),n.setAttribute("aria-disabled",String(h)),"disabled"in n&&(n.disabled=h);let p=c(n,"soldout-text"),b=c(n,"subscribe-text");if(p||b){let m=n.querySelector(l("add-label"))||n;m.dataset.tetherLabel===void 0&&(m.dataset.tetherLabel=m.tagName==="INPUT"?m.value:m.textContent);let y=m.dataset.tetherLabel;e&&b&&(y=b),h&&p&&(y=p),n.getAttribute("aria-busy")!=="true"&&d(m,y)}}),x("variant-changed",{product:i,variant:t,selected:{...this.selected},purchase:this.purchase,sellingPlanId:e?this.planId:null},this.root)}};export{pt as a,ft as b,ct as c};
1
+ import{b as rt,e as ot}from"./chunk-RREHGH4A.js";import{b as nt}from"./chunk-L2TRRKYV.js";import{d as V,e as F,f as S,g as N,h as W,i as M,j as Y,k as E}from"./chunk-AJLPU2JC.js";import{A as I,B as d,D as q,E as k,F as tt,G as A,I as D,J as et,K as it,L as st,M as at,b as T,g as G,n as g,o as l,p as c,q as P,r as J,s as B,t as K,u as x,v as z,w as $,x as X,z as Z}from"./chunk-K2YEQAIH.js";var pt=new WeakMap,lt=()=>l("product");function mt(w,i){let t=i.indexOf("."),e=i.slice(0,t),s=i.slice(t+1);return(w.metafields||[]).find(a=>a&&a.namespace===e&&a.key===s)||null}var C=new Map;function ft(w){(w||[]).forEach(i=>{i?.handle&&!C.has(i.handle)&&C.set(i.handle,(i.options||[]).map(t=>t.name))})}var ct=class{constructor(i,t){this.root=i,this.product=t,this.selected={},this.variant=null,this.quantity=Math.max(0,parseInt(c(i,"quantity")??"1",10)||(P(i,"quantity")?0:1)),this.plans=F(t),this.purchase="one-time",this.planId=null,pt.set(i,this),i.setAttribute(g("state"),"ready"),i.removeAttribute(g("error")),this.initSelection(),this.initPurchase(),this.renderProduct(),this.bind(),this.renderVariant(),et(i,"product"),D("product"),x("product-ready",{product:t,scope:this},i)}update(i){let t=this.variant?.id;this.product=i,this.plans=F(i),this.planId&&!this.plans.some(s=>s.id===this.planId)&&(this.planId=this.plans[0]?.id||null),!this.plans.length&&this.purchase==="subscription"&&(this.purchase="one-time");let e=i.variants.nodes.find(s=>s.id===t);e&&(this.selected={},e.selectedOptions.forEach(s=>{this.selected[s.name]=s.value})),this.root.setAttribute(g("state"),"ready"),this.root.removeAttribute(g("error")),this.renderProduct(),this.renderVariant(),D("product"),x("product-updated",{product:i,scope:this},this.root)}$(i){let t=K(this.root,i,lt());return this.root.matches(i)?[this.root,...t]:t}optName(i){let t=this.product?.options||[];if(!i||t.some(s=>s.name===i))return i;let e=(C.get(this.product.handle)||[]).indexOf(i);return e>=0&&t[e]?t[e].name:i}initSelection(){let i=this.product.variants.nodes,t=i.find(s=>s.availableForSale)||i[0];t&&t.selectedOptions.forEach(s=>{this.selected[s.name]=s.value});let e=new URLSearchParams(window.location.search).get("variant")||c(this.root,"variant");if(e){let s=V.variant(e),o=i.find(a=>a.id===s);o&&(this.selected={},o.selectedOptions.forEach(a=>{this.selected[a.name]=a.value}))}}initPurchase(){if(!this.plans.length)return;let i=new URLSearchParams(window.location.search),t=E(this.product,i.get("selling_plan")),e=E(this.product,c(this.root,"default-plan"));this.planId=(t||e||this.plans[0]).id;let s=t?"subscription":c(this.root,"default-purchase")||T.defaultPurchase;this.purchase=this.product.requiresSellingPlan||s==="subscription"?"subscription":"one-time"}findVariant(){return this.product.variants.nodes.find(i=>i.selectedOptions.every(t=>this.selected[t.name]===t.value))||null}isValueAvailable(i,t){return this.product.variants.nodes.some(e=>e.availableForSale&&e.selectedOptions.every(s=>s.name===i?s.value===t:this.selected[s.name]===s.value))}get plan(){return this.plans.find(i=>i.id===this.planId)||null}get subscriptionAvailable(){return!!(this.variant&&this.plans.some(i=>S(this.variant,i.id)))}get isSubscription(){return this.purchase==="subscription"&&!!S(this.variant,this.planId)}getLine(){if(!this.variant)return null;let i={merchandiseId:this.variant.id,quantity:this.quantity};this.isSubscription&&(i.sellingPlanId=this.planId);let t=this.collectAttributes();return t.length&&(i.attributes=t),i}collectAttributes(){let i=at(st(this.root,"line-attributes")),t=this.$(l("line-attribute")).map(e=>{let s=c(e,"line-attribute"),o;return e.type==="checkbox"?o=e.checked?e.value&&e.value!=="on"?e.value:"Yes":"":e.type==="radio"?o=e.checked?e.value:null:o=e.value,o==null||o===""?null:{key:s,value:String(o)}}).filter(Boolean);return[...i,...t]}select(i,t){if(this.selected[i]===t)return;let e=this.product.variants.nodes.filter(o=>o.selectedOptions.some(a=>a.name===i&&a.value===t));if(!e.length)return;let s={...this.selected,[i]:t};if(!e.some(o=>o.selectedOptions.every(a=>s[a.name]===a.value))){let o=r=>r.selectedOptions.filter(u=>u.name!==i&&this.selected[u.name]===u.value).length*2+(r.availableForSale?1:0);e.reduce((r,u)=>o(u)>o(r)?u:r).selectedOptions.forEach(r=>{s[r.name]=r.value})}this.selected=s,this.renderVariant()}selectVariant(i){let t=this.product.variants.nodes.find(e=>e.id===V.variant(i));t&&(this.selected={},t.selectedOptions.forEach(e=>{this.selected[e.name]=e.value}),this.renderVariant())}setPurchase(i){let t=i==="subscription"?"subscription":"one-time";t==="one-time"&&this.product.requiresSellingPlan||this.purchase!==t&&(this.purchase=t,this.renderVariant())}selectPlan(i){let t=E(this.product,i);t&&(this.planId=t.id,this.purchase="subscription",this.renderVariant())}setQuantity(i){let t=P(this.root,"quantity")?0:1;this.quantity=Math.max(t,parseInt(i,10)||0),this.$(l("qty")).forEach(e=>d(e,this.quantity)),this.renderVariant()}async addToCart(){if(!this.variant?.availableForSale)return null;let i=this.getLine();if(!i||i.quantity<1)return null;let t=await nt.add(i);return x("product-added",{product:this.product,variant:this.variant,line:i},this.root),t}bind(){let i=t=>t&&t.closest(lt())===this.root;this.root.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;let s=e.closest(l("option-value"));if(i(s)&&s.closest(l("option-list"))){t.preventDefault(),this.select(this.optName(c(s.closest(l("option-list")),"option-list")),c(s,"option-value"));return}let o=e.closest(l("plan-value"));if(i(o)){t.preventDefault(),this.selectPlan(c(o,"plan-value"));return}let a=e.closest(`${l("purchase")}:not(select)`);if(i(a)){a.tagName!=="INPUT"&&t.preventDefault(),this.setPurchase(c(a,"purchase"));return}let r=e.closest(l("qty-plus"));if(i(r)){t.preventDefault(),this.setQuantity(this.quantity+1);return}let u=e.closest(l("qty-minus"));if(i(u)){t.preventDefault(),this.setQuantity(this.quantity-1);return}let v=e.closest(l("add-to-cart"));i(v)&&(t.preventDefault(),this.onAddClick(v))}),this.root.addEventListener("change",t=>{let e=t.target;i(e)&&(e.matches(`select${l("option")}`)?this.select(this.optName(c(e,"option")),e.value):e.matches(`select${l("variant-select")}`)?this.selectVariant(e.value):e.matches(`select${l("plan")}`)?e.value?this.selectPlan(e.value):this.setPurchase("one-time"):e.matches(`select${l("purchase")}`)?this.setPurchase(e.value):e.matches(l("qty"))&&this.setQuantity(e.value))})}onAddClick(i){let t=i.querySelector(l("add-label"))||i,e=c(i,"adding-text"),s=o=>d(t,o);t.dataset.tetherLabel===void 0&&(t.dataset.tetherLabel=t.tagName==="INPUT"?t.value:t.textContent),it(i,async()=>{e&&s(e);try{await this.addToCart()}catch(o){G(o,"add to cart failed"),x("error",{error:o,context:"add-to-cart"},this.root)}finally{e&&s(t.dataset.tetherLabel)}}).then(()=>{this.renderVariant()})}renderProduct(){let i=this.product;C.has(i.handle)||this.$(`${l("option-list")},select${l("option")}`).map(s=>c(s,"option-list")||c(s,"option")).some(s=>i.options.some(o=>o.name===s))&&ft([i]);let t=this.product;this.$(l("bind")).forEach(e=>{let s=c(e,"bind")||"",o={title:t.title,"description-text":t.description,vendor:t.vendor,type:t.productType,handle:t.handle}[s];if(o!==void 0)return d(e,o);switch(s){case"description":e.innerHTML=t.descriptionHtml||"";return;case"published-at":return d(e,X(t.publishedAt));case"min-price":return d(e,$(t.priceRange.minVariantPrice));case"max-price":return d(e,$(t.priceRange.maxVariantPrice));case"featured-image":return I(e,t.featuredImage?.url,t.featuredImage?.altText||t.title);case"url":case"link":e.setAttribute("href",J(t.handle,t.id)),s==="url"&&!e.firstElementChild&&!e.textContent.trim()&&d(e,t.title);return;case"images":{let a=[...e.children].map(r=>r.tagName==="IMG"?r:r.querySelector("img"));if(!tt(e)&&a.length===t.images.nodes.length&&a.every((r,u)=>Z(r?.getAttribute("src"),t.images.nodes[u].url)))return}return A(e,t.images.nodes,(a,r)=>{let u=a.matches(`img,${l("bind","image")}`)?a:a.querySelector("img")||a;I(u,r.url,r.altText||t.title)});case"tags":{let a=(e.getAttribute("exclude")||"").split(",").map(r=>r.trim()).filter(Boolean);return A(e,t.tags.filter(r=>!a.includes(r)),(r,u)=>d(r,u))}default:if(/^image:\d+$/.test(s)){let a=t.images.nodes[s.slice(6)-1]||t.featuredImage;return I(e,a?.url,a?.altText||t.title)}if(s.startsWith("metafield:")){let a=mt(t,s.slice(10));return a?a.reference?.image?I(e,a.reference.image.url,a.reference.image.altText):(/^(rich_text|multi_line_text)_field$/.test(a.type)&&(e.style.whiteSpace="pre-line"),d(e,a.value)):d(e,"")}return}}),this.$(l("option-list")).forEach(e=>{let s=this.optName(c(e,"option-list")),o=t.options.find(a=>a.name===s);return!o||o.optionValues.length<=1&&P(e,"hide-single")?q(e,!1):A(e,o.optionValues,(a,r)=>{a.setAttribute(g("option-value"),r.name);let u=a.querySelector(l("bind","option-value"));u?d(u,r.name):a.firstElementChild||d(a,r.name);let v=a.querySelector(l("bind","swatch"));v&&r.swatch?.color&&(v.style.backgroundColor=r.swatch.color),v&&r.swatch?.image?.previewImage&&I(v,r.swatch.image.previewImage.url,r.name)})}),this.$(`select${l("option")}`).forEach(e=>{let s=t.options.find(o=>o.name===this.optName(c(e,"option")));if(!s)return q(e,!1);e.innerHTML="",s.optionValues.forEach(o=>e.appendChild(new Option(o.name,o.name)))}),this.$(`select${l("variant-select")}`).forEach(e=>{e.innerHTML="",t.variants.nodes.forEach(s=>e.appendChild(new Option(s.title,s.id)))}),this.$(l("plan-list")).forEach(e=>{let s=(c(e,"plan-list")||"").trim(),o=["","true","all","*"].includes(s.toLowerCase())?null:s,a=this.plans.filter(r=>!o||r.group.name===o);A(e,a,(r,u)=>{r.setAttribute(g("plan-value"),u.id),!r.firstElementChild&&!r.querySelector(l("plan-bind"))&&d(r,u.name)})}),this.$(`select${l("plan")}`).forEach(e=>{e.innerHTML="",!t.requiresSellingPlan&&c(e,"plan")!=="subscription-only"&&e.appendChild(new Option(e.getAttribute(g("one-time-label"))||"One-time purchase","")),this.plans.forEach(s=>e.appendChild(new Option(s.name,s.id)))})}renderVariant(){let i=this.product,t=this.findVariant();if(t||([t]=i.variants.nodes,t&&(this.selected={},t.selectedOptions.forEach(n=>{this.selected[n.name]=n.value}))),this.variant=t,!t)return;if(this.plans.length&&!S(t,this.planId)){let n=this.plans.find(h=>S(t,h.id));n&&(this.planId=n.id)}let e=this.isSubscription,s=t.price,o=this.planId?N(t,this.planId):null,a=e?o:s,r=e&&S(t,this.planId)?.priceAdjustments?.[0]?.compareAtPrice||t.compareAtPrice,u=r&&parseFloat(r.amount)>parseFloat(a.amount),v=u?Math.round((1-parseFloat(a.amount)/parseFloat(r.amount))*100):0,L=this.planId?M(t,this.planId):{amount:null,percentage:0},O=this.plan,ut={amount:(parseFloat(a.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:a.currencyCode},f=$,U=n=>z(n),j={price:()=>f(a),"total-price":()=>f(ut),"one-time-price":()=>f(s),"subscription-price":()=>f(o),"subscription-savings":()=>U(L.percentage),"subscription-savings-amount":()=>f(L.amount),"checkout-charge":()=>{let n=e?W(t,this.planId):a;return n&&f({amount:(parseFloat(n.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:n.currencyCode})},"plan-name":()=>O?.name,"plan-description":()=>O?.description,"plan-group":()=>O?.group?.name,"compare-at-price":()=>u?f(r):"","unit-price":()=>f(t.unitPrice),"discount-percentage":()=>`${v}%`,"discount-amount":()=>u?f({amount:String(parseFloat(r.amount)-parseFloat(a.amount)),currencyCode:a.currencyCode}):"","variant-title":()=>t.title,"variant-id":()=>t.id,sku:()=>t.sku,barcode:()=>t.barcode,stock:()=>t.quantityAvailable,quantity:()=>this.quantity};this.$(l("bind")).forEach(n=>{let h=c(n,"bind");h==="variant-image"?I(n,t.image?.url||i.featuredImage?.url,t.image?.altText||i.title):j[h]&&d(n,j[h]())}),this.$(l("option-selected")).forEach(n=>d(n,this.selected[this.optName(c(n,"option-selected"))]||"")),this.$(l("option-list")).forEach(n=>{let h=this.optName(c(n,"option-list"));B(n,l("option-value")).forEach(p=>{let b=c(p,"option-value");k(p,this.selected[h]===b);let m=!this.isValueAvailable(h,b);p.classList.toggle("is-unavailable",m),p.setAttribute("data-unavailable",m?"true":"false")})}),this.$(`select${l("option")}`).forEach(n=>{n.value=this.selected[this.optName(c(n,"option"))]||""}),this.$(`select${l("variant-select")}`).forEach(n=>{n.value=t.id}),this.$(l("purchase")).forEach(n=>{if(n.tagName==="SELECT"){n.value=this.purchase;return}let h=c(n,"purchase");k(n,h===this.purchase);let p=h==="subscription"?!this.subscriptionAvailable:i.requiresSellingPlan;n.classList.toggle("is-unavailable",p)}),this.$(l("plan-value")).forEach(n=>{let h=c(n,"plan-value"),p=this.plans.find(m=>m.id===h),b=!!S(t,h);k(n,e&&h===this.planId),n.classList.toggle("is-unavailable",!b),B(n,l("plan-bind")).forEach(m=>{let y=Y(p),Q=M(t,h),ht=c(m,"plan-bind"),R={name:()=>p?.name,option:()=>(p?.options||[]).map(dt=>dt.value).join(", "),description:()=>p?.description,price:()=>f(N(t,h)),savings:()=>U(Q.percentage),"savings-amount":()=>f(Q.amount),adjustment:()=>y?y.type==="percentage"?`${y.value}%`:f(y.value):""}[ht];R&&d(m,R())})}),this.$(`select${l("plan")}`).forEach(n=>{n.value=e?this.planId:""});let _=t.quantityAvailable!=null&&t.quantityAvailable>0&&t.quantityAvailable<=(T.lowStock??5),H={"in-stock":t.availableForSale,"out-of-stock":!t.availableForSale,backorder:t.availableForSale&&t.currentlyNotInStock,"on-sale":!!u,"not-on-sale":!u,"has-variants":i.variants.nodes.length>1,"single-variant":i.variants.nodes.length===1,"low-stock":_,"plenty-in-stock":t.availableForSale&&!_,"subscription-available":this.subscriptionAvailable,"subscription-unavailable":!this.subscriptionAvailable,"subscription-only":!!i.requiresSellingPlan,"one-time-available":!i.requiresSellingPlan,"subscription-selected":e,"one-time-selected":!e,"has-savings":e?L.percentage>0:!!u,loading:!1,ready:!0,error:!1,"not-found":!1};this.$(l("show")).forEach(n=>{let h=c(n,"show");h in H&&(rt.includes(h)&&!ot(n,this.root)||q(n,H[h]))}),this.root.classList.toggle("is-subscription",e),this.root.setAttribute(g("purchase-mode"),e?"subscription":"one-time"),this.$(l("add-to-cart")).forEach(n=>{let h=!t.availableForSale;n.classList.toggle("is-disabled",h),n.setAttribute("aria-disabled",String(h)),"disabled"in n&&(n.disabled=h);let p=c(n,"soldout-text"),b=c(n,"subscribe-text");if(p||b){let m=n.querySelector(l("add-label"))||n;m.dataset.tetherLabel===void 0&&(m.dataset.tetherLabel=m.tagName==="INPUT"?m.value:m.textContent);let y=m.dataset.tetherLabel;e&&b&&(y=b),h&&p&&(y=p),n.getAttribute("aria-busy")!=="true"&&d(m,y)}}),x("variant-changed",{product:i,variant:t,selected:{...this.selected},purchase:this.purchase,sellingPlanId:e?this.planId:null},this.root)}};export{pt as a,ft as b,ct as c};
@@ -0,0 +1,11 @@
1
+ import{c as D}from"./chunk-64TUD3QR.js";import{a as b,d as q}from"./chunk-RREHGH4A.js";import{c as P}from"./chunk-FIOZPPC5.js";import{e as V}from"./chunk-AJLPU2JC.js";import{F as M,b as i,d as S,i as E,l as x,n as h,o as c,p as g,s as p}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var I=e=>{let n=/^(\d{4})-(01|04|07|10)$/.exec(String(e||""));return n?{y:+n[1],m:+n[2]}:null},B=(e,n)=>`${e}-${String(n).padStart(2,"0")}`;function A(e,n=1){let o=I(e);if(!o)throw new Error(`not a quarterly Shopify API version: ${e}`);let s=o.y*4+(o.m-1)/3+n;return B(Math.floor(s/4),s%4*3+1)}function T(e,n=new Date){if(e==="unstable")return{version:e,ok:!1,note:'"unstable" changes without notice: pin a dated version such as 2026-07'};let o=I(e);if(!o)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let s=new Date(Date.UTC(o.y,o.m-1,1)),r=new Date(Date.UTC(o.y+1,o.m-1,1)),f=(r-n)/(30.44*24*3600*1e3),l=`supported until about ${r.toISOString().slice(0,7)}`;return s>n?l="not released yet (release candidate at best)":f<=0?l="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)":f<3&&(l=`${l}: plan the upgrade to ${A(e)} or later (see README)`),{version:e,ok:s<=n&&f>0,monthsLeft:Math.round(f),next:A(e),note:l}}var C=new Set(["in-stock","out-of-stock","backorder","low-stock","plenty-in-stock","on-sale","not-on-sale","has-variants","single-variant","subscription-available","subscription-unavailable","subscription-only","one-time-available","subscription-selected","one-time-selected","has-savings","loading","ready","error","not-found","cart-empty","cart-filled","cart-has-subscription","cart-no-subscription","cart-has-discount","cart-error","cart-warning","list-empty","list-filled","search-empty","search-results","logged-in","logged-out","orders-empty","orders-loading"]),N=new Set(["title","description","description-text","vendor","type","handle","published-at","price","total-price","compare-at-price","unit-price","min-price","max-price","discount-percentage","discount-amount","variant-title","variant-id","sku","barcode","stock","quantity","featured-image","variant-image","images","tags","link","url","one-time-price","subscription-price","subscription-savings","subscription-savings-amount","checkout-charge","plan-name","plan-description","plan-group","option-value","swatch","image"]),U=new Set(`account account-bind account-link account-login account-logout add-label add-to-cart adding-text
2
+ always-enabled bind cart-checkout-charge cart-clear cart-close cart-count cart-discounts cart-drawer cart-label cart-lines
3
+ cart-note cart-open cart-subtotal cart-total cart-warning checkout code collection collection-bind countries country
4
+ country-bind country-label country-select default-plan default-purchase discount discount-code discount-form discount-input
5
+ discount-remove display error group group-add hide-single language limit line line-attribute line-attributes line-id
6
+ line-minus line-plan line-plus line-remove line-show list load-more market-pending one-time-label option option-list
7
+ option-selected option-value order-bind order-line order-lines orders page-country page-language page-locale page-title plan plan-bind plan-list
8
+ plan-value product products purchase purchase-mode qty qty-minus qty-plus quantity recommendations reverse search
9
+ search-bind search-collections search-input search-limit search-min search-products search-queries search-results
10
+ search-state show soldout-text sort state subscribe-text variant variant-select variant-url max-width max-height crop
11
+ sig label hydrated busy`.split(/\s+/).filter(Boolean));function O(e,n){let o=Array.from({length:e.length+1},(s,r)=>[r,...Array(n.length).fill(0)]);for(let s=1;s<=n.length;s++)o[0][s]=s;for(let s=1;s<=e.length;s++)for(let r=1;r<=n.length;r++)o[s][r]=Math.min(o[s-1][r]+1,o[s][r-1]+1,o[s-1][r-1]+(e[s-1]===n[r-1]?0:1));return o[e.length][n.length]}function $(e,n,o=""){let s=null,r=1/0;for(let f of n){let l=O(String(e),f);l<r&&(r=l,s=f)}return s&&r<=Math.max(2,Math.floor(String(e).length/4))?` Did you mean "${o}${s}"?`:""}var L=e=>e?`${String(e).slice(0,4)}\u2026${String(e).slice(-4)} (${String(e).length} chars)`:"(missing)";function j(e){let n=e.id?`#${e.id}`:"",o=e.className&&typeof e.className=="string"?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";return`<${e.tagName.toLowerCase()}${n}${o}>`}function R(e=document){let n=[],o=(t,a,u)=>n.push({level:t,message:a,element:u?j(u):void 0,el:u}),s=t=>!!t.closest(c("product")),r=`${c("collection")},${c("products")},${c("recommendations")}`;p(e,c("product")).forEach(t=>{if(t.closest(r)&&t.closest(c("list")))return;let{key:a,fromUrl:u,raw:y}=b(t);y?u&&!a&&o("warn",`${h("product")}="${y}" but this URL has no value for it (e.g. ?handle=my-product).`,t):o("error",`${h("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`,t)}),["bind","option-list","option","variant-select","add-to-cart","purchase","plan-list","plan","qty","line-attribute"].forEach(t=>{p(e,c(t)).forEach(a=>{s(a)||t==="line-attribute"&&a.closest(c("group"))||o("warn",`${h(t)} outside any ${h("product")}: it does nothing here.`,a)})}),p(e,c("group-add")).forEach(t=>{t.closest(c("group"))||o("warn",`${h("group-add")} outside a ${h("group")}.`,t)}),["option-list","plan-list","cart-lines","list"].forEach(t=>p(e,c(t)).forEach(a=>{!a.firstElementChild&&!M(a)&&o("warn",`${h(t)} without a template child: put one example element inside it.`,a)})),p(e,r).forEach(t=>{p(t,c("list")).length||o("error",`List without a ${h("list")} child: products have nowhere to render.`,t)}),p(e,c("show")).forEach(t=>{let a=g(t,"show");C.has(a)||o("warn",`Unknown ${h("show")}="${a}".${$(a,C)}`,t)}),p(e,c("bind")).forEach(t=>{let a=g(t,"bind")||"";!a||N.has(a)||/^image:\d+$/.test(a)||a.startsWith("metafield:")||o("warn",`Unknown ${h("bind")}="${a}": it stays empty.${$(a,N)}`,t)});let l=`${i.prefix}-`,w=new Set;return p(e,"*").forEach(t=>{for(let a of t.attributes){if(!a.name.startsWith(l))continue;let u=a.name.slice(l.length);U.has(u)||w.has(u)||(w.add(u),o("warn",`Unknown attribute ${a.name}: Tether ignores it.${$(u,U,l)}`,t))}}),p(e,c("bind")).forEach(t=>{let a=g(t,"bind")||"";if(!a.startsWith("metafield:"))return;let u=a.slice(10);(i.metafields||[]).some(m=>(typeof m=="string"?m:`${m.namespace}.${m.key}`)===u)||o("error",`${h("bind")}="${a}" but "${u}" is not in config.metafields, so it stays empty.`,t)}),p(e,c("cart-open")).length&&!p(e,c("cart-drawer")).length&&o("warn",`${h("cart-open")} exists but there is no ${h("cart-drawer")} on this page.`),p(e,c("cart-drawer")).length>1&&o("warn",`More than one ${h("cart-drawer")}.`),p(e,`[${h("state")}="error"]`).forEach(t=>{t.matches(q())&&o("error",`Scope failed to load (${g(t,"error")||"error"}).`,t)}),n}async function X({root:e=document,silent:n=!1,version:o,now:s=new Date}={}){let r={version:o,config:{domain:i.domain||"(missing)",token:L(i.token),apiVersion:i.apiVersion,endpoint:i.domain?E():null,country:i.country,language:i.language,locale:i.locale,markets:i.markets||null,prefix:i.prefix,productPath:i.productPath,metafields:i.metafields,autoMount:i.autoMount,observe:i.observe,onError:typeof i.onError=="function"},apiVersion:T(i.apiVersion,s),market:{country:i.country||null,language:i.language||null,locale:i.locale||null,detected:i.markets?.detect?D(i.markets):null},reachable:!1,shop:null,latencyMs:null,products:[],sellingPlans:[],problems:[]};if(!S())r.problems.push({level:"error",message:"TETHER_CONFIG needs domain and token."});else{let f=Date.now();try{let l=await x("query TetherDiagnose { shop { name primaryDomain { url } paymentSettings { currencyCode } } }",{},{context:!1});r.reachable=!0,r.shop={name:l.shop?.name,url:l.shop?.primaryDomain?.url,currency:l.shop?.paymentSettings?.currencyCode}}catch(l){r.problems.push({level:"error",message:`Storefront API not reachable: ${l.message||l.code||"unknown error"}`})}if(r.latencyMs=Date.now()-f,r.reachable){let l=[...new Set(p(e,c("product")).map(t=>b(t).key).filter(Boolean))].slice(0,20);(await Promise.allSettled(l.map(t=>P(t)))).forEach((t,a)=>{if(t.status==="fulfilled"){let u=t.value,y=V(u);r.products.push({key:l[a],handle:u.handle,title:u.title,plans:y.length,requiresSellingPlan:u.requiresSellingPlan}),y.forEach(m=>r.sellingPlans.push({product:u.handle,group:m.group?.name,plan:m.name,id:m.id})),p(e,c("product")).filter(m=>b(m).key===l[a]&&m.querySelector(c("add-to-cart"))).forEach(m=>{let k=new Set(p(m,`${c("option-list")},select${c("option")}`).map(d=>g(d,"option-list")||g(d,"option")));if(!k.size&&p(m,`select${c("variant-select")}`).length)return;let v=(u.options||[]).map(d=>d.name);i.language||[...k].filter(d=>d&&!v.includes(d)).forEach(d=>{r.problems.push({level:"warn",message:`Product "${u.handle}" has no option "${d}" (its options: ${v.join(", ")||"none"}).${$(d,v)}`})}),(u.options||[]).filter(d=>d.optionValues.length>1&&!k.has(d.name)).forEach(d=>{r.problems.push({level:"warn",message:`Product "${u.handle}": option "${d.name}" (${d.optionValues.length} values) has no tether-option-list, so visitors can't choose it.`})})})}else r.products.push({key:l[a],error:t.reason?.message}),r.problems.push({level:"error",message:`Product "${l[a]}": ${t.reason?.message||t.reason?.code||"not loaded"}. Is it published to the Headless channel?`})})}}return(!r.apiVersion.ok||(r.apiVersion.monthsLeft??99)<3)&&r.problems.push({level:r.apiVersion.ok?"warn":"error",message:`apiVersion ${i.apiVersion}: ${r.apiVersion.note}`}),typeof document<"u"&&r.problems.push(...R(e)),n||Y(r),r}function Y(e){let n=console,o=e.problems.filter(s=>s.level==="error").length;n.group?.(`[${i.prefix}] diagnose: ${o?`${o} error(s)`:"no errors"}, ${e.problems.length-o} warning(s)`),n.log("version",e.version,"| API",e.apiVersion.version,`(${e.apiVersion.note})`),n.log("config",e.config),e.market&&n.log("market",`in use: ${[e.market.country,e.market.language].filter(Boolean).join(" / ")||"the store default"}`,e.market.detected?`(detection picks ${JSON.stringify(e.market.detected)})`:""),n.log(e.reachable?`Storefront API reachable: ${e.shop?.name} (${e.latencyMs} ms)`:"Storefront API NOT reachable"),e.products.length&&(n.table||n.log)(e.products),e.sellingPlans.length?(n.table||n.log)(e.sellingPlans):e.reachable&&n.log("No selling plans on the products of this page."),e.problems.forEach(s=>(s.level==="error"?n.error:n.warn)(s.message,s.el||"")),n.groupEnd?.()}export{T as apiVersionStatus,R as checkMarkup,X as diagnose,$ as didYouMean};
@@ -1 +1 @@
1
- import{a as b}from"./chunk-6R752OYZ.js";import"./chunk-4UR45XTC.js";import{b as l}from"./chunk-BGIKQY6H.js";import"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{L as w,M as h,b as o,f as p,g,o as u,p as d,q as f,s as m,u as y}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";async function q(e){let t=e.closest(u("group"));if(!t)return null;let n=d(t,"group"),s=h(w(t,"line-attributes")),i=n?[{key:"_group",value:n},...s]:s,a=m(t,u("product")).map(r=>b.get(r)).filter(r=>r&&r.variant?.availableForSale&&r.quantity>0).map(r=>{let c=r.getLine();return c.attributes=[...c.attributes||[],...i],c});if(!a.length)return p("group-add: nothing selected"),null;try{let r=await l.add(a);return y("group-added",{group:n,lines:a},t),r}catch(r){return g(r,"group add"),null}}function A(e){if(e.key===o.storageKey||e.key===`${o.storageKey}:seen`)l.init();else if(e.key===`${o.prefix}:market:${o.domain}`&&e.newValue)try{let t=JSON.parse(e.newValue);t?.country&&window.Tether?.setCountry(t.country,{language:t.language??null,locale:t.locale,remember:!1}).catch(()=>{})}catch{}}var k=new WeakMap;function K(e,{variant:t,sellingPlanId:n}){let s=`${t.id}|${n||""}`,i=k.get(e);if(k.set(e,s),!(!i||i===s)&&!(!f(e,"variant-url")&&!(o.variantUrl&&document.querySelector(u("product"))===e)))try{let a=new URL(window.location.href);a.searchParams.set("variant",t.id.split("/").pop()),n?a.searchParams.set("selling_plan",n.split("/").pop()):a.searchParams.delete("selling_plan"),window.history.replaceState(window.history.state,"",a)}catch{}}export{q as addGroup,A as onStorage,K as writeVariantUrl};
1
+ import{a as b}from"./chunk-ZIUIWEON.js";import"./chunk-RREHGH4A.js";import{b as l}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{L as w,M as h,b as o,f as p,g,o as u,p as d,q as f,s as m,u as y}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";async function q(e){let t=e.closest(u("group"));if(!t)return null;let n=d(t,"group"),s=h(w(t,"line-attributes")),i=n?[{key:"_group",value:n},...s]:s,a=m(t,u("product")).map(r=>b.get(r)).filter(r=>r&&r.variant?.availableForSale&&r.quantity>0).map(r=>{let c=r.getLine();return c.attributes=[...c.attributes||[],...i],c});if(!a.length)return p("group-add: nothing selected"),null;try{let r=await l.add(a);return y("group-added",{group:n,lines:a},t),r}catch(r){return g(r,"group add"),null}}function A(e){if(e.key===o.storageKey||e.key===`${o.storageKey}:seen`)l.init();else if(e.key===`${o.prefix}:market:${o.domain}`&&e.newValue)try{let t=JSON.parse(e.newValue);t?.country&&window.Tether?.setCountry(t.country,{language:t.language??null,locale:t.locale,remember:!1}).catch(()=>{})}catch{}}var k=new WeakMap;function K(e,{variant:t,sellingPlanId:n}){let s=`${t.id}|${n||""}`,i=k.get(e);if(k.set(e,s),!(!i||i===s)&&!(!f(e,"variant-url")&&!(o.variantUrl&&document.querySelector(u("product"))===e)))try{let a=new URL(window.location.href);a.searchParams.set("variant",t.id.split("/").pop()),n?a.searchParams.set("selling_plan",n.split("/").pop()):a.searchParams.delete("selling_plan"),window.history.replaceState(window.history.state,"",a)}catch{}}export{q as addGroup,A as onStorage,K as writeVariantUrl};
@@ -1 +1 @@
1
- import{a as k,c as U,e as z,f as B,g as M,h as L,i as N}from"./chunk-CISGFYOF.js";import{a as C,b,c as T,d as A,e as I,f as v}from"./chunk-YZMBXS6Y.js";import"./chunk-6R752OYZ.js";import"./chunk-4UR45XTC.js";import{b as d}from"./chunk-BGIKQY6H.js";import{d as E}from"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{b as t,g as p,h as w,n as g,o as h,p as P,u as x}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";function O(s=document){let u=L(s,`select${h("country-select")}`),m=L(s,h("country-bind"));return!u.length&&!m.length?Promise.resolve():v().then(l=>{let r=(t.country||l.country?.isoCode||"").toUpperCase(),c=[...l.availableCountries||[]].sort((e,o)=>e.name.localeCompare(o.name,t.locale||void 0)),i=c.find(e=>e.isoCode===r)||l.country,f=(e,o)=>e.replace(/\{name\}/g,o.name).replace(/\{code\}/g,o.isoCode).replace(/\{currency\}/g,o.currency?.isoCode||"").replace(/\{symbol\}/g,o.currency?.symbol||"");u.forEach(e=>{let o=e.getAttribute(g("country-label"))||"{name} ({currency})",a=(e.getAttribute(g("countries"))||"").toUpperCase().split(/[\s,]+/).filter(Boolean),n=a.length?a.map(y=>c.find(S=>S.isoCode===y)).filter(Boolean):c;e.innerHTML="",n.forEach(y=>e.appendChild(new Option(f(o,y),y.isoCode))),e.value=r,e.value!==r&&(e.selectedIndex=-1),e.disabled=n.length<2&&!e.hasAttribute(g("always-enabled"))}),m.forEach(e=>{let o=P(e,"country-bind")||"name",a={name:i?.name,code:i?.isoCode,currency:i?.currency?.isoCode,symbol:i?.currency?.symbol}[o];e.textContent=a||""})}).catch(l=>p(l,"country select"))}async function q(s,{language:u,locale:m,remember:l=!0}={}){let r=C(s);if(!r)throw new w(`Not a country code: ${s}`,{code:"INVALID_COUNTRY"});let c=Object.values(t.markets?.locales||{}).find(n=>C(n?.country)===r),i=m||c?.locale,f=i||t.locale,e=u!==void 0?b(u):c?c.language?b(c.language):void 0:t.language,o=r!==String(t.country||"").toUpperCase()||e!==t.language||f!==t.locale;if(t.country=r,t.language=e||void 0,t.locale=f,l&&A({country:r,language:e,locale:i}),!o)return O(),d.state;E();let a=[];return u!==void 0&&I(),d.id()&&a.push(d.setBuyerIdentity({countryCode:r},{create:!1}).catch(n=>p(n,"cart country"))),M(),B.forEach(n=>a.push(n.load())),z.forEach(n=>{n.closest(k())||(U.delete(n),N(n))}),O(),x("country-changed",{country:r,language:t.language}),await Promise.all(a),d.state}export{T as detectMarket,v as getLocalization,O as renderCountrySelects,q as setCountry};
1
+ import{a as k,c as U,e as z,f as B,g as M,h as L,i as N}from"./chunk-VCPI7MJ2.js";import{a as C,b,c as T,d as A,e as I,f as v}from"./chunk-64TUD3QR.js";import"./chunk-ZIUIWEON.js";import"./chunk-RREHGH4A.js";import{b as d}from"./chunk-L2TRRKYV.js";import{d as E}from"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{b as t,g as p,h as w,n as g,o as h,p as P,u as x}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";function O(s=document){let u=L(s,`select${h("country-select")}`),m=L(s,h("country-bind"));return!u.length&&!m.length?Promise.resolve():v().then(l=>{let r=(t.country||l.country?.isoCode||"").toUpperCase(),c=[...l.availableCountries||[]].sort((e,o)=>e.name.localeCompare(o.name,t.locale||void 0)),i=c.find(e=>e.isoCode===r)||l.country,f=(e,o)=>e.replace(/\{name\}/g,o.name).replace(/\{code\}/g,o.isoCode).replace(/\{currency\}/g,o.currency?.isoCode||"").replace(/\{symbol\}/g,o.currency?.symbol||"");u.forEach(e=>{let o=e.getAttribute(g("country-label"))||"{name} ({currency})",a=(e.getAttribute(g("countries"))||"").toUpperCase().split(/[\s,]+/).filter(Boolean),n=a.length?a.map(y=>c.find(S=>S.isoCode===y)).filter(Boolean):c;e.innerHTML="",n.forEach(y=>e.appendChild(new Option(f(o,y),y.isoCode))),e.value=r,e.value!==r&&(e.selectedIndex=-1),e.disabled=n.length<2&&!e.hasAttribute(g("always-enabled"))}),m.forEach(e=>{let o=P(e,"country-bind")||"name",a={name:i?.name,code:i?.isoCode,currency:i?.currency?.isoCode,symbol:i?.currency?.symbol}[o];e.textContent=a||""})}).catch(l=>p(l,"country select"))}async function q(s,{language:u,locale:m,remember:l=!0}={}){let r=C(s);if(!r)throw new w(`Not a country code: ${s}`,{code:"INVALID_COUNTRY"});let c=Object.values(t.markets?.locales||{}).find(n=>C(n?.country)===r),i=m||c?.locale,f=i||t.locale,e=u!==void 0?b(u):c?c.language?b(c.language):void 0:t.language,o=r!==String(t.country||"").toUpperCase()||e!==t.language||f!==t.locale;if(t.country=r,t.language=e||void 0,t.locale=f,l&&A({country:r,language:e,locale:i}),!o)return O(),d.state;E();let a=[];return u!==void 0&&I(),d.id()&&a.push(d.setBuyerIdentity({countryCode:r},{create:!1}).catch(n=>p(n,"cart country"))),M(),B.forEach(n=>a.push(n.load())),z.forEach(n=>{n.closest(k())||(U.delete(n),N(n))}),O(),x("country-changed",{country:r,language:t.language}),await Promise.all(a),d.state}export{T as detectMarket,v as getLocalization,O as renderCountrySelects,q as setCountry};
@@ -1 +1 @@
1
- import{A as N,B as O,D as q,G as V,b as y,g as C,l as E,n as D,o as u,p,r as R,s as h,u as U,w as P}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var H="query TetherPredictive($q:String!,$limit:Int!){predictiveSearch(query:$q,limit:$limit,limitScope:EACH,types:[PRODUCT,COLLECTION,QUERY]){products{id handle title availableForSale featuredImage{url altText}priceRange{minVariantPrice{amount currencyCode}}}collections{handle title image{url altText}}queries{text}}}",F=new WeakSet,W=0;function J(s=document){[...s.matches?.(u("search"))?[s]:[],...h(s,u("search"))].forEach(c=>{F.has(c)||(F.add(c),j(c))})}function j(s){let n=s.querySelector(u("search-input"))||s.querySelector("input"),c=s.querySelector(u("search-results"));if(!n||!c)return;let M=parseInt(p(s,"search-limit")||"6",10)||6,v=parseInt(p(s,"search-min")||"2",10)||2,k=c.id||(c.id=`${y.prefix}-search-${++W}`);n.setAttribute("role","combobox"),n.setAttribute("aria-autocomplete","list"),n.setAttribute("aria-controls",k),n.setAttribute("aria-expanded","false"),n.setAttribute("autocomplete","off"),c.hasAttribute("role")||c.setAttribute("role","listbox"),c.hidden=!0;let x=0,w=null,I="",L=new Map,b=t=>s.setAttribute(D("search-state"),t),f=t=>{s.classList.toggle("is-open",t),c.hidden=!t,n.setAttribute("aria-expanded",String(t)),t||n.removeAttribute("aria-activedescendant")},S=()=>h(c,'[role="option"]');async function Q(t){let e=++x;if(t.length<v){f(!1),b("idle");return}b("loading");try{let r=L.get(t)||(await E(H,{q:t,limit:M})).predictiveSearch;if(L.set(t,r),e!==x)return;Y(r,t)}catch(r){if(e!==x)return;b("error"),C(r,"search")}}function Y(t,e){let r=t?.products||[],o=t?.collections||[],l=(t?.queries||[]).filter(i=>i.text.toLowerCase()!==e.toLowerCase()),d=(i,a,A)=>h(c,u(i)).forEach(g=>{V(g,a,A),q(g,a.length>0)});d("search-products",r,(i,a)=>{$(i,{title:a.title,price:P(a.priceRange?.minVariantPrice),image:a.featuredImage}),T(i,R(a.handle,a.id)),i.classList.toggle("is-sold-out",!a.availableForSale)}),d("search-collections",o,(i,a)=>{$(i,{title:a.title,image:a.image}),T(i,`${(y.collectionPath||"/collection").replace(/\/$/,"")}/${a.handle}`)}),d("search-queries",l,(i,a)=>{$(i,{text:a.text});let A=i.tagName==="A"?i:i.querySelector("a"),g=s.getAttribute("action")||"/search";A&&A.setAttribute("href",`${g}${g.includes("?")?"&":"?"}${n.name||"q"}=${encodeURIComponent(a.text)}`)});let m=r.length+o.length+l.length;h(s,u("show")).forEach(i=>{let a=p(i,"show");a==="search-empty"&&q(i,m===0),a==="search-results"&&q(i,m>0)}),S().forEach((i,a)=>{i.id||(i.id=`${k}-${a}`),i.setAttribute("aria-selected","false")}),b(m?"ready":"empty"),f(!0),U("search",{term:e,products:r,collections:o,queries:l},s)}function $(t,e){h(t,u("search-bind")).forEach(r=>{let o=p(r,"search-bind");o==="image"?N(r,e.image?.url,e.image?.altText||e.title):e[o]!=null&&O(r,e[o])})}function T(t,e){let r=t.tagName==="A"?t:t.querySelector("a");r&&(r.setAttribute("href",e),r.setAttribute("role","option"))}n.addEventListener("input",()=>{let t=n.value.trim();t!==I&&(I=t,clearTimeout(w),w=setTimeout(()=>Q(t),y.searchDelay??150))}),n.addEventListener("focus",()=>{n.value.trim().length>=v&&S().length&&f(!0)}),n.addEventListener("keydown",t=>{let e=S(),r=e.findIndex(l=>l.getAttribute("aria-selected")==="true"),o=l=>{e.forEach((d,m)=>d.setAttribute("aria-selected",String(m===l))),e[l]&&(n.setAttribute("aria-activedescendant",e[l].id),e[l].scrollIntoView?.({block:"nearest"}))};t.key==="ArrowDown"&&e.length?(t.preventDefault(),f(!0),o((r+1)%e.length)):t.key==="ArrowUp"&&e.length?(t.preventDefault(),o(r<=0?e.length-1:r-1)):t.key==="Enter"&&r>=0?(t.preventDefault(),e[r].click()):t.key==="Escape"&&f(!1)}),document.addEventListener("click",t=>{s.contains(t.target)||f(!1)})}export{J as mountSearch};
1
+ import{A as N,B as O,D as q,G as V,b as y,g as C,l as E,n as D,o as u,p,r as R,s as h,u as U,w as P}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var H="query TetherPredictive($q:String!,$limit:Int!){predictiveSearch(query:$q,limit:$limit,limitScope:EACH,types:[PRODUCT,COLLECTION,QUERY]){products{id handle title availableForSale featuredImage{url altText}priceRange{minVariantPrice{amount currencyCode}}}collections{handle title image{url altText}}queries{text}}}",F=new WeakSet,W=0;function J(s=document){[...s.matches?.(u("search"))?[s]:[],...h(s,u("search"))].forEach(c=>{F.has(c)||(F.add(c),j(c))})}function j(s){let n=s.querySelector(u("search-input"))||s.querySelector("input"),c=s.querySelector(u("search-results"));if(!n||!c)return;let M=parseInt(p(s,"search-limit")||"6",10)||6,v=parseInt(p(s,"search-min")||"2",10)||2,k=c.id||(c.id=`${y.prefix}-search-${++W}`);n.setAttribute("role","combobox"),n.setAttribute("aria-autocomplete","list"),n.setAttribute("aria-controls",k),n.setAttribute("aria-expanded","false"),n.setAttribute("autocomplete","off"),c.hasAttribute("role")||c.setAttribute("role","listbox"),c.hidden=!0;let x=0,w=null,I="",L=new Map,b=t=>s.setAttribute(D("search-state"),t),f=t=>{s.classList.toggle("is-open",t),c.hidden=!t,n.setAttribute("aria-expanded",String(t)),t||n.removeAttribute("aria-activedescendant")},S=()=>h(c,'[role="option"]');async function Q(t){let e=++x;if(t.length<v){f(!1),b("idle");return}b("loading");try{let r=L.get(t)||(await E(H,{q:t,limit:M})).predictiveSearch;if(L.set(t,r),e!==x)return;Y(r,t)}catch(r){if(e!==x)return;b("error"),C(r,"search")}}function Y(t,e){let r=t?.products||[],o=t?.collections||[],l=(t?.queries||[]).filter(i=>i.text.toLowerCase()!==e.toLowerCase()),d=(i,a,A)=>h(c,u(i)).forEach(g=>{V(g,a,A),q(g,a.length>0)});d("search-products",r,(i,a)=>{$(i,{title:a.title,price:P(a.priceRange?.minVariantPrice),image:a.featuredImage}),T(i,R(a.handle,a.id)),i.classList.toggle("is-sold-out",!a.availableForSale)}),d("search-collections",o,(i,a)=>{$(i,{title:a.title,image:a.image}),T(i,`${(y.collectionPath||"/collection").replace(/\/$/,"")}/${a.handle}`)}),d("search-queries",l,(i,a)=>{$(i,{text:a.text});let A=i.tagName==="A"?i:i.querySelector("a"),g=s.getAttribute("action")||"/search";A&&A.setAttribute("href",`${g}${g.includes("?")?"&":"?"}${n.name||"q"}=${encodeURIComponent(a.text)}`)});let m=r.length+o.length+l.length;h(s,u("show")).forEach(i=>{let a=p(i,"show");a==="search-empty"&&q(i,m===0),a==="search-results"&&q(i,m>0)}),S().forEach((i,a)=>{i.id||(i.id=`${k}-${a}`),i.setAttribute("aria-selected","false")}),b(m?"ready":"empty"),f(!0),U("search",{term:e,products:r,collections:o,queries:l},s)}function $(t,e){h(t,u("search-bind")).forEach(r=>{let o=p(r,"search-bind");o==="image"?N(r,e.image?.url,e.image?.altText||e.title):e[o]!=null&&O(r,e[o])})}function T(t,e){let r=t.tagName==="A"?t:t.querySelector("a");r&&(r.setAttribute("href",e),r.setAttribute("role","option"))}n.addEventListener("input",()=>{let t=n.value.trim();t!==I&&(I=t,clearTimeout(w),w=setTimeout(()=>Q(t),y.searchDelay??150))}),n.addEventListener("focus",()=>{n.value.trim().length>=v&&S().length&&f(!0)}),n.addEventListener("keydown",t=>{let e=S(),r=e.findIndex(l=>l.getAttribute("aria-selected")==="true"),o=l=>{e.forEach((d,m)=>d.setAttribute("aria-selected",String(m===l))),e[l]&&(n.setAttribute("aria-activedescendant",e[l].id),e[l].scrollIntoView?.({block:"nearest"}))};t.key==="ArrowDown"&&e.length?(t.preventDefault(),f(!0),o((r+1)%e.length)):t.key==="ArrowUp"&&e.length?(t.preventDefault(),o(r<=0?e.length-1:r-1)):t.key==="Enter"&&r>=0?(t.preventDefault(),e[r].click()):t.key==="Escape"&&f(!1)}),document.addEventListener("click",t=>{s.contains(t.target)||f(!1)})}export{J as mountSearch};
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- import{a as W,b as Z,d as x,f as S,g as X,h as g,i as Y,j as ee,k as te,l as ne,m as re}from"./chunks/chunk-CISGFYOF.js";import{a as j}from"./chunks/chunk-6R752OYZ.js";import{a as V}from"./chunks/chunk-4UR45XTC.js";import{a as Q,b as c}from"./chunks/chunk-BGIKQY6H.js";import{a as _,b as R,c as q,d as F,h as G,i as B}from"./chunks/chunk-ZVUPVSLF.js";import{l as K}from"./chunks/chunk-YXCXIPQV.js";import{K as h,b as r,c as O,d as w,e as L,f as M,g as u,h as D,j as N,l as U,n as f,o as a,s as H,u as k,w as z,y as J}from"./chunks/chunk-KARKXC6G.js";import"./chunks/chunk-VC46IEJQ.js";var me={diagnose:()=>import("./chunks/diagnose-6ZSK5DGE.js"),markets:()=>import("./chunks/markets-ui-HJCVLCKJ.js"),search:()=>import("./chunks/search-LN2H6SXS.js"),extras:()=>import("./chunks/extras-QDCSW6VU.js"),account:()=>import("./chunks/account-JBZJN7X7.js"),analytics:()=>import("./chunks/analytics-22NMIVBV.js")},l=t=>me[t](),oe=void 0;var ae="0.6.1",m=null,C=null;function p(t=document){if(!w())return 0;let e=0;return X(),re(t),g(t,W()).forEach(n=>{if(x.has(n))return;x.add(n),e++;let o=new Z(n);S.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>p(i.detail.container)),te(o.load())}),g(t,a("product")).forEach(n=>{Y(n)&&e++}),g(t,`${a("country-select")},${a("country-bind")}`).length&&l("markets").then(n=>n.renderCountrySelects(t)).catch(n=>u(n,"markets")),(r.account?.clientId||r.account?.server)&&(g(t,`[${f("account-login")}],[${f("account-bind")}],[${f("orders")}],[${f("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||he())&&l("account").then(n=>n.mountAccount(t)).catch(n=>u(n,"account")),g(t,a("search")).length&&l("search").then(n=>n.mountSearch(t)).catch(n=>u(n,"search")),H(t,a("account-link")).forEach(n=>{n.setAttribute("href",`https://${r.domain}/account`)}),ne(),c.render(),L(`mounted ${e} scope(s)`,t),e}function se(){c.close()}function pe(t){let e=t?.closest?.(a("product"));return e&&j.get(e)||null}var ce=!1;function ge(){ce||(ce=!0,document.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;if(e.closest(a("cart-open"))){t.preventDefault(),c.toggle();return}if(e.closest(a("cart-close"))){t.preventDefault(),c.close();return}let n=e.closest(a("cart-clear"));if(n){t.preventDefault(),h(n,()=>c.clear().catch(d=>u(d,"cart clear")));return}let o=e.closest(a("checkout"));if(o){t.preventDefault(),h(o,()=>c.checkout());return}let i=e.closest(ie());if(i&&i.closest(a("cart-lines"))){let d=i.getAttribute(`data-${r.prefix}-key`),E=c.lines.find($=>$.id===d),b=$=>{t.preventDefault(),$().catch(fe=>u(fe,"cart line"))};if(e.closest(a("line-remove")))return i.classList.add("is-busy"),b(()=>c.removeLine(d));if(E&&e.closest(a("line-plus")))return b(()=>c.changeQuantity(d,1));if(E&&e.closest(a("line-minus")))return b(()=>c.changeQuantity(d,-1))}let s=e.closest(a("discount-remove"));if(s){t.preventDefault();let d=s.closest(a("discount-code"))?.getAttribute(f("discount-code"));d&&c.removeDiscount(d).catch(E=>u(E,"discount"));return}let y=e.closest(a("group-add"));y&&(t.preventDefault(),h(y,()=>ue(y)))}),document.addEventListener("change",t=>{let e=t.target;if(!e?.closest)return;let n=e.closest(ie()),o=n?.getAttribute(`data-${r.prefix}-key`),i=(s,y)=>{n.classList.add("is-busy"),n.setAttribute("aria-busy","true"),s.catch(d=>u(d,y))};o&&e.matches(`input${a("line","quantity")}`)?i(c.updateLine(o,parseInt(e.value,10)||0),"cart line"):o&&e.matches(`select${a("line-plan")}`)?i(c.updateLine(o,{sellingPlanId:e.value||null}),"cart line plan"):e.matches(`select${a("country-select")}`)?e.value&&I(e.value).catch(s=>u(s,"country")):e.matches(a("cart-note"))&&c.setNote(e.value).catch(s=>u(s,"cart note"))}),document.addEventListener("submit",t=>{let e=t.target.closest?.(a("discount-form"));if(!e)return;t.preventDefault();let n=e.querySelector(a("discount-input"))||e.querySelector("input"),o=n?.value.trim();o&&h(e,async()=>{let i=s=>{e.classList.toggle("is-invalid",s),n&&(s?n.setAttribute("aria-invalid","true"):n.removeAttribute("aria-invalid"))};try{await c.applyDiscount(o),i(!1),k("discount-applied",{code:o},e),n&&(n.value="")}catch(s){i(!0),s?.code==="INVALID_DISCOUNT"?k("discount-invalid",{code:o},e):u(s,"discount")}})},!0),document.addEventListener("input",t=>{let e=t.target.closest?.(a("discount-form"));e&&(e.classList.remove("is-invalid"),t.target.removeAttribute?.("aria-invalid"))}),window.addEventListener("storage",t=>{r.domain&&t.key?.startsWith(`${r.prefix}:`)&&l("extras").then(e=>e.onStorage(t)).catch(()=>{})}),document.addEventListener(`${r.prefix}:variant-changed`,t=>{let e=t.target;(r.variantUrl||e.hasAttribute?.(f("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(m||Promise.resolve()).then(()=>{let t=A();if(!t&&T){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:de}T=!!A(),t?.country&&(String(t.country).toUpperCase()!==String(r.country||"").toUpperCase()||String(t.language||"").toUpperCase()!==String(r.language||"").toUpperCase())?I(t.country,{language:t.language??null,locale:t.locale,remember:!1}).then(()=>p(document),()=>p(document)):p(document)})),document.addEventListener("astro:before-swap",()=>se())),window.addEventListener("online",()=>{ee(),S.forEach(t=>{t.root.getAttribute(f("state"))==="error"&&t.load()})}),document.addEventListener("keydown",t=>{if(!c.isOpen())return;if(t.key==="Escape"){c.close();return}if(t.key!=="Tab"||r.cartFocus===!1)return;let e=c.drawers().find(s=>s.classList.contains(r.cartDrawerOpenClass)),n=e?Q(e):[];if(!n.length)return;let o=n[0],i=n[n.length-1];(!e.contains(document.activeElement)||t.shiftKey&&document.activeElement===o||!t.shiftKey&&document.activeElement===i)&&(t.preventDefault(),(t.shiftKey?i:o).focus())}))}function ie(){return`[data-${r.prefix}-key]`}var ue=t=>l("extras").then(e=>e.addGroup(t)),v=null;function le(t={}){return m&&!Object.keys(t).length?m:(O({...window.TETHER_CONFIG||{},...t}),w()?(ge(),r.observe&&Ee(),r.analytics&&!v&&(v=[],["product-ready","list-ready","cart-updated","cart-toggled","checkout","search"].forEach(e=>document.addEventListener(`${r.prefix}:${e}`,n=>v.push(n))),document.addEventListener("astro:page-load",()=>v.push(new CustomEvent(`${r.prefix}:page`))),l("analytics").then(e=>e.startAnalytics(v)).catch(e=>u(e,"analytics"))),m=ye(t).then(()=>c.init()).then(async e=>{let n=r.country?String(r.country).toUpperCase():null;if(e&&n&&e.buyerIdentity?.countryCode&&e.buyerIdentity.countryCode!==n)try{e=await c.setBuyerIdentity({countryCode:n},{create:!1})}catch(o){u(o,"cart country")}return k("ready",{cart:e}),P}),m):(M("TETHER_CONFIG is missing domain or token. Tether is idle."),m=Promise.resolve(null),m))}function A(t=document){let e=o=>t.querySelector(`meta[name="${r.prefix}-page-${o}"]`)?.getAttribute("content")||void 0,n=e("country");return n?{country:n.toUpperCase(),language:e("language"),locale:e("locale")}:null}var de=null,T=!1;async function ye(t){let e=r.markets||{};de={country:r.country,language:r.language,locale:r.locale};let n=A();if(T=!!n,n){r.country=n.country,r.language=n.language?n.language.toUpperCase():void 0,n.locale&&(r.locale=n.locale);return}if(e.detect===!1)return;let o=null;if(e.detect)try{o=(await l("markets")).detectMarket(e)}catch(i){u(i,"markets");return}else if(e.remember!==!1){try{o=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{}o&&!/^[A-Z]{2}$/.test(o.country||"")&&(o=null)}o&&(o.country&&(r.country=o.country),o.language&&(r.language=o.language),o.locale&&!t.locale&&(r.locale=o.locale),L("market",o))}function he(){try{return!!(sessionStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account-hint:${r.domain}`])}catch{return!1}}var ve=new Proxy({},{get:(t,e)=>(...n)=>l("account").then(o=>o[e](...n))});function I(t,e){return l("markets").then(n=>n.setCountry(t,e))}function Ee(){if(C||typeof MutationObserver>"u")return;let t=null,e=new Set;C=new MutationObserver(n=>{n.forEach(o=>o.addedNodes.forEach(i=>{i.nodeType===1&&e.add(i)})),clearTimeout(t),t=setTimeout(()=>{e.forEach(o=>{o.isConnected&&p(o)}),e.clear()},50)}),C.observe(document.body,{childList:!0,subtree:!0})}var P={VERSION:ae,init:le,mount:p,unmount:se,get config(){return r},get ready(){return m||Promise.resolve(null)},query:U,withContext:N,cart:c,getProduct:q,getProducts:G,getRecommendations:B,getScope:pe,addGroup:ue,account:ve,primeProduct:R,normalizeProductKey:_,clearProductCache:F,formatMoney:z,imageUrl:J,plans:K,TetherError:D,resolveProductKey:V,setCountry:I,detectMarket:t=>l("markets").then(e=>e.detectMarket(t||r.markets)),getLocalization:()=>l("markets").then(t=>t.getLocalization()),diagnose:t=>l("diagnose").then(e=>e.diagnose({...t,version:ae})),__core:oe,__parts:{},on(t,e){let n=o=>e(o.detail,o);return document.addEventListener(`${r.prefix}:${t}`,n),()=>document.removeEventListener(`${r.prefix}:${t}`,n)}},De=P;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=P,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let e=()=>le().then(()=>p(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{ae as VERSION,ue as addGroup,P as api,De as default,pe as getScope,le as init,p as mount,I as setCountry,se as unmount};
1
+ import{a as W,b as Z,d as x,f as S,g as X,h as g,i as Y,j as ee,k as te,l as ne,m as re}from"./chunks/chunk-VCPI7MJ2.js";import{a as j}from"./chunks/chunk-ZIUIWEON.js";import{a as V}from"./chunks/chunk-RREHGH4A.js";import{a as Q,b as c}from"./chunks/chunk-L2TRRKYV.js";import{a as _,b as R,c as q,d as F,h as G,i as B}from"./chunks/chunk-FIOZPPC5.js";import{l as K}from"./chunks/chunk-AJLPU2JC.js";import{K as h,b as r,c as O,d as w,e as L,f as M,g as u,h as D,j as N,l as U,n as f,o as a,s as H,u as k,w as z,y as J}from"./chunks/chunk-K2YEQAIH.js";import"./chunks/chunk-VC46IEJQ.js";var me={diagnose:()=>import("./chunks/diagnose-4JHU6RTC.js"),markets:()=>import("./chunks/markets-ui-F3R5T5EL.js"),search:()=>import("./chunks/search-NILMGYXG.js"),extras:()=>import("./chunks/extras-R4X34VQL.js"),account:()=>import("./chunks/account-NVHPA7AX.js"),analytics:()=>import("./chunks/analytics-SLATWPLC.js")},l=t=>me[t](),oe=void 0;var ae="0.6.3",m=null,C=null;function p(t=document){if(!w())return 0;let e=0;return X(),re(t),g(t,W()).forEach(n=>{if(x.has(n))return;x.add(n),e++;let o=new Z(n);S.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>p(i.detail.container)),te(o.load())}),g(t,a("product")).forEach(n=>{Y(n)&&e++}),g(t,`${a("country-select")},${a("country-bind")}`).length&&l("markets").then(n=>n.renderCountrySelects(t)).catch(n=>u(n,"markets")),(r.account?.clientId||r.account?.server)&&(g(t,`[${f("account-login")}],[${f("account-bind")}],[${f("orders")}],[${f("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||he())&&l("account").then(n=>n.mountAccount(t)).catch(n=>u(n,"account")),g(t,a("search")).length&&l("search").then(n=>n.mountSearch(t)).catch(n=>u(n,"search")),H(t,a("account-link")).forEach(n=>{n.setAttribute("href",`https://${r.domain}/account`)}),ne(),c.render(),L(`mounted ${e} scope(s)`,t),e}function se(){c.close()}function pe(t){let e=t?.closest?.(a("product"));return e&&j.get(e)||null}var ce=!1;function ge(){ce||(ce=!0,document.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;if(e.closest(a("cart-open"))){t.preventDefault(),c.toggle();return}if(e.closest(a("cart-close"))){t.preventDefault(),c.close();return}let n=e.closest(a("cart-clear"));if(n){t.preventDefault(),h(n,()=>c.clear().catch(d=>u(d,"cart clear")));return}let o=e.closest(a("checkout"));if(o){t.preventDefault(),h(o,()=>c.checkout());return}let i=e.closest(ie());if(i&&i.closest(a("cart-lines"))){let d=i.getAttribute(`data-${r.prefix}-key`),E=c.lines.find($=>$.id===d),b=$=>{t.preventDefault(),$().catch(fe=>u(fe,"cart line"))};if(e.closest(a("line-remove")))return i.classList.add("is-busy"),b(()=>c.removeLine(d));if(E&&e.closest(a("line-plus")))return b(()=>c.changeQuantity(d,1));if(E&&e.closest(a("line-minus")))return b(()=>c.changeQuantity(d,-1))}let s=e.closest(a("discount-remove"));if(s){t.preventDefault();let d=s.closest(a("discount-code"))?.getAttribute(f("discount-code"));d&&c.removeDiscount(d).catch(E=>u(E,"discount"));return}let y=e.closest(a("group-add"));y&&(t.preventDefault(),h(y,()=>ue(y)))}),document.addEventListener("change",t=>{let e=t.target;if(!e?.closest)return;let n=e.closest(ie()),o=n?.getAttribute(`data-${r.prefix}-key`),i=(s,y)=>{n.classList.add("is-busy"),n.setAttribute("aria-busy","true"),s.catch(d=>u(d,y))};o&&e.matches(`input${a("line","quantity")}`)?i(c.updateLine(o,parseInt(e.value,10)||0),"cart line"):o&&e.matches(`select${a("line-plan")}`)?i(c.updateLine(o,{sellingPlanId:e.value||null}),"cart line plan"):e.matches(`select${a("country-select")}`)?e.value&&I(e.value).catch(s=>u(s,"country")):e.matches(a("cart-note"))&&c.setNote(e.value).catch(s=>u(s,"cart note"))}),document.addEventListener("submit",t=>{let e=t.target.closest?.(a("discount-form"));if(!e)return;t.preventDefault();let n=e.querySelector(a("discount-input"))||e.querySelector("input"),o=n?.value.trim();o&&h(e,async()=>{let i=s=>{e.classList.toggle("is-invalid",s),n&&(s?n.setAttribute("aria-invalid","true"):n.removeAttribute("aria-invalid"))};try{await c.applyDiscount(o),i(!1),k("discount-applied",{code:o},e),n&&(n.value="")}catch(s){i(!0),s?.code==="INVALID_DISCOUNT"?k("discount-invalid",{code:o},e):u(s,"discount")}})},!0),document.addEventListener("input",t=>{let e=t.target.closest?.(a("discount-form"));e&&(e.classList.remove("is-invalid"),t.target.removeAttribute?.("aria-invalid"))}),window.addEventListener("storage",t=>{r.domain&&t.key?.startsWith(`${r.prefix}:`)&&l("extras").then(e=>e.onStorage(t)).catch(()=>{})}),document.addEventListener(`${r.prefix}:variant-changed`,t=>{let e=t.target;(r.variantUrl||e.hasAttribute?.(f("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(m||Promise.resolve()).then(()=>{let t=A();if(!t&&T){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:de}T=!!A(),t?.country&&(String(t.country).toUpperCase()!==String(r.country||"").toUpperCase()||String(t.language||"").toUpperCase()!==String(r.language||"").toUpperCase())?I(t.country,{language:t.language??null,locale:t.locale,remember:!1}).then(()=>p(document),()=>p(document)):p(document)})),document.addEventListener("astro:before-swap",()=>se())),window.addEventListener("online",()=>{ee(),S.forEach(t=>{t.root.getAttribute(f("state"))==="error"&&t.load()})}),document.addEventListener("keydown",t=>{if(!c.isOpen())return;if(t.key==="Escape"){c.close();return}if(t.key!=="Tab"||r.cartFocus===!1)return;let e=c.drawers().find(s=>s.classList.contains(r.cartDrawerOpenClass)),n=e?Q(e):[];if(!n.length)return;let o=n[0],i=n[n.length-1];(!e.contains(document.activeElement)||t.shiftKey&&document.activeElement===o||!t.shiftKey&&document.activeElement===i)&&(t.preventDefault(),(t.shiftKey?i:o).focus())}))}function ie(){return`[data-${r.prefix}-key]`}var ue=t=>l("extras").then(e=>e.addGroup(t)),v=null;function le(t={}){return m&&!Object.keys(t).length?m:(O({...window.TETHER_CONFIG||{},...t}),w()?(ge(),r.observe&&Ee(),r.analytics&&!v&&(v=[],["product-ready","list-ready","cart-updated","cart-toggled","checkout","search"].forEach(e=>document.addEventListener(`${r.prefix}:${e}`,n=>v.push(n))),document.addEventListener("astro:page-load",()=>v.push(new CustomEvent(`${r.prefix}:page`))),l("analytics").then(e=>e.startAnalytics(v)).catch(e=>u(e,"analytics"))),m=ye(t).then(()=>c.init()).then(async e=>{let n=r.country?String(r.country).toUpperCase():null;if(e&&n&&e.buyerIdentity?.countryCode&&e.buyerIdentity.countryCode!==n)try{e=await c.setBuyerIdentity({countryCode:n},{create:!1})}catch(o){u(o,"cart country")}return k("ready",{cart:e}),P}),m):(M("TETHER_CONFIG is missing domain or token. Tether is idle."),m=Promise.resolve(null),m))}function A(t=document){let e=o=>t.querySelector(`meta[name="${r.prefix}-page-${o}"]`)?.getAttribute("content")||void 0,n=e("country");return n?{country:n.toUpperCase(),language:e("language"),locale:e("locale")}:null}var de=null,T=!1;async function ye(t){let e=r.markets||{};de={country:r.country,language:r.language,locale:r.locale};let n=A();if(T=!!n,n){r.country=n.country,r.language=n.language?n.language.toUpperCase():void 0,n.locale&&(r.locale=n.locale);return}if(e.detect===!1)return;let o=null;if(e.detect)try{o=(await l("markets")).detectMarket(e)}catch(i){u(i,"markets");return}else if(e.remember!==!1){try{o=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{}o&&!/^[A-Z]{2}$/.test(o.country||"")&&(o=null)}o&&(o.country&&(r.country=o.country),o.language&&(r.language=o.language),o.locale&&!t.locale&&(r.locale=o.locale),L("market",o))}function he(){try{return!!(sessionStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account-hint:${r.domain}`])}catch{return!1}}var ve=new Proxy({},{get:(t,e)=>(...n)=>l("account").then(o=>o[e](...n))});function I(t,e){return l("markets").then(n=>n.setCountry(t,e))}function Ee(){if(C||typeof MutationObserver>"u")return;let t=null,e=new Set;C=new MutationObserver(n=>{n.forEach(o=>o.addedNodes.forEach(i=>{i.nodeType===1&&e.add(i)})),clearTimeout(t),t=setTimeout(()=>{e.forEach(o=>{o.isConnected&&p(o)}),e.clear()},50)}),C.observe(document.body,{childList:!0,subtree:!0})}var P={VERSION:ae,init:le,mount:p,unmount:se,get config(){return r},get ready(){return m||Promise.resolve(null)},query:U,withContext:N,cart:c,getProduct:q,getProducts:G,getRecommendations:B,getScope:pe,addGroup:ue,account:ve,primeProduct:R,normalizeProductKey:_,clearProductCache:F,formatMoney:z,imageUrl:J,plans:K,TetherError:D,resolveProductKey:V,setCountry:I,detectMarket:t=>l("markets").then(e=>e.detectMarket(t||r.markets)),getLocalization:()=>l("markets").then(t=>t.getLocalization()),diagnose:t=>l("diagnose").then(e=>e.diagnose({...t,version:ae})),__core:oe,__parts:{},on(t,e){let n=o=>e(o.detail,o);return document.addEventListener(`${r.prefix}:${t}`,n),()=>document.removeEventListener(`${r.prefix}:${t}`,n)}},De=P;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=P,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let e=()=>le().then(()=>p(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{ae as VERSION,ue as addGroup,P as api,De as default,pe as getScope,le as init,p as mount,I as setCountry,se as unmount};
@@ -1 +1 @@
1
- import{a as D,c as R,d as j,e as k,f as $,g as b,i as B,k as H,l as Y}from"./chunks/chunk-YXCXIPQV.js";import{a as q,h as K,j as X,k as L,v as M,y as z}from"./chunks/chunk-KARKXC6G.js";import"./chunks/chunk-VC46IEJQ.js";function G(l,{variant:c,sellingPlan:o,defaultPurchase:F="one-time",lowStock:g=5}={}){let p=l?.variants?.nodes||[],N=c?j.variant(c):null,s=N&&p.find(r=>r.id===N)||p.find(r=>r.availableForSale)||p[0]||null;if(!s)return null;let C=Object.fromEntries((s.selectedOptions||[]).map(r=>[r.name,r.value])),S=k(l),w=H(l,o),d=S.length?w||S[0]:null;d&&!$(s,d.id)&&(d=S.find(r=>$(s,r.id))||d);let U=l.requiresSellingPlan||w||F==="subscription",v=S.some(r=>$(s,r.id)),T=S.length&&U?"subscription":"one-time",m=T==="subscription"&&v,e=m?b(s,d.id):s.price,t=m&&$(s,d.id)?.priceAdjustments?.[0]?.compareAtPrice||s.compareAtPrice,n=!!(t&&parseFloat(t.amount)>parseFloat(e.amount)),i=s.quantityAvailable,f=i!=null&&i>0&&i<=g,O=m?B(s,d.id).percentage:0;return{variant:s,selected:C,purchase:T,plan:m?d:null,plans:S.map(r=>({id:r.id,name:r.name,price:b(s,r.id),savings:B(s,r.id).percentage,selected:m&&r.id===d.id,available:!!$(s,r.id)})),savings:d?B(s,d.id).percentage:0,price:e,compareAtPrice:n?t:null,available:s.availableForSale,show:{"in-stock":s.availableForSale,"out-of-stock":!s.availableForSale,backorder:!!(s.availableForSale&&s.currentlyNotInStock),"on-sale":n,"not-on-sale":!n,"has-variants":p.length>1,"single-variant":p.length===1,"low-stock":f,"plenty-in-stock":s.availableForSale&&!f,"subscription-available":v,"subscription-unavailable":!v,"subscription-only":!!l.requiresSellingPlan,"one-time-available":!l.requiresSellingPlan,"subscription-selected":m,"one-time-selected":!m,"has-savings":m?O>0:n},unavailable:Object.fromEntries((l.options||[]).map(r=>[r.name,r.optionValues.map(u=>u.name).filter(u=>P(r.name,u))])),isUnavailable:(r,u)=>P(r,u)};function P(r,u){return!p.some(y=>y.availableForSale&&y.selectedOptions.every(h=>h.name===r?h.value===u:C[h.name]===h.value))}}var x=l=>typeof l=="string"&&l.startsWith("gid://");function J(l){let c=String(l??"").trim();if(!c)return null;if(x(c))return c;if(/^\d+$/.test(c))return`gid://shopify/Product/${c}`;let o=c.match(/\/products\/([^/?#]+)/);return o?o[1]:c}function Z(l,c){if(!l)return"";let o=parseFloat(l.amount);if(Number.isNaN(o))return"";try{return new Intl.NumberFormat(c||void 0,{style:"currency",currency:l.currencyCode}).format(o)}catch{return`${l.currencyCode} ${o.toFixed(2)}`}}function V(l,{productPath:c="/product",id:o}={}){return/\{(handle|id)\}/.test(c)?c.replace(/\{handle\}/g,encodeURIComponent(l||"")).replace(/\{id\}/g,encodeURIComponent(o?String(o).split("/").pop():"")):`${c.replace(/\/$/,"")}/${l}`}var W=l=>JSON.stringify(l).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),ee={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};function le(l={}){let c=Object.fromEntries(Object.entries(l).filter(([e])=>e in q||e==="fetch"||e==="pageSize"||e==="siteUrl")),o={...q,...c};for(let[e,t]of Object.entries(ee))o[e]||(o[e]=t.map(n=>l[n]).find(Boolean)||"");if(o.domain=String(o.domain||"").replace(/^https?:\/\//,"").replace(/\/.*$/,""),!o.domain||!o.token)throw new K("createStorefront needs domain and token: pass them, or import.meta.env with PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN",{code:"NOT_CONFIGURED"});let F=l.pageSize||25,g=(e,t,n)=>L(o,e,t,n),p=()=>D(o);async function N(e){let t=J(e);if(!t)return null;let n=x(t)?await g(`query TetherServerProductById($id:ID!){node(id:$id){... on Product{...TetherProduct}}}${p()}`,{id:t}):await g(`query TetherServerProduct($handle:String!){product(handle:$handle){...TetherProduct}}${p()}`,{handle:t}),i=x(t)?n.node:n.product;return i&&i.id?i:null}async function s({collection:e,query:t,first:n=F,after:i=null,sortKey:f,reverse:O=!1,filters:P}={}){if(e){let u=await g(`query TetherServerCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${R()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${p()}`,{handle:e,first:n,after:i,sortKey:f||void 0,reverse:O,filters:P||void 0});if(!u.collection)return{collection:null,products:[],pageInfo:{hasNextPage:!1,endCursor:null}};let{products:y,...h}=u.collection;return{collection:h,products:y.nodes,pageInfo:y.pageInfo}}let r=await g(`query TetherServerProducts($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${p()}`,{first:n,after:i,query:t||void 0,sortKey:f||void 0,reverse:O});return{collection:null,products:r.products.nodes,pageInfo:r.products.pageInfo}}async function C(e={}){let t=[],n=null;for(let i=0;i<500;i++){let f=await s({...e,first:F,after:n});if(t.push(...f.products),!f.pageInfo.hasNextPage)break;n=f.pageInfo.endCursor}return t}async function S(e,t={}){let n=await s({...t,collection:e});return n.collection?{...n.collection,products:n.products,pageInfo:n.pageInfo}:null}async function w(){let e=[],t=null;for(let n=0;n<100;n++){let i=await g(`query TetherServerCollections($first:Int!,$after:String){collections(first:$first,after:$after){nodes{${R()}}pageInfo{hasNextPage endCursor}}}`,{first:100,after:t});if(e.push(...i.collections.nodes),!i.collections.pageInfo.hasNextPage)break;t=i.collections.pageInfo.endCursor}return e}async function d(e,t="RELATED"){let n=J(typeof e=="object"?e?.id:e),i=n?.startsWith("gid://");return(await g(`query TetherServerRecs(${i?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${i?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${p()}`,i?{id:n,intent:t}:{handle:n,intent:t})).productRecommendations||[]}function U(e,{card:t=!1}={}){let n=(Array.isArray(e)?e:[e]).filter(Boolean);t&&(n=n.map(m));let i={v:1,at:new Date().toISOString(),country:o.country||null,language:o.language||null,products:n};return`<script type="application/json" data-tether-hydrate>${W(i)}<\/script>`}function v(e,{url:t,brand:n}={}){if(!e)return null;let i=t||(o.siteUrl?new URL(V(e.handle,{productPath:o.productPath,id:e.id}),o.siteUrl).toString():void 0),f=a=>String(a.id).split("/").pop(),O=a=>i?`${i}${i.includes("?")?"&":"?"}variant=${f(a)}`:void 0,P=(e.description||"").trim()||void 0,r=(e.images?.nodes||[]).map(a=>a.url).filter(Boolean),u=n||e.vendor,y=a=>{if(!e.requiresSellingPlan)return a.price;let I=k(e).find(Q=>$(a,Q.id));return I?b(a,I.id):a.price},h=a=>({"@type":"Offer",price:y(a)?.amount,priceCurrency:y(a)?.currencyCode,availability:`https://schema.org/${a.availableForSale?a.currentlyNotInStock?"BackOrder":"InStock":"OutOfStock"}`,url:O(a)}),_=e.variants?.nodes||[],A=a=>JSON.parse(JSON.stringify(a));if(_.length<=1){let a=_[0];return A({"@context":"https://schema.org","@type":"Product",name:e.title,description:P,url:i,image:r,sku:a?.sku||void 0,brand:u?{"@type":"Brand",name:u}:void 0,offers:a?h(a):void 0})}let E={size:"https://schema.org/size",color:"https://schema.org/color",colour:"https://schema.org/color",material:"https://schema.org/material"};return A({"@context":"https://schema.org","@type":"ProductGroup",name:e.title,description:P,url:i,productGroupID:String(e.id).split("/").pop(),image:r,brand:u?{"@type":"Brand",name:u}:void 0,variesBy:[...new Set((e.options||[]).map(a=>E[a.name.toLowerCase()]).filter(Boolean))],hasVariant:_.map(a=>({"@type":"Product",name:`${e.title} - ${a.title}`,sku:a.sku||void 0,image:a.image?.url||r[0],...Object.fromEntries((a.selectedOptions||[]).filter(I=>E[I.name.toLowerCase()]).map(I=>[E[I.name.toLowerCase()].split("/").pop(),I.value])),offers:h(a)}))})}let T=(e,t)=>e?`<script type="application/ld+json">${W(v(e,t))}<\/script>`:"";function m(e){return{...e,description:"",descriptionHtml:"",images:{nodes:(e.images?.nodes||[]).slice(0,1)},variants:{nodes:(e.variants?.nodes||[]).map(t=>({...t,image:null}))}}}return{config:o,query:g,getProduct:N,getProducts:s,allProducts:C,getCollection:S,allCollections:w,getRecommendations:d,hydrate:U,formatMoney:(e,t=o.locale)=>Z(e,t),formatPercent:(e,t=o.locale)=>M(e,t),imageUrl:z,jsonLd:T,jsonLdData:v,initialState:(e,t={})=>G(e,{defaultPurchase:o.defaultPurchase,lowStock:o.lowStock,...t}),productUrl:(e,t={})=>V(e,{productPath:o.productPath,...t}),plans:Y}}export{K as TetherError,le as createStorefront,Z as formatMoney,M as formatPercent,z as imageUrl,G as initialState,Y as plans,J as productKey,V as productUrl,X as withContext};
1
+ import{a as D,c as R,d as j,e as k,f as P,g as b,i as B,k as H,l as Y}from"./chunks/chunk-AJLPU2JC.js";import{a as q,h as K,j as X,k as L,v as M,y as z}from"./chunks/chunk-K2YEQAIH.js";import"./chunks/chunk-VC46IEJQ.js";function G(l,{variant:c,sellingPlan:o,defaultPurchase:F="one-time",lowStock:g=5}={}){let f=l?.variants?.nodes||[],N=c?j.variant(c):null,s=N&&f.find(r=>r.id===N)||f.find(r=>r.availableForSale)||f[0]||null;if(!s)return null;let C=Object.fromEntries((s.selectedOptions||[]).map(r=>[r.name,r.value])),S=k(l),w=H(l,o),p=S.length?w||S[0]:null;p&&!P(s,p.id)&&(p=S.find(r=>P(s,r.id))||p);let U=l.requiresSellingPlan||w||F==="subscription",O=S.some(r=>P(s,r.id)),T=S.length&&U?"subscription":"one-time",m=T==="subscription"&&O,e=m?b(s,p.id):s.price,t=m&&P(s,p.id)?.priceAdjustments?.[0]?.compareAtPrice||s.compareAtPrice,n=!!(t&&parseFloat(t.amount)>parseFloat(e.amount)),a=s.quantityAvailable,d=a!=null&&a>0&&a<=g,y=m?B(s,p.id).percentage:0;return{variant:s,selected:C,purchase:T,plan:m?p:null,plans:S.map(r=>({id:r.id,name:r.name,price:b(s,r.id),savings:B(s,r.id).percentage,selected:m&&r.id===p.id,available:!!P(s,r.id)})),savings:p?B(s,p.id).percentage:0,price:e,compareAtPrice:n?t:null,available:s.availableForSale,show:{"in-stock":s.availableForSale,"out-of-stock":!s.availableForSale,backorder:!!(s.availableForSale&&s.currentlyNotInStock),"on-sale":n,"not-on-sale":!n,"has-variants":f.length>1,"single-variant":f.length===1,"low-stock":d,"plenty-in-stock":s.availableForSale&&!d,"subscription-available":O,"subscription-unavailable":!O,"subscription-only":!!l.requiresSellingPlan,"one-time-available":!l.requiresSellingPlan,"subscription-selected":m,"one-time-selected":!m,"has-savings":m?y>0:n},unavailable:Object.fromEntries((l.options||[]).map(r=>[r.name,r.optionValues.map(u=>u.name).filter(u=>I(r.name,u))])),isUnavailable:(r,u)=>I(r,u)};function I(r,u){return!f.some($=>$.availableForSale&&$.selectedOptions.every(h=>h.name===r?h.value===u:C[h.name]===h.value))}}var x=l=>typeof l=="string"&&l.startsWith("gid://");function J(l){let c=String(l??"").trim();if(!c)return null;if(x(c))return c;if(/^\d+$/.test(c))return`gid://shopify/Product/${c}`;let o=c.match(/\/products\/([^/?#]+)/);return o?o[1]:c}function Z(l,c){if(!l)return"";let o=parseFloat(l.amount);if(Number.isNaN(o))return"";try{return new Intl.NumberFormat(c||void 0,{style:"currency",currency:l.currencyCode}).format(o)}catch{return`${l.currencyCode} ${o.toFixed(2)}`}}function V(l,{productPath:c="/product",id:o}={}){return/\{(handle|id)\}/.test(c)?c.replace(/\{handle\}/g,encodeURIComponent(l||"")).replace(/\{id\}/g,encodeURIComponent(o?String(o).split("/").pop():"")):`${c.replace(/\/$/,"")}/${l}`}var W=l=>JSON.stringify(l).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),ee={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};function le(l={}){let c=Object.fromEntries(Object.entries(l).filter(([e])=>e in q||e==="fetch"||e==="pageSize"||e==="siteUrl")),o={...q,...c};for(let[e,t]of Object.entries(ee))o[e]||(o[e]=t.map(n=>l[n]).find(Boolean)||"");if(o.domain=String(o.domain||"").replace(/^https?:\/\//,"").replace(/\/.*$/,""),!o.domain||!o.token)throw new K("createStorefront needs domain and token: pass them, or import.meta.env with PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN",{code:"NOT_CONFIGURED"});let F=l.pageSize||25,g=(e,t,n)=>L(o,e,t,n),f=()=>D(o);async function N(e){let t=J(e);if(!t)return null;let n=x(t)?await g(`query TetherServerProductById($id:ID!){node(id:$id){... on Product{...TetherProduct}}}${f()}`,{id:t}):await g(`query TetherServerProduct($handle:String!){product(handle:$handle){...TetherProduct}}${f()}`,{handle:t}),a=x(t)?n.node:n.product;return a&&a.id?a:null}async function s({collection:e,query:t,first:n=F,after:a=null,sortKey:d,reverse:y=!1,filters:I}={}){if(e){let u=await g(`query TetherServerCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${R()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${f()}`,{handle:e,first:n,after:a,sortKey:d||void 0,reverse:y,filters:I||void 0});if(!u.collection)return{collection:null,products:[],pageInfo:{hasNextPage:!1,endCursor:null}};let{products:$,...h}=u.collection;return{collection:h,products:$.nodes,pageInfo:$.pageInfo}}let r=await g(`query TetherServerProducts($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${f()}`,{first:n,after:a,query:t||void 0,sortKey:d||void 0,reverse:y});return{collection:null,products:r.products.nodes,pageInfo:r.products.pageInfo}}async function C(e={}){let t=[],n=null;for(let a=0;a<500;a++){let d=await s({...e,first:F,after:n});if(t.push(...d.products),!d.pageInfo.hasNextPage)break;n=d.pageInfo.endCursor}return t}async function S(e,t={}){let n=await s({...t,collection:e});return n.collection?{...n.collection,products:n.products,pageInfo:n.pageInfo}:null}async function w(){let e=[],t=null;for(let n=0;n<100;n++){let a=await g(`query TetherServerCollections($first:Int!,$after:String){collections(first:$first,after:$after){nodes{${R()}}pageInfo{hasNextPage endCursor}}}`,{first:100,after:t});if(e.push(...a.collections.nodes),!a.collections.pageInfo.hasNextPage)break;t=a.collections.pageInfo.endCursor}return e}async function p(e,t="RELATED"){let n=J(typeof e=="object"?e?.id:e),a=n?.startsWith("gid://");return(await g(`query TetherServerRecs(${a?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${a?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${f()}`,a?{id:n,intent:t}:{handle:n,intent:t})).productRecommendations||[]}function U(e,{card:t=!1,images:n=2}={}){let a=(Array.isArray(e)?e:[e]).filter(Boolean);t&&(a=a.map(y=>m(y,n)));let d={v:1,at:new Date().toISOString(),country:o.country||null,language:o.language||null,products:a};return`<script type="application/json" data-tether-hydrate>${W(d)}<\/script>`}function O(e,{url:t,brand:n}={}){if(!e)return null;let a=t||(o.siteUrl?new URL(V(e.handle,{productPath:o.productPath,id:e.id}),o.siteUrl).toString():void 0),d=i=>String(i.id).split("/").pop(),y=i=>a?`${a}${a.includes("?")?"&":"?"}variant=${d(i)}`:void 0,I=(e.description||"").trim()||void 0,r=(e.images?.nodes||[]).map(i=>i.url).filter(Boolean),u=n||e.vendor,$=i=>{if(!e.requiresSellingPlan)return i.price;let v=k(e).find(Q=>P(i,Q.id));return v?b(i,v.id):i.price},h=i=>({"@type":"Offer",price:$(i)?.amount,priceCurrency:$(i)?.currencyCode,availability:`https://schema.org/${i.availableForSale?i.currentlyNotInStock?"BackOrder":"InStock":"OutOfStock"}`,url:y(i)}),_=e.variants?.nodes||[],A=i=>JSON.parse(JSON.stringify(i));if(_.length<=1){let i=_[0];return A({"@context":"https://schema.org","@type":"Product",name:e.title,description:I,url:a,image:r,sku:i?.sku||void 0,brand:u?{"@type":"Brand",name:u}:void 0,offers:i?h(i):void 0})}let E={size:"https://schema.org/size",color:"https://schema.org/color",colour:"https://schema.org/color",material:"https://schema.org/material"};return A({"@context":"https://schema.org","@type":"ProductGroup",name:e.title,description:I,url:a,productGroupID:String(e.id).split("/").pop(),image:r,brand:u?{"@type":"Brand",name:u}:void 0,variesBy:[...new Set((e.options||[]).map(i=>E[i.name.toLowerCase()]).filter(Boolean))],hasVariant:_.map(i=>({"@type":"Product",name:`${e.title} - ${i.title}`,sku:i.sku||void 0,image:i.image?.url||r[0],...Object.fromEntries((i.selectedOptions||[]).filter(v=>E[v.name.toLowerCase()]).map(v=>[E[v.name.toLowerCase()].split("/").pop(),v.value])),offers:h(i)}))})}let T=(e,t)=>e?`<script type="application/ld+json">${W(O(e,t))}<\/script>`:"";function m(e,t=2){return{...e,description:"",descriptionHtml:"",images:{nodes:(e.images?.nodes||[]).slice(0,Math.max(1,t))},variants:{nodes:(e.variants?.nodes||[]).map(n=>({...n,image:null}))}}}return{config:o,query:g,getProduct:N,getProducts:s,allProducts:C,getCollection:S,allCollections:w,getRecommendations:p,hydrate:U,formatMoney:(e,t=o.locale)=>Z(e,t),formatPercent:(e,t=o.locale)=>M(e,t),imageUrl:z,jsonLd:T,jsonLdData:O,initialState:(e,t={})=>G(e,{defaultPurchase:o.defaultPurchase,lowStock:o.lowStock,...t}),productUrl:(e,t={})=>V(e,{productPath:o.productPath,...t}),plans:Y}}export{K as TetherError,le as createStorefront,Z as formatMoney,M as formatPercent,z as imageUrl,G as initialState,Y as plans,J as productKey,V as productUrl,X as withContext};