@occluze/tether 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -109
- package/dist/esm/astro.js +1 -1
- package/dist/esm/chunks/{account-CXMA5RPZ.js → account-W4FBRKXA.js} +1 -1
- package/dist/esm/chunks/{account-pages-IZO7FEOZ.js → account-pages-IM3OQTOP.js} +1 -1
- package/dist/esm/chunks/analytics-QDVOLZY3.js +1 -0
- package/dist/esm/chunks/{chunk-BBVUVPMO.js → chunk-AUVAN3KZ.js} +1 -1
- package/dist/esm/chunks/chunk-BMDYNMRC.js +1 -0
- package/dist/esm/chunks/chunk-CUL66KRA.js +1 -0
- package/dist/esm/chunks/{chunk-WT7RGGJU.js → chunk-CVNRODH3.js} +1 -1
- package/dist/esm/chunks/{chunk-N3V45JPS.js → chunk-CXHPBT7N.js} +1 -1
- package/dist/esm/chunks/chunk-GF6JTI65.js +1 -0
- package/dist/esm/chunks/chunk-MRSDJPBC.js +1 -0
- package/dist/esm/chunks/chunk-NYDZPTLP.js +1 -0
- package/dist/esm/chunks/chunk-QDHLXXAZ.js +1 -0
- package/dist/esm/chunks/{chunk-4HD4J5JC.js → chunk-QUECUXHD.js} +1 -1
- package/dist/esm/chunks/chunk-RJY76ESL.js +1 -0
- package/dist/esm/chunks/chunk-RPI5C3EJ.js +1 -0
- package/dist/esm/chunks/{chunk-6TFMLT4A.js → chunk-YC4JXWRG.js} +1 -1
- package/dist/esm/chunks/{diagnose-XCEBQKBO.js → diagnose-3XHPZZNP.js} +1 -1
- package/dist/esm/chunks/extras-C724KKG6.js +1 -0
- package/dist/esm/chunks/{markets-ui-M4IQ62CT.js → markets-ui-WBWWQAGU.js} +1 -1
- package/dist/esm/chunks/search-5NFIZBPJ.js +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/server.js +2 -2
- package/dist/tether.diagnose.js +2 -2
- package/dist/tether.diagnose.min.js +2 -2
- package/dist/tether.extras.js +33 -22
- package/dist/tether.extras.min.js +1 -1
- package/dist/tether.js +201 -186
- package/dist/tether.markets.js +13 -2
- package/dist/tether.markets.min.js +1 -1
- package/dist/tether.min.js +3 -3
- package/dist/tether.min.js.map +4 -4
- package/dist/types/src/cart/mutations.d.ts +2 -2
- package/dist/types/src/cart.d.ts +1 -0
- package/dist/types/src/client.d.ts +16 -11
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/markets.d.ts +9 -2
- package/dist/types/src/uri.d.ts +6 -0
- package/package.json +54 -5
- package/dist/esm/chunks/analytics-PG5FPRDN.js +0 -1
- package/dist/esm/chunks/chunk-E5YO6274.js +0 -1
- package/dist/esm/chunks/chunk-EW5SYO6L.js +0 -1
- package/dist/esm/chunks/chunk-HJY2JSNB.js +0 -1
- package/dist/esm/chunks/chunk-MQYB6BH4.js +0 -1
- package/dist/esm/chunks/chunk-RPMBCAGS.js +0 -1
- package/dist/esm/chunks/chunk-VFNHIGCS.js +0 -1
- package/dist/esm/chunks/chunk-YN6LEBEN.js +0 -1
- package/dist/esm/chunks/chunk-Z6HS3H7K.js +0 -1
- package/dist/esm/chunks/extras-4HU3VSBQ.js +0 -1
- package/dist/esm/chunks/search-A5DS2IOS.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as Z,d as Pt,g as Q,h as kt,p as q,v as Et}from"./chunk-YC4JXWRG.js";import{A as W,C as v,D as vt,E as At,F as g,G as k,H as M,K as Lt,P as D,a as b,c as U,d as H,h as V,k as ht,l as L,m as s,n as f,o as yt,p as d,t as y,v as bt,w as P,x as St,y as T,z as wt}from"./chunk-CUL66KRA.js";import{C as Ct,r as l,x as gt,z as w}from"./chunk-QDHLXXAZ.js";var ne={id:"string",quantity:"number",attributes:["object"],cost:{totalAmount:q,subtotalAmount:q,amountPerQuantity:q},merchandise:{id:"string",selectedOptions:["object"],product:"object"}},tt={id:"string",checkoutUrl:"string",totalQuantity:"number",attributes:["object"],discountCodes:["object"],cost:{totalAmount:q,subtotalAmount:q},lines:{nodes:[ne]}};var re='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',ie=60,et=!1,K=null,oe=t=>t!==null&&"focus"in t,It=t=>d(t,re).filter(e=>e.offsetParent!==null||e===document.activeElement),$=()=>d(document,s("cart-drawer")),nt=t=>t.classList.contains(l.cartDrawerOpenClass);function S(){let t=$();return t.length?t.some(nt):et}function j(t){d(document,s("cart-open")).forEach(e=>{e.setAttribute("aria-expanded",String(t))}),$().forEach(e=>{e.hasAttribute("role")||e.setAttribute("role","dialog"),!e.hasAttribute("aria-label")&&!e.hasAttribute("aria-labelledby")&&e.setAttribute("aria-label",f(e,"cart-label")||"Cart"),e.setAttribute("aria-modal",String(t)),!nt(e)&&(e.setAttribute("aria-hidden","true"),l.cartFocus&&(e.inert=!0))})}function ae(t){let e=It(t)[0]??t;e===t&&!t.hasAttribute("tabindex")&&(t.tabIndex=-1),e.focus({preventScroll:!0})}function B(){if(S())return;et=!0;let t=$().filter(n=>f(n,"cart-drawer")!=="manual");t.forEach(n=>{n.inert=!1,n.classList.add(l.cartDrawerOpenClass),n.setAttribute("aria-hidden","false")}),j(!0);let[e]=t;l.cartFocus&&e&&(K=oe(document.activeElement)?document.activeElement:null,setTimeout(()=>{ae(e)},ie)),l.onCartOpen?.(t),y("cart-toggled",{open:!0})}function rt(){if(!S())return;et=!1;let t=$(),e=t.some(n=>n.contains(document.activeElement));t.forEach(n=>{n.classList.remove(l.cartDrawerOpenClass),n.setAttribute("aria-hidden","true"),l.cartFocus&&(n.inert=!0)}),j(!1),e&&K?.isConnected&&K.focus({preventScroll:!0}),K=null,l.onCartClose?.(t),y("cart-toggled",{open:!1})}function xt(){S()?rt():B()}function se(t){if(t.key!=="Tab"||!l.cartFocus||!S())return;let e=$().find(nt);if(!e)return;let n=It(e),r=n[0],i=n.at(-1);if(!r||!i)return;let o=document.activeElement,a=t.shiftKey?o===r:o===i;e.contains(o)&&!a||(t.preventDefault(),(t.shiftKey?i:r).focus())}var ue=/^image:(\d+)$/,Tt="metafield:",ce=/^(rich_text|multi_line_text)_field$/,le=["","true","all","*"],ot=t=>t.tagName==="SELECT",it=(t,e)=>t.$(`select${e}`).filter(ot);function de(t,e){let n=e.images.nodes,r=[...t.children].map(o=>o.tagName==="IMG"?o:o.querySelector("img"));!St(t)&&r.length===n.length&&r.every((o,a)=>bt(o?.getAttribute("src"),n[a]?.url))||T(t,n,(o,a)=>{let u=o.matches(`img,${s("bind","image")}`)?o:d(o,"img")[0]??o;P(u,a.url,a.altText||e.title)})}function me(t,e,n){let r=n.indexOf("."),i=n.slice(0,r),o=n.slice(r+1),a=(e.metafields??[]).find(c=>c?.namespace===i&&c.key===o);if(!a){g(t,"");return}let u=a.reference?.image;if(u){P(t,u.url,u.altText);return}ce.test(a.type)&&(t.style.whiteSpace="pre-line"),g(t,a.value)}var pe=new Map(Object.entries({title:t=>t.title,"description-text":t=>t.description,vendor:t=>t.vendor,type:t=>t.productType,handle:t=>t.handle,"published-at":t=>vt(t.publishedAt),"min-price":t=>v(t.priceRange.minVariantPrice),"max-price":t=>v(t.priceRange.maxVariantPrice)}));function fe(t,e){let n=(t.getAttribute("exclude")??"").split(",").map(i=>i.trim()).filter(Boolean),r=e.tags.filter(i=>!n.includes(i));T(t,r,(i,o)=>{g(i,o)})}function ge(t,e,n){let r=pe.get(e);if(r){g(t,r(n));return}switch(e){case"description":At(t,n.descriptionHtml);break;case"featured-image":P(t,n.featuredImage?.url,n.featuredImage?.altText||n.title);break;case"url":case"link":{let i=W(n.handle,n.id);i&&t.setAttribute("href",i),e==="url"&&!t.firstElementChild&&!t.textContent.trim()&&g(t,n.title);break}case"images":de(t,n);break;case"tags":fe(t,n);break;default:he(t,e,n)}}function he(t,e,n){let r=ue.exec(e);if(r){let i=n.images.nodes[Number(r[1])-1]??n.featuredImage;P(t,i?.url,i?.altText||n.title)}else e.startsWith(Tt)&&me(t,n,e.slice(Tt.length))}function ye(t){let{product:e}=t;t.$(s("option-list")).forEach(n=>{let r=t.optName(f(n,"option-list")),i=e.options.find(o=>o.name===r);if(!i||i.optionValues.length<=1&&yt(n,"hide-single")){M(n,!1);return}T(n,i.optionValues,(o,a)=>{o.setAttribute(L("option-value"),a.name);let u=d(o,s("bind","option-value"))[0];u?g(u,a.name):o.firstElementChild||g(o,a.name);let c=d(o,s("bind","swatch"))[0],{swatch:p}=a;!c||!p||(p.color&&(c.style.backgroundColor=p.color),p.image?.previewImage&&P(c,p.image.previewImage.url,a.name))})})}function Ce(t){let{product:e}=t;it(t,s("option")).forEach(n=>{let r=e.options.find(i=>i.name===t.optName(f(n,"option")));if(!r){M(n,!1);return}n.replaceChildren(...r.optionValues.map(i=>new Option(i.name,i.name)))}),it(t,s("variant-select")).forEach(n=>{n.replaceChildren(...e.variants.nodes.map(r=>new Option(r.title,r.id)))}),it(t,s("plan")).forEach(n=>{let r=t.plans.map(a=>new Option(a.name,a.id)),i=!e.requiresSellingPlan&&f(n,"plan")!=="subscription-only",o=n.getAttribute(L("one-time-label"))||"One-time purchase";n.replaceChildren(...i?[new Option(o,"")]:[],...r)})}function be(t){t.$(s("plan-list")).forEach(e=>{let n=(f(e,"plan-list")??"").trim(),r=le.includes(n.toLowerCase())?null:n,i=t.plans.filter(o=>!r||o.group.name===r);T(e,i,(o,a)=>{o.setAttribute(L("plan-value"),a.id),!o.firstElementChild&&!o.querySelector(s("plan-bind"))&&g(o,a.name)})})}function Xe(t){t.$(s("bind")).forEach(e=>{ge(e,f(e,"bind")??"",t.product)}),ye(t),Ce(t),be(t)}var Mt="Default Title",at=(t,e)=>e.get(t.id)?.quantity??t.quantity,$t=t=>t.split("/").pop()??t;function Se(t){let e=t.merchandise,n=W(e.product.handle,e.product.id);if(!n)return null;let r=new URLSearchParams;r.set("variant",$t(e.id));let i=t.sellingPlanAllocation?.sellingPlan.id;return i&&r.set("selling_plan",$t(i)),`${n}${n.includes("?")?"&":"?"}${r.toString()}`}var Ot=t=>t.merchandise.product.title,qt={title:Ot,"product-title":Ot,"variant-title":t=>t.merchandise.title===Mt?"":t.merchandise.title,options:t=>t.merchandise.selectedOptions.filter(e=>e.value!==Mt).map(e=>`${e.name}: ${e.value}`).join(", "),vendor:t=>t.merchandise.product.vendor,sku:t=>t.merchandise.sku??"",price:t=>v(t.cost.amountPerQuantity),"compare-at-price":t=>v(t.cost.compareAtAmountPerQuantity??t.merchandise.compareAtPrice),"line-total":t=>v(t.cost.totalAmount),"line-subtotal":t=>v(t.cost.subtotalAmount),quantity:(t,e)=>at(t,e.pending),plan:t=>t.sellingPlanAllocation?.sellingPlan.name??"","plan-description":t=>t.sellingPlanAllocation?.sellingPlan.description??"",components:t=>(t.lineComponents??[]).map(e=>`${e.quantity} \xD7 ${e.merchandise.product.title}`).join(", ")},Rt="attribute:";function we(t,e,n){if(Object.hasOwn(qt,e))return qt[e]?.(t,n);if(!e.startsWith(Rt))return;let r=e.slice(Rt.length);return t.attributes.find(i=>i.key===r)?.value??""}function ve(t,e,n){let r=kt(n),i=!n.requiresSellingPlan&&f(t,"line-plan")!=="subscription-only",o={value:"",label:t.getAttribute(L("one-time-label"))||"One-time purchase"},a=[...i?[o]:[],...r.map(c=>({value:c.id,label:c.name}))],u=a.map(c=>c.value).join("|");t.dataset.tetherSig!==u&&(t.replaceChildren(...a.map(c=>{let p=document.createElement("option");return p.value=c.value,p.textContent=c.label,p})),t.dataset.tetherSig=u),t.value=e.sellingPlanAllocation?.sellingPlan.id??"",M(t,r.length>0)}function Ae(t,e,n){let r=!!e.sellingPlanAllocation;t.classList.toggle("is-subscription",r);let i=n.warnings.find(u=>u.target===e.id);t.classList.toggle("is-warning",!!i);let o=n.pending.has(e.id);t.classList.toggle("is-busy",o),o?t.setAttribute("aria-busy","true"):t.removeAttribute("aria-busy"),d(t,s("line","warning")).forEach(u=>{k(u,i?.message??"")});let a=new Map([["subscription",r],["one-time",!r],["on-sale",Pt(e.cost.compareAtAmountPerQuantity?.amount,e.cost.amountPerQuantity.amount)],["has-components",(e.lineComponents??[]).length>0],["warning",!!i]]);d(t,s("line-show")).forEach(u=>{let c=f(u,"line-show"),p=c===null?void 0:a.get(c);p!==void 0&&M(u,p)})}function Le(t,e,n){let r=e.merchandise;t.setAttribute(L("line-id"),e.id),d(t,s("line")).forEach(o=>{let a=f(o,"line")??"";if(a==="image"){P(o,r.image?.url??r.product.featuredImage?.url,r.product.title);return}if(a==="url"){let c=Se(e);c&&o.setAttribute("href",c);return}let u=we(e,a,n);u!==void 0&&k(o,u)}),Ae(t,e,n),d(t,s("line-plan")).filter(ot).forEach(o=>{Et(r.product.handle).then(a=>{ve(o,e,a)}).catch(a=>{w(a,"line plan options")})})}function Pe(t,e){let n=t?.totalQuantity??0,r=(t?.lines.nodes??[]).some(o=>o.sellingPlanAllocation),i=new Map([["cart-empty",n===0],["cart-filled",n>0],["cart-has-subscription",r],["cart-no-subscription",!r],["cart-has-discount",(t?.discountCodes??[]).some(o=>o.applicable)],["cart-error",e.failed],["cart-warning",e.warnings.length>0]]);d(document,s("show")).forEach(o=>{let a=f(o,"show"),u=a===null?void 0:i.get(a);u===void 0||o.closest(s("product"))||M(o,u)}),d(document,s("checkout")).forEach(o=>{o.classList.toggle("is-disabled",!n),o.setAttribute("aria-disabled",String(!n))})}function ke(t){d(document,`textarea${s("cart-note")},input${s("cart-note")}`).forEach(e=>{document.activeElement!==e&&g(e,t?.note??"")}),d(document,s("cart-discounts")).forEach(e=>{T(e,t?.discountCodes??[],(n,r)=>{n.setAttribute(L("discount-code"),r.code);let i=n.querySelector(s("discount","code"))??(n.firstElementChild?null:n);i&&g(i,r.code),n.classList.toggle("is-inapplicable",!r.applicable)})})}function Ut(t){let{cart:e}=t,n=r=>e?v(e.cost[r]):"";j(S()),d(document,s("cart-count")).forEach(r=>{k(r,e?.totalQuantity??0)}),d(document,s("cart-subtotal")).forEach(r=>{k(r,n("subtotalAmount"))}),d(document,s("cart-total")).forEach(r=>{k(r,n("totalAmount"))}),d(document,s("cart-checkout-charge")).forEach(r=>{k(r,n("checkoutChargeAmount"))}),Pe(e,t),d(document,s("cart-warning")).forEach(r=>{k(r,[...new Set(t.warnings.map(i=>i.message))].join(" "))}),ke(e),d(document,s("cart-lines")).forEach(r=>{wt(r,e?.lines.nodes??[],i=>i.id,(i,o)=>{Le(i,o,t)},{onEnter:l.onLineEnter,onLeave:l.onLineLeave})}),e&&Lt("cart")}function Dt(t){d(document,s("cart-count")).forEach(e=>{/^\s*0?\s*$/.test(e.textContent)&&(e.textContent=String(t))})}function st(t,e="localStorage"){try{return window[e].getItem(t)}catch{return null}}function ut(t,e,n="localStorage"){try{window[n].setItem(t,e)}catch{}}function Qt(t,e="localStorage"){try{window[e].removeItem(t)}catch{}}var Nt=/^gid:\/\/shopify\/Cart\/[\w-]+(\?key=[\w-]+)?$/;var h={kind:"unknown"},R=[],O=new Map,G=()=>h;function m(){switch(h.kind){case"ready":case"error":return h.cart;case"unknown":case"empty":return null}}var Ft=()=>R,ct=t=>t?{kind:"ready",cart:t}:{kind:"empty"},Ht=()=>`${l.storageKey}:seen`;function E(){let t=st(l.storageKey);return t?Nt.test(t)?t:(I(),null):null}function I(){Qt(l.storageKey)}function lt(t){h=ct(t),t&&ut(l.storageKey,t.id)}function N(){Ut({cart:m(),warnings:R,pending:O,failed:h.kind==="error"})}function _(t){N(),y("cart-updated",{cart:m(),reason:t})}function C(t,e){return lt(t),ut(Ht(),`${Date.now()}|${t?.totalQuantity??0}`),_(e),t}function F(t){h=t.kind==="loaded"?ct(t.cart):{kind:"error",error:t.error,cart:null},_("load")}function Ee(){let t=st(Ht())?.split("|")[1]??"",e=Number(t);return/^\d+$/.test(t)&&Number.isSafeInteger(e)?e:null}function Vt(){if(h.kind!=="unknown")return;let t=Ee();t!==null&&Dt(t)}function Wt(t){R=t.filter((e,n)=>t.findIndex(r=>r.message===e.message)===n).map(e=>({...e,message:l.warningText?.(e)||e.message})),R.length&&y("cart-warning",{warnings:R})}var _t=()=>{};function Ie(){let t=Promise.resolve();return e=>{let n=t.then(e);return t=n.then(_t,_t),n}}var xe=Ie();function Kt(t){return xe(t).then(e=>(h.kind==="error"&&(h=ct(h.cart),N()),e),e=>{throw h={kind:"error",error:e,cart:m()},N(),y("cart-error",{error:e}),e})}var dt=t=>at(t,O),Te=()=>({open:S(),count:m()?.totalQuantity??0,loaded:h.kind!=="unknown",warnings:[...R]});function jt(t){let e=["cart-updated","cart-toggled"].map(r=>`${l.prefix}:${r}`),n=()=>{t(m(),Te())};return e.forEach(r=>{document.addEventListener(r,n)}),n(),()=>{e.forEach(r=>{document.removeEventListener(r,n)})}}var Me=/does not exist|not found|invalid id/i,$e=t=>H({[t]:U({cart:U(tt)})});function X(t){return t instanceof b?t.userErrors?.some(e=>e.field?.[0]==="cartId")?!0:(t.errors??[]).some(e=>Me.test(e.message)):!1}function Gt(t){if(!(t instanceof b))return!1;let{code:e,status:n=0}=t;return e==="NETWORK"||e==="INVALID_RESPONSE"||e==="SERVER_ERROR"||n>=500}function Xt(t,e=1,n={}){let r=typeof t=="object"&&t!==null?t:{...n,quantity:e,...t==null?{}:{variantId:t}},i=Q.variant(r.merchandiseId||r.variantId||r.id);if(!i)throw new b("add(): variantId is required");let o=parseInt(String(r.quantity??1),10),a={merchandiseId:i,quantity:Math.max(1,o||1)},u=Q.sellingPlan(r.sellingPlanId||r.sellingPlan);u&&(a.sellingPlanId=u);let c=D(r.attributes);return c.length&&(a.attributes=c),a}function Oe(t,e,n){return r=>`mutation Tether_${t}(${e}){${t}(${n}){cart{...TetherCart}userErrors{field message}warnings{code message target}}}${Z(r)}`}async function Yt(t,e,n,r){let i=await V(Oe(t,e,n),r,$e(t),{operation:"mutation"}),o=ht(i[t],t);return Wt(o.warnings??[]),o.cart}function Bt(t){let e=l.country?{buyerIdentity:{countryCode:l.country},...t}:t;return Yt("cartCreate","$input: CartInput!","input: $input",{input:e})}async function x({name:t,args:e,inner:n,variables:r,createInput:i}){let o=E();if(!o)return i?Bt(i):null;try{return await Yt(t,`$cartId: ID!, ${e}`,`cartId: $cartId, ${n}`,{...r,cartId:o})}catch(a){if(!X(a)||(I(),!i))throw a;return gt("cart expired, creating a new one"),Bt(i)}}async function mt(t){return(await V(n=>`query TetherCart($id:ID!){cart(id:$id){...TetherCart}}${Z(n)}`,{id:t},H({cart:U(tt)}))).cart}async function zt(t){return(await V("query TetherCheckout($id: ID!) { cart(id: $id) { checkoutUrl } }",{id:t},H({cart:U({checkoutUrl:"string"})}))).cart?.checkoutUrl??null}function Jt(t,e){let n=typeof e=="number"?{quantity:e}:e,r={id:t};n.quantity!==void 0&&(r.quantity=n.quantity),"sellingPlanId"in n&&(r.sellingPlanId=n.sellingPlanId?Q.sellingPlan(n.sellingPlanId):null),n.attributes&&(r.attributes=D(n.attributes));let i=n.merchandiseId||n.variantId;return i&&(r.merchandiseId=Q.variant(i)),r}var pt=t=>x({name:"cartLinesUpdate",args:"$lines: [CartLineUpdateInput!]!",inner:"lines: $lines",variables:{lines:t},createInput:null}),Y=t=>x({name:"cartLinesRemove",args:"$lineIds: [ID!]!",inner:"lineIds: $lineIds",variables:{lineIds:t},createInput:null}),Zt=(t,e)=>e>0?pt([{id:t,quantity:e}]):Y([t]);var ft=null;function te(t){ft=t}var qe=t=>zt(t).then(e=>({kind:"url",url:e}),e=>({kind:"failed",error:e}));async function Re(){if(!ft)return null;try{let t=await ft();return t&&`${t}${t.includes("?")?"&":"?"}logged_in=true`}catch(t){return w(t,"account checkout"),null}}async function Ue(t){let e=qe(t),n=await Re();if(n)return n;let r=await e;if(r.kind==="failed")throw r.error;if(!r.url)throw new b("No checkoutUrl (cart empty or expired)");return r.url}function De(t){try{t.opener=null}catch{}}async function ee(t=l.checkoutTarget){let e=E(),n=m();if(!e||n&&!n.totalQuantity)return null;let r=t==="_blank"?window.open("","_blank"):null;r&&De(r);try{let i=await Ue(e);if(!Ct(i))throw new b("The checkout URL is not https: not opened");return y("checkout",{url:i,cart:m()}),r&&!r.closed?r.location.href=i:window.location.href=i,i}catch(i){return r?.close(),w(i,"checkout failed"),null}}var J=()=>m()?.lines.nodes??[];async function Qe(){let t=E();if(t)try{let e=await mt(t);e||I(),C(e,"load")}catch(e){w(e,"cart reload after a failed change")}}function A(t){return Kt(()=>t().catch(async e=>{throw Gt(e)&&await Qe(),e}))}function Ne(t,e){let n=J().find(u=>u.id===t);if(!n)return Promise.resolve(m());let r=Math.max(0,dt(n)+e),i={quantity:r};O.set(t,i),_("pending");let o=()=>O.get(t)===i;return A(async()=>{if(!o())return m();if(J().find(p=>p.id===t)?.quantity===r)return m();let c=await Zt(t,r);return o()?C(c,r>0?"update":"remove"):(lt(c),c)}).finally(()=>{o()&&(O.delete(t),_("settled"))})}function _e(t){let e=(m()?.discountCodes??[]).map(r=>r.code),n=typeof t=="function"?t(e):t;return(Array.isArray(n)?n:[n]).map(r=>r.trim()).filter(Boolean)}function Fe(t){let e=new Map((m()?.attributes??[]).map(n=>[n.key,n.value]));return D(t).forEach(n=>e.set(n.key,n.value)),[...e].filter(([,n])=>n!=="").map(([n,r])=>({key:n,value:r}))}async function He(){let t=E();if(!t)return F({kind:"loaded",cart:null}),null;Vt();try{let e=await mt(t);e||I(),F({kind:"loaded",cart:e})}catch(e){w(e,"cart load failed"),X(e)&&I(),F({kind:"failed",error:e})}return m()}var z={init:He,id:E,get status(){return G()},get state(){return m()},get lines(){return[...J()]},get count(){return m()?.totalQuantity??0},get loaded(){return G().kind!=="unknown"},get lastError(){let t=G();return t.kind!=="error"?null:t.error instanceof Error?t.error:new Error(String(t.error))},get warnings(){return[...Ft()]},get pendingQty(){return O},setCheckoutResolver:te,forgetSaved(){I(),F({kind:"loaded",cart:null})},render:N,subscribe:jt,add(t,e=1,n={}){let r=(Array.isArray(t)?t:[t]).map(i=>Xt(i,e,n));return A(async()=>{let i=await x({name:"cartLinesAdd",args:"$lines: [CartLineInput!]!",inner:"lines: $lines",variables:{lines:r},createInput:{lines:r}});if(!i)throw new b("Shopify answered the add without a cart");return C(i,"add"),y("added",{cart:i,lines:r}),l.openCartOnAdd&&B(),i})},updateLine(t,e){let n=typeof e=="number"?e:e.quantity;if(n!==void 0&&n<=0)return z.removeLine(t);let r=Jt(t,e);return A(async()=>C(await pt([r]),"update"))},changeQuantity:Ne,quantityOf:dt,removeLine(t){let e=Array.isArray(t)?t:[t];return A(async()=>C(await Y(e),"remove"))},clear(){return A(async()=>{let t=J().map(e=>e.id);return t.length?C(await Y(t),"remove"):m()})},setNote(t){let e={note:t??""};return A(async()=>C(await x({name:"cartNoteUpdate",args:"$note: String!",inner:"note: $note",variables:e,createInput:e}),"note"))},setAttributes(t){return A(async()=>{let e={attributes:Fe(t)},n=await x({name:"cartAttributesUpdate",args:"$attributes: [AttributeInput!]!",inner:"attributes: $attributes",variables:e,createInput:e});return C(n,"attributes")})},setDiscountCodes(t){return A(async()=>{let e={discountCodes:_e(t)},n=await x({name:"cartDiscountCodesUpdate",args:"$discountCodes: [String!]!",inner:"discountCodes: $discountCodes",variables:e,createInput:e});return C(n,"discount")})},async applyDiscount(t){let e=await z.setDiscountCodes(i=>[...new Set([...i,t])]),n=t.toLowerCase();if((e?.discountCodes??[]).find(i=>i.code.toLowerCase()===n)?.applicable)return e;try{await z.removeDiscount(t)}catch(i){w(i,"removing a discount code Shopify refused")}throw new b(`Discount code not valid: ${t}`,{code:"INVALID_DISCOUNT"})},removeDiscount(t){let e=t.toLowerCase();return z.setDiscountCodes(n=>n.filter(r=>r.toLowerCase()!==e))},setBuyerIdentity(t,{create:e=!0}={}){return A(async()=>{let n=await x({name:"cartBuyerIdentityUpdate",args:"$buyerIdentity: CartBuyerIdentityInput!",inner:"buyerIdentity: $buyerIdentity",variables:{buyerIdentity:t},createInput:e?{buyerIdentity:t}:null}).catch(r=>{if(e||!X(r))throw r;return null});return C(n,"buyer-identity")})},checkout:ee,drawers:$,isOpen:S,open:B,close:rt,toggle:xt};export{se as a,ot as b,it as c,Xe as d,st as e,ut as f,Qt as g,z as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as M}from"./chunk-BMDYNMRC.js";import{e as m,f as p}from"./chunk-RJY76ESL.js";import{m as k,o as i,p as g,r as u,u as y}from"./chunk-QDHLXXAZ.js";var S="tether_country",C=()=>`${u.prefix}:market:${u.domain}`,w={getItem:e=>m(e)};function b(){let e=typeof window<"u";return{document:typeof document<"u"?document:null,location:e?window.location:null,storage:w,global:e?window:{}}}function E(e){try{return JSON.parse(e)}catch(t){if(t instanceof SyntaxError)return null;throw t}}function L(e){if(typeof e!="object"||e===null)return null;let t=i(Reflect.get(e,"country"));if(!t)return null;let n=Reflect.get(e,"locale");return{country:t,language:g(Reflect.get(e,"language"))??void 0,locale:typeof n=="string"&&n?n:void 0}}var h=e=>L(E(e));function x(e=w){let t=e.getItem(C());return t?h(t):null}function R(e,t){if(!e||!t)return null;let n=e.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${t}=`));return n?M(n.slice(t.length+1)):null}function s(e,t){if(!e||!t)return null;let n=t.toLowerCase(),r=Object.keys(e).find(o=>o.toLowerCase()===n);return r?e[r]??null:null}function v(e,t){let n=a=>t.document?.querySelector(`meta[name="${a}"]`)?.getAttribute("content"),r=Reflect.get(t.global,"TETHER_COUNTRY"),o=Reflect.get(t.global,"TETHER_LANGUAGE"),l=n("tether-country")||R(t.document,e.cookie||S);return{country:r||l,language:o||n("tether-language")}}function N(e,t){let n=(t.location?.pathname??"/").split("/").find(c=>c!==""),r=s(e.locales,n);if(r)return r;let o=t.document?.documentElement.getAttribute("lang");if(!o)return null;let l=s(e.locales,o)??s(e.locales,o.split("-")[0]);if(l)return{locale:o,...l};if(e.locales&&e.strict)return null;let a=o.split("-")[1];return{language:o,country:a?.length===2?a:null,locale:o}}function O(e,t,n){switch(e){case"saved":return t.remember===!1?null:x(n.storage);case"server":return v(t,n);case"webflow":return N(t,n)}}function H(e){return e?e===!0?k:e:["saved"]}function I(e=u.markets,t=b()){let n=(e===u.markets?e:y(e))??{};if(n.detect===!1)return{};let r={},o={sources:r};for(let l of H(n.detect)){let a=O(l,n,t);if(!a)continue;let c=i(a.country),d=g(a.language),f=typeof a.locale=="string"&&a.locale?a.locale:null;c&&!o.country&&(o.country=c,r.country=l),d&&!o.language&&(o.language=d,r.language=l),f&&!o.locale&&(o.locale=f,r.locale=l)}return o}function _(e){if(u.markets?.remember===!1)return;let t={country:e.country,language:e.language||void 0,locale:e.locale||void 0};p(C(),JSON.stringify(t))}export{C as a,h as b,x as c,I as d,_ as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as b,b as h,c as y,d as v,
|
|
1
|
+
import{a as b,b as h,c as y,d as v,h as $}from"./chunk-CUL66KRA.js";import{G as k,a as te,d as x,e as T,n as _,r as P,x as V}from"./chunk-QDHLXXAZ.js";var de={};te(de,{GID:()=>Q,allPlans:()=>I,allocationFor:()=>M,findPlan:()=>ue,hasPlans:()=>oe,planAdjustment:()=>ce,planCheckoutCharge:()=>se,planPrice:()=>B,planSavings:()=>ae,plansForVariant:()=>le,toGid:()=>C});var re=/^(-?)(\d+)(?:\.(\d+))?$/;function G(e,n){let t=re.exec(e.trim());if(!t)return null;let[,r="",o="0",l=""]=t,u=BigInt(`${o}${l.padEnd(n,"0")}`);return r==="-"?-u:u}var L=e=>e.split(".")[1]?.length??0;function Fe(e,n){if(e==null||n==null)return!1;let t=Math.max(L(e.trim()),L(n.trim())),r=G(e,t),o=G(n,t);return r===null||o===null?!1:r>o}var q=2,U=new Map;function W(e){let n=U.get(e);if(n!==void 0)return n;let t=q;try{t=new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??q}catch{}return U.set(e,t),t}function O(e){return Math.round(parseFloat(e.amount)*10**W(e.currencyCode))}function K(e,n){let t=W(n);return{amount:(e/10**t).toFixed(t),currencyCode:n}}var ie=100;function C(e,n){let t=typeof e=="string"||typeof e=="number"?String(e).trim():"";return t?t.startsWith("gid://")?t:/^\d+$/.test(t)?`gid://shopify/${n}/${t}`:t:null}var Q={product:e=>C(e,"Product"),variant:e=>C(e,"ProductVariant"),sellingPlan:e=>C(e,"SellingPlan")};function I(e){return(e?.sellingPlanGroups?.nodes??[]).flatMap(t=>t.sellingPlans.nodes.map(r=>({...r,group:t})))}function oe(e){return I(e).length>0}function M(e,n){return!e||!n?null:(e.sellingPlanAllocations?.nodes??[]).find(r=>r.sellingPlan.id===n)??null}function le(e,n){return I(e).filter(t=>M(n,t.id))}function B(e,n){let t=M(e,n)?.priceAdjustments[0];return t?.perDeliveryPrice??t?.price??e?.price??null}function se(e,n){let t=M(e,n);return t?.checkoutChargeAmount??t?.priceAdjustments[0]?.price??e?.price??null}function ae(e,n){let t=B(e,n);if(!e||!t)return{amount:null,percentage:0};let r=parseFloat(e.price.amount),o=parseFloat(t.amount);if(!Number.isFinite(r)||!Number.isFinite(o)||r<=0||o>=r)return{amount:null,percentage:0};let l=O(e.price)-O(t);return{amount:K(l,e.price.currencyCode),percentage:Math.round((1-o/r)*ie)}}function ce(e){let n=e?.priceAdjustments[0]?.adjustmentValue;if(!n)return null;switch(n.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:n.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"amount",value:n.adjustmentAmount};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:n.price};default:return null}}function ue(e,n){if(!n)return null;let t=I(e),r=Q.sellingPlan(n),o=n.trim().toLowerCase();return t.find(l=>l.id===r)??t.find(l=>l.name.toLowerCase()===o)??t.find(l=>l.options.some(u=>u.value.toLowerCase()===o))??null}var i="amount currencyCode",H={inventory:!0},Y=e=>e.inventory?"quantityAvailable":"",g="url altText width height";function pe(e){let n=[];for(let r of e){let o=_(r);o&&n.push(o)}return n.length?`metafields(identifiers:[${n.map(({namespace:r,key:o})=>`{namespace: ${JSON.stringify(r)}, key: ${JSON.stringify(o)}}`).join(", ")}]){namespace key type value reference{... on MediaImage{image{${g}}}}}`:""}var ge=` id name description recurringDeliveries options{name value}priceAdjustments{orderCount adjustmentValue{__typename ... on SellingPlanPercentagePriceAdjustment{adjustmentPercentage}... on SellingPlanFixedAmountPriceAdjustment{adjustmentAmount{${i}}}... on SellingPlanFixedPriceAdjustment{price{${i}}}}}`,me=` sellingPlan{id}checkoutChargeAmount{${i}}remainingBalanceChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}unitPrice{${i}}}`;function z(e=P,n=H){return` fragment TetherProduct on Product{id handle title description descriptionHtml productType vendor tags availableForSale publishedAt onlineStoreUrl requiresSellingPlan seo{title description}featuredImage{${g}}images(first:${e.imagesFirst}){nodes{${g}}}options{name optionValues{name swatch{color image{previewImage{${g}}}}}}priceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}compareAtPriceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}${pe(e.metafields)} sellingPlanGroups(first:${e.sellingPlanGroupsFirst}){nodes{name appName options{name values}sellingPlans(first:${e.sellingPlansFirst}){nodes{${ge}}}}}variants(first:${e.variantsFirst}){nodes{id title availableForSale currentlyNotInStock ${Y(n)} sku barcode selectedOptions{name value}image{${g}}price{${i}}compareAtPrice{${i}}unitPrice{${i}}sellingPlanAllocations(first:${e.sellingPlansFirst}){nodes{${me}}}}}}`}function Ne(e=H){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 ${Y(e)} image{${g}}price{${i}}compareAtPrice{${i}}selectedOptions{name value}product{id title handle vendor featuredImage{${g}}}}}... on ComponentizableCartLine{lineComponents{id quantity merchandise{... on ProductVariant{id title product{title handle}}}}}}}}`}function J(){return`
|
|
2
2
|
id handle title description descriptionHtml
|
|
3
3
|
image { ${g} }
|
|
4
4
|
seo { title description }`}var N={amount:"string",currencyCode:"string"},f={id:"string",handle:"string",title:"string",options:["object"],images:{nodes:["object"]},priceRange:{minVariantPrice:N,maxVariantPrice:N},variants:{nodes:[{id:"string",price:N,selectedOptions:["object"]}]}},D={nodes:[f],pageInfo:{hasNextPage:"boolean"}},_e=e=>T(e,"id")!==""&&T(e,"handle")!==""&&h(e,f),X=e=>x(e)&&(e.id===void 0||h(e,f));var fe=1e4,Pe=6e4,c=new Map,E=new Map,m=new Set,F=new Map,ne=[],R=!1,A=0,Z=e=>e.startsWith("gid://"),j=k;function S(e){if(!e)return;let n=Promise.resolve(e);c.set(e.handle,n),c.set(e.id,n)}function he(e){let n=j(e);if(!n)return Promise.reject(new b("empty product key",{code:"NOT_FOUND"}));let t=c.get(n);if(t)return t;let r=new Promise((o,l)=>{E.set(n,{resolve:o,reject:l}),ne.push(n),R||(R=!0,setTimeout(()=>void Se(),0))});return c.set(n,r),r}var w=e=>n=>`${e}${z(P,n)}`;function ye(e){let n=e.filter(Z),t=e.filter(p=>!Z(p)),r=[],o=[],l={};return n.length&&(r.push("$ids: [ID!]!"),l.ids=n,o.push("byId: nodes(ids: $ids) { ... on Product { ...TetherProduct } }")),t.forEach((p,s)=>{r.push(`$h${s}: String!`),l[`h${s}`]=p,o.push(`h${s}: product(handle: $h${s}) { ...TetherProduct }`)}),{query:w(`query TetherProducts(${r.join(",")}){${o.join(" ")}}`),variables:l,handles:t}}function ee(e,n){let t=E.get(e);E.delete(e),t&&n(t)}function $e(e,n){if(n!==A)return;let t=c.get(e);setTimeout(()=>{c.get(e)===t&&c.delete(e)},fe)}function Ae(e){if(!x(e))return!1;let{byId:n=[],...t}=e;return h(n,[y(X)])&&Object.values(t).every(y(f))}async function Se(){R=!1;let e=A,n=ne.splice(0);if(!n.length)return;let{query:t,variables:r,handles:o}=ye(n);V("fetch products",n);let l;try{l=await $(t,r,Ae)}catch(s){n.forEach(d=>{ee(d,a=>{e===A&&c.delete(d),a.reject(s)})});return}let u=new Map;for(let s of l.byId??[])s?.id&&u.set(s.id,s);o.forEach((s,d)=>{let a=l[`h${d}`];a&&u.set(s,a)});let p=Date.now();n.forEach(s=>{ee(s,d=>{let a=u.get(s);if(!a){$e(s,e),d.reject(new b(`Product not found: ${s}`,{code:"NOT_FOUND"}));return}e===A&&(S(a),F.set(a.handle,p),F.set(a.id,p)),d.resolve(a)})})}function Ke(){c.clear(),A+=1,m.clear(),F.clear()}function Qe(e){for(let n of e??[])!n.id||!n.handle||Date.now()-(F.get(n.handle)??0)<Pe&&c.has(n.handle)||(S(n),m.add(n.handle),m.add(n.id))}function Be(e){let n=j(e);return!n||!m.has(n)?!1:(m.delete(n),c.get(n)?.then(t=>{m.delete(t.handle),m.delete(t.id)},xe),!0)}function xe(){}function He(e){let n=j(e);return n&&c.delete(n),he(e)}var be=v({collection:y({handle:"string",products:D})}),ve=v({products:D}),Ce=v({productRecommendations:y([f])}),Ie=`query TetherCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${J()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}`,Me="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}}}";async function Ye({collection:e,query:n,first:t=P.collectionFirst,after:r=null,sortKey:o,reverse:l=!1,filters:u}={}){if(e){let s=await $(w(Ie),{handle:e,first:t,after:r,sortKey:o||void 0,reverse:l,filters:u??void 0},be);if(!s.collection)throw new b(`Collection not found: ${e}`,{code:"NOT_FOUND"});let{products:d,...a}=s.collection;return d.nodes.forEach(S),{collection:a,products:d.nodes,pageInfo:d.pageInfo}}let p=await $(w(Me),{first:t,after:r,query:n||void 0,sortKey:o||void 0,reverse:l},ve);return p.products.nodes.forEach(S),{collection:null,products:p.products.nodes,pageInfo:p.products.pageInfo}}async function ze(e,n="RELATED"){let t=j(typeof e=="object"?e?.id:e),r=t?.startsWith("gid://")??!1,l=(await $(w(`query TetherRecs(${r?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${r?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}`),r?{id:t,intent:n}:{handle:t,intent:n},Ce)).productRecommendations??[];return l.forEach(S),l}export{z as a,Ne as b,J as c,Fe as d,O as e,K as f,Q as g,I as h,M as i,B as j,se as k,ae as l,ce as m,ue as n,de as o,N as p,f as q,_e as r,X as s,j as t,S as u,he as v,Ke as w,Qe as x,Be as y,He as z,be as A,ve as B,Ce as C,Ye as D,ze as E};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as h,e as A}from"./chunk-BMDYNMRC.js";import{a as M}from"./chunk-MRSDJPBC.js";import{h as E,v as D}from"./chunk-YC4JXWRG.js";import{d as P,e as $,h as v,l as p,m as l,n as m,p as d,x as S}from"./chunk-CUL66KRA.js";import{c as k,r as a,w}from"./chunk-QDHLXXAZ.js";var R=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","addresses-loading","addresses-empty","addresses-error","subscriptions-loading","subscriptions-empty","subscriptions-error"]),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"]),x=new Set(`account account-bind account-link account-login account-logout add-label add-to-cart adding-text
|
|
2
2
|
always-enabled bind cart-checkout-charge cart-clear cart-close cart-count cart-discounts cart-drawer cart-label cart-lines
|
|
3
3
|
cart-note cart-open cart-subtotal cart-total cart-warning checkout code collection collection-bind countries country
|
|
4
4
|
country-bind country-label country-select default-plan default-purchase discount discount-code discount-form discount-input
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as v}from"./chunk-GF6JTI65.js";import{a as b,b as S}from"./chunk-RPI5C3EJ.js";import{a as k}from"./chunk-NYDZPTLP.js";import"./chunk-AUVAN3KZ.js";import"./chunk-BMDYNMRC.js";import"./chunk-MRSDJPBC.js";import{h as p}from"./chunk-RJY76ESL.js";import"./chunk-YC4JXWRG.js";import{N as h,O as w,m as l,n as f,o as g,p as d,t as y}from"./chunk-CUL66KRA.js";import{r as s,y as m,z as u}from"./chunk-QDHLXXAZ.js";function U(t,r){let e=w(h(t,"line-attributes"));return r?[{key:"_group",value:r},...e]:e}async function V(t){let r=t.closest(l("group"));if(!r)return null;let e=f(r,"group"),n=U(r,e),i=d(r,l("product")).flatMap(a=>{let o=k.get(a);if(!o?.variant?.availableForSale||o.quantity<=0)return[];let c=o.getLine();return c?[{...c,attributes:[...c.attributes??[],...n]}]:[]});if(!i.length)return m("group-add: nothing selected"),null;try{let a=await p.add(i);return y("group-added",{group:e,lines:i},r),a}catch(a){return u(a,"group add"),null}}function _(t){if(t.key===s.storageKey||t.key===`${s.storageKey}:seen`){p.init().catch(n=>{u(n,"cart from another tab")});return}if(t.key!==b()||!t.newValue)return;let r=S(t.newValue);if(!r)return;let e={language:r.language??null,locale:r.locale,remember:!1};v(r.country,e).catch(n=>{u(n,"market from another tab")})}var E=new WeakMap,K=t=>t.split("/").pop()??t;function x(t){try{window.history.replaceState(window.history.state,"",t)}catch{}}function $(t,{variant:r,sellingPlanId:e}){let n=`${r.id}|${e??""}`,i=E.get(t);if(E.set(t,n),!i||i===n)return;let a=s.variantUrl&&document.querySelector(l("product"))===t;if(!g(t,"variant-url")&&!a)return;let o=new URL(window.location.href);o.searchParams.set("variant",K(r.id)),e?o.searchParams.set("selling_plan",K(e)):o.searchParams.delete("selling_plan"),x(o)}export{V as addGroup,_ as onStorage,$ as writeVariantUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as E,c as P,e as k,f as T,g as A,h as p,i as x}from"./chunk-
|
|
1
|
+
import{a as E,c as P,e as k,f as T,g as A,h as p,i as x}from"./chunk-QUECUXHD.js";import{d as F,e as I}from"./chunk-RPI5C3EJ.js";import"./chunk-NYDZPTLP.js";import"./chunk-AUVAN3KZ.js";import"./chunk-BMDYNMRC.js";import{h as u}from"./chunk-RJY76ESL.js";import{w}from"./chunk-YC4JXWRG.js";import{a as L,d as h,h as b,l as s,m as C,n as v,t as z}from"./chunk-CUL66KRA.js";import{o as f,p as g,r as a,z as y}from"./chunk-QDHLXXAZ.js";var _="{name} ({currency})",j="name",d=null;function B(){d=null}var D="query TetherLocalization{localization{country{isoCode name currency{isoCode symbol}}language{isoCode name}availableCountries{isoCode name currency{isoCode symbol}availableLanguages{isoCode name}}}}",O={isoCode:"string",name:"string",currency:"object"},H=h({localization:{country:O,availableCountries:[O]}});function R(){return d??(d=b(D,{},H).then(e=>e.localization,e=>{throw d=null,e})),d}function U(e,n){switch(n){case"name":return e.name;case"code":return e.isoCode;case"currency":return e.currency.isoCode;case"symbol":return e.currency.symbol;default:return""}}var Y=(e,n)=>e.replace(/\{(name|code|currency|symbol)\}/g,(o,i)=>U(n,i));function q(e,n,o){let i=e.getAttribute(s("country-label"))||_,r=(e.getAttribute(s("countries"))||"").toUpperCase().split(/[\s,]+/).filter(Boolean),c=r.length?r.map(t=>n.find(l=>l.isoCode===t)).filter(t=>t!==void 0):n;e.replaceChildren(...c.map(t=>new Option(Y(i,t),t.isoCode))),e.value=o,e.value!==o&&(e.selectedIndex=-1),e.disabled=c.length<2&&!e.hasAttribute(s("always-enabled"))}function $(e,n,o){let i=(a.country||o.country.isoCode).toUpperCase(),r=[...o.availableCountries].sort((t,l)=>t.name.localeCompare(l.name,a.locale||void 0)),c=r.find(t=>t.isoCode===i)??o.country;e.forEach(t=>{q(t,r,i)}),n.forEach(t=>{t.textContent=U(c,v(t,"country-bind")||j)})}function S(e=document){let n=p(e,`select${C("country-select")}`),o=p(e,C("country-bind"));return!n.length&&!o.length?Promise.resolve():R().then(i=>{$(n,o,i)}).catch(i=>{y(i,"country select")})}var Q=e=>Object.values(a.markets?.locales??{}).find(n=>f(n.country)===e);function V(e,n){return e!==void 0?g(e):n?n.language?g(n.language):void 0:a.language}function Z(e){w();let n=[];return u.id()&&n.push(u.setBuyerIdentity({countryCode:e},{create:!1}).catch(o=>{y(o,"cart country")})),A(),T.forEach(o=>n.push(o.load())),k.forEach(o=>{o.closest(E())||(P.delete(o),x(o))}),n}async function re(e,{language:n,locale:o,remember:i=!0}={}){let r=f(e);if(!r)throw new L(`Not a country code: ${e}`,{code:"INVALID_COUNTRY"});let c=Q(r),t=o||c?.locale,l=t||a.locale,m=V(n,c),M=r!==a.country||m!==a.language||l!==a.locale;if(a.country=r,a.language=m||void 0,a.locale=l,i&&I({country:r,language:m,locale:t}),!M)return S(),u.state;n!==void 0&&B();let N=Z(r);return S(),z("country-changed",{country:r,language:a.language}),await Promise.all(N),u.state}export{F as detectMarket,R as getLocalization,S as renderCountrySelects,re as setCountry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as M}from"./chunk-QUECUXHD.js";import"./chunk-NYDZPTLP.js";import"./chunk-AUVAN3KZ.js";import"./chunk-BMDYNMRC.js";import"./chunk-RJY76ESL.js";import"./chunk-YC4JXWRG.js";import{A as x,C,F as q,H as d,c as S,d as E,h as T,l as A,m as o,n as m,p as h,t as I,w as L,y as w}from"./chunk-CUL66KRA.js";import{b as a,r as u,x as b,z as y}from"./chunk-QDHLXXAZ.js";var N=E({predictiveSearch:S({products:[{priceRange:"object"}],collections:["object"],queries:[{text:"string"}]})}),U="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}}}",D=6,V=2,F="/search",R=new WeakSet,v=0;function $(s,t,e){return parseInt(m(s,t)||"",10)||e}var H=s=>s.tagName==="A"?s:s.querySelector("a");function p(s,t){h(s,o("search-bind")).forEach(e=>{let i=m(e,"search-bind");i==="image"?L(e,t.image?.url,t.image?.altText||t.title):(i==="title"||i==="price"||i==="text")&&t[i]!=null&&q(e,t[i])})}function k(s,t){let e=H(s);e&&(t&&e.setAttribute("href",t),e.setAttribute("role","option"))}var f=class{constructor(t,e,i){a(this,"root");a(this,"input");a(this,"results");a(this,"limit");a(this,"minCharacters");a(this,"resultsId");a(this,"searchNumber",0);a(this,"timer");a(this,"lastTerm","");a(this,"cache",new Map);this.root=t,this.input=e,this.results=i,this.limit=$(t,"search-limit",D),this.minCharacters=$(t,"search-min",V),i.id||(v+=1,i.id=`${u.prefix}-search-${v}`),this.resultsId=i.id,this.setUpAria(),this.listen()}setUpAria(){this.input.setAttribute("role","combobox"),this.input.setAttribute("aria-autocomplete","list"),this.input.setAttribute("aria-controls",this.resultsId),this.input.setAttribute("aria-expanded","false"),this.input.setAttribute("autocomplete","off"),this.results.hasAttribute("role")||this.results.setAttribute("role","listbox"),this.results.hidden=!0}listen(){this.input.addEventListener("input",()=>{let t=this.input.value.trim();t!==this.lastTerm&&(this.lastTerm=t,clearTimeout(this.timer),this.timer=setTimeout(()=>void this.search(t),u.searchDelay))}),this.input.addEventListener("focus",()=>{this.input.value.trim().length>=this.minCharacters&&this.options().length&&this.open(!0)}),this.input.addEventListener("keydown",t=>{this.onKeydown(t)}),document.addEventListener("click",t=>{this.root.contains(t.target)||this.open(!1)})}setState(t){this.root.setAttribute(A("search-state"),t)}open(t){this.root.classList.toggle("is-open",t),this.results.hidden=!t,this.input.setAttribute("aria-expanded",String(t)),t||this.input.removeAttribute("aria-activedescendant")}options(){return h(this.results,'[role="option"]')}async fetchResults(t){let e=this.cache.get(t);if(e)return e;let i=await T(U,{q:t,limit:this.limit},N);return this.cache.set(t,i.predictiveSearch),i.predictiveSearch}async search(t){this.searchNumber+=1;let e=this.searchNumber;if(t.length<this.minCharacters){this.open(!1),this.setState("idle");return}this.setState("loading");try{let i=await this.fetchResults(t);e===this.searchNumber&&this.render(i,t)}catch(i){if(e!==this.searchNumber){b("a superseded search failed",i);return}this.setState("error"),y(i,"search")}}fillList(t,e,i){h(this.results,o(t)).forEach(l=>{w(l,e,i),d(l,e.length>0)})}queryUrl(t){let e=this.root.getAttribute("action")||F,i=e.includes("?")?"&":"?";return`${e}${i}${this.input.name||"q"}=${encodeURIComponent(t)}`}render(t,e){let i=t?.products??[],l=t?.collections??[],c=(t?.queries??[]).filter(n=>n.text.toLowerCase()!==e.toLowerCase());this.fillList("search-products",i,(n,r)=>{let P=C(r.priceRange.minVariantPrice);p(n,{title:r.title,price:P,image:r.featuredImage}),k(n,x(r.handle,r.id)),n.classList.toggle("is-sold-out",!r.availableForSale)}),this.fillList("search-collections",l,(n,r)=>{p(n,{title:r.title,image:r.image}),k(n,`${(u.collectionPath||"/collection").replace(/\/$/,"")}/${r.handle}`)}),this.fillList("search-queries",c,(n,r)=>{p(n,{text:r.text}),H(n)?.setAttribute("href",this.queryUrl(r.text))});let g=i.length+l.length+c.length;this.showCount(g),this.setState(g?"ready":"empty"),this.open(!0),I("search",{term:e,products:i,collections:l,queries:c},this.root)}showCount(t){h(this.root,o("show")).forEach(e=>{let i=m(e,"show");i==="search-empty"&&d(e,t===0),i==="search-results"&&d(e,t>0)}),this.options().forEach((e,i)=>{e.id||(e.id=`${this.resultsId}-${i}`),e.setAttribute("aria-selected","false")})}highlight(t,e){t.forEach((l,c)=>{l.setAttribute("aria-selected",String(c===e))});let i=t[e];i&&(this.input.setAttribute("aria-activedescendant",i.id),i.scrollIntoView?.({block:"nearest"}))}onKeydown(t){let e=this.options(),i=e.findIndex(l=>l.getAttribute("aria-selected")==="true");t.key==="ArrowDown"&&e.length?(t.preventDefault(),this.open(!0),this.highlight(e,(i+1)%e.length)):t.key==="ArrowUp"&&e.length?(t.preventDefault(),this.highlight(e,i<=0?e.length-1:i-1)):t.key==="Enter"&&i>=0?(t.preventDefault(),e[i]?.click()):t.key==="Escape"&&this.open(!1)}};function j(s=document){for(let t of M(s,o("search"))){if(R.has(t))continue;R.add(t);let e=t.querySelector(o("search-input"))??t.querySelector("input"),i=t.querySelector(o("search-results"));e&&i&&new f(t,e,i)}}export{j as mountSearch};
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as nt,b as ot,d as T,f as w,g as C,h as p,i as rt,j as it,k as st,l as k,m as S}from"./chunks/chunk-
|
|
1
|
+
import{a as nt,b as ot,d as T,f as w,g as C,h as p,i as rt,j as it,k as st,l as k,m as S}from"./chunks/chunk-QUECUXHD.js";import{a as at,b as ct,c as h}from"./chunks/chunk-GF6JTI65.js";import"./chunks/chunk-RPI5C3EJ.js";import{a as et}from"./chunks/chunk-NYDZPTLP.js";import"./chunks/chunk-AUVAN3KZ.js";import{b as tt}from"./chunks/chunk-BMDYNMRC.js";import{a as ut,b as lt,c as dt}from"./chunks/chunk-CVNRODH3.js";import{a as l,b as mt}from"./chunks/chunk-MRSDJPBC.js";import{a as z,e as Z,h as s}from"./chunks/chunk-RJY76ESL.js";import{D as J,E as X,o as q,t as K,u as Q,v as W,w as Y}from"./chunks/chunk-YC4JXWRG.js";import{C as j,J as P,M as f,a as v,f as _,j as G,l as d,m as r,r as U,s as g,t as y,u as B}from"./chunks/chunk-CUL66KRA.js";import{e as H,r as c,s as $,v as V,w as E,x as L,y as F,z as a}from"./chunks/chunk-QDHLXXAZ.js";var Nt=["account-login","account-bind","account-link","orders","order","addresses","subscriptions","profile-form","address-form"],Ot=()=>[...Nt.map(t=>`[${d(t)}]`),`[${d("show")}^="logged-"]`].join(",");function Dt(){return!!Z(ut())}function ft(t){!c.account||!(p(t,Ot()).length>0||dt(new URLSearchParams(window.location.search).get("account"))||Dt())||l("account").then(n=>n.mountAccount(t)).catch(n=>{a(n,"account")})}function u(t){return(...e)=>l("account").then(n=>{let o=n[t];return o(...e)})}var pt={login:u("login"),logout:u("logout"),isLoggedIn:u("isLoggedIn"),customer:u("customer"),orders:u("orders"),order:u("order"),updateProfile:u("updateProfile"),addresses:u("addresses"),saveAddress:u("saveAddress"),deleteAddress:u("deleteAddress"),subscriptions:u("subscriptions"),subscriptionAction:u("subscriptionAction"),requestReturn:u("requestReturn"),render:u("render"),mountAccount:u("mountAccount")};var gt=()=>`data-${c.prefix}-key`,ht=t=>t instanceof window.Element;function Et(t){let e=t.closest(`[${gt()}]`),n=e?.getAttribute(gt());return e&&n?{line:e,id:n}:null}function A(t,e){t.catch(n=>{a(n,e)})}function Rt(t,e){let n=Et(e);if(!n?.line.closest(r("cart-lines")))return;let{line:o,id:i}=n;if(e.closest(r("line-remove"))){t.preventDefault(),o.classList.add("is-busy"),A(s.removeLine(i),"cart line");return}let R=Ht(e);!R||!s.lines.some(It=>It.id===i)||(t.preventDefault(),A(s.changeQuantity(i,R),"cart line"))}function Ht(t){return t.closest(r("line-plus"))?1:t.closest(r("line-minus"))?-1:0}function $t(t){let{target:e}=t;if(!ht(e))return;if(e.closest(r("cart-open"))){t.preventDefault(),s.toggle();return}if(e.closest(r("cart-close"))){t.preventDefault(),s.close();return}let n=e.closest(r("cart-clear"));if(n){t.preventDefault(),f(n,()=>s.clear().catch(i=>{a(i,"cart clear")}));return}let o=e.closest(r("checkout"));if(o){t.preventDefault(),f(o,()=>s.checkout());return}Rt(t,e)}function yt(t,e,n){t.classList.add("is-busy"),t.setAttribute("aria-busy","true"),A(e,n)}function Vt(t){let{target:e}=t;if(!ht(e))return;let n=Et(e);n&&e instanceof window.HTMLInputElement&&e.matches(r("line","quantity"))?yt(n.line,s.updateLine(n.id,parseInt(e.value,10)||0),"cart line"):n&&e instanceof window.HTMLSelectElement&&e.matches(r("line-plan"))?yt(n.line,s.updateLine(n.id,{sellingPlanId:e.value||null}),"cart line plan"):Ft(e)&&e.matches(r("cart-note"))&&A(s.setNote(e.value),"cart note")}var Ft=t=>t instanceof window.HTMLInputElement||t instanceof window.HTMLTextAreaElement||t instanceof window.HTMLSelectElement;function _t(t){if(s.isOpen()){if(t.key==="Escape"){s.close();return}z(t)}}function vt(){document.addEventListener("click",$t),document.addEventListener("change",Vt),document.addEventListener("keydown",_t)}var x=t=>t instanceof window.Element;function Gt(t){let e=t.querySelector(r("discount-input"))??t.querySelector("input");return e instanceof window.HTMLInputElement?e:null}function Pt(t,e,n){t.classList.toggle("is-invalid",n),n?e?.setAttribute("aria-invalid","true"):e?.removeAttribute("aria-invalid")}async function Ut(t,e,n){try{await s.applyDiscount(n),Pt(t,e,!1),y("discount-applied",{code:n},t),e&&(e.value="")}catch(o){Pt(t,e,!0),o instanceof v&&o.code==="INVALID_DISCOUNT"?y("discount-invalid",{code:n},t):a(o,"discount")}}function Bt(t){let{target:e}=t,n=x(e)?e.closest(r("discount-form")):null;if(!n)return;t.preventDefault();let o=Gt(n),i=o?.value.trim();i&&f(n,()=>Ut(n,o,i))}function jt(t){let{target:e}=t;if(!x(e))return;let n=e.closest(r("discount-form"));n&&(n.classList.remove("is-invalid"),e.removeAttribute("aria-invalid"))}function qt(t){let{target:e}=t,n=x(e)?e.closest(r("discount-remove")):null;if(!n)return;t.preventDefault();let o=n.closest(r("discount-code"))?.getAttribute(d("discount-code"));o&&s.removeDiscount(o).catch(i=>{a(i,"discount")})}function wt(){document.addEventListener("submit",Bt,!0),document.addEventListener("input",jt),document.addEventListener("click",qt)}var M=t=>l("extras").then(e=>e.addGroup(t)),I=t=>{a(t,"extras")};function zt(t){let{target:e}=t,n=e instanceof window.Element?e.closest(r("group-add")):null;n&&(t.preventDefault(),f(n,()=>M(n)).catch(I))}function Kt(t){!c.domain||!t.key?.startsWith(`${c.prefix}:`)||l("extras").then(e=>{e.onStorage(t)}).catch(I)}function Qt(t){if(!g(t,"variant-changed"))return;let{target:e}=t;e instanceof window.Element&&(!c.variantUrl&&!e.hasAttribute(d("variant-url"))||l("extras").then(n=>{n.writeVariantUrl(e,t.detail)}).catch(I))}function At(){document.addEventListener("click",zt),window.addEventListener("storage",Kt),document.addEventListener(`${c.prefix}:variant-changed`,Qt)}var N=null;function bt(){N=document.body}async function Wt(t){await t.ready();let e=ct();if(!e){N!==document.body&&t.mount(document);return}try{await h(e.country,{language:e.language??null,locale:e.locale,remember:!1})}catch(n){a(n,"country")}t.mount(document)}function Yt(t){document.addEventListener("astro:page-load",()=>{Wt(t).catch(e=>{a(e,"page mount")})}),document.addEventListener("astro:before-swap",()=>{N=null,t.unmount()})}function Jt(t){let{target:e}=t;!(e instanceof window.HTMLSelectElement)||!e.matches(r("country-select"))||e.value&&h(e.value).catch(n=>{a(n,"country")})}function Xt(){it(),w.forEach(t=>{t.root.getAttribute(d("state"))==="error"&&t.load()})}function Lt(t){c.astro&&Yt(t),document.addEventListener("change",Jt),window.addEventListener("online",Xt)}var Ct="0.7.2",Zt=50;function te(){let t=P("TETHER_CONFIG");return typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t)):{}}var m=null,O=null,kt=null,Tt=!1;function ee(t){let e=0;return p(t,nt()).forEach(n=>{if(T.has(n))return;T.add(n),e++;let o=new ot(n);w.add(o),n.addEventListener(`${c.prefix}:list-rendered`,i=>{g(i,"list-rendered")&&b(i.detail.container)}),st(o.load())}),e}function ne(t){p(t,`${r("country-select")},${r("country-bind")}`).length&&l("markets").then(e=>e.renderCountrySelects(t)).catch(e=>{a(e,"markets")}),ft(t),p(t,r("search")).length&&l("search").then(e=>{e.mountSearch(t)}).catch(e=>{a(e,"search")})}function St(t){let e=ee(t);return p(t,r("product")).forEach(n=>{rt(n)&&e++}),ne(t),e}function b(t=document){if(!E())return 0;t===document&&bt(),C(),S(t.ownerDocument??document);let e=St(t);return k(),s.render(),L(`mounted ${e} scope(s)`,t),e}function oe(t){let e=t.filter(o=>o.isConnected&&!t.some(i=>i!==o&&i.contains(o)));if(!e.length||!E())return;C(),e.forEach(o=>{S(o)});let n=e.reduce((o,i)=>o+St(i),0);k(),s.render(),L(`mounted ${n} scope(s) in ${e.length} added element(s)`)}function xt(){s.close()}function re(t){let e=t?.closest(r("product"));return e?et.get(e)??null:null}function ie(){Tt||(Tt=!0,vt(),wt(),At(),Lt({ready:()=>m??Promise.resolve(null),mount:b,unmount:xt}))}function se(){let t=[];kt=t,U.forEach(e=>{document.addEventListener(`${c.prefix}:${e}`,n=>t.push(n))}),document.addEventListener("astro:page-load",e=>t.push(e)),l("analytics").then(e=>e.startAnalytics(t)).catch(e=>{a(e,"analytics")})}async function ae(t){let e=c.country,n=t?.buyerIdentity.countryCode;if(!t||!e||!n||n===e)return t;try{return await s.setBuyerIdentity({countryCode:e},{create:!1})}catch(o){return a(o,"cart country"),t}}function Mt(t={}){return m&&!Object.keys(t).length?m:(V({...te(),...t}),E()?(lt(),ie(),c.observe&&ce(),c.analytics&&!kt&&se(),m=at(t).then(()=>s.init()).then(ae).then(e=>(y("ready",{cart:e}),D)),m):(F("TETHER_CONFIG is missing domain or token. Tether is idle."),m=Promise.resolve(null),m))}function ce(){if(O||typeof MutationObserver>"u")return;let t,e=new Set;O=new MutationObserver(n=>{n.forEach(o=>{o.addedNodes.forEach(i=>{i instanceof window.Element&&e.add(i)})}),clearTimeout(t),t=setTimeout(()=>{let o=[...e];e.clear(),oe(o)},Zt)}),O.observe(document.body,{childList:!0,subtree:!0})}var ue=t=>l("markets").then(e=>e.detectMarket(t??c.markets)),le=()=>l("markets").then(t=>t.getLocalization()),de=t=>l("diagnose").then(e=>e.diagnose({...t,version:Ct}));function me(t,e){let n=`${c.prefix}:${t}`,o=i=>{g(i,t)&&e(i.detail,i)};return document.addEventListener(n,o),()=>{document.removeEventListener(n,o)}}var fe={VERSION:Ct,init:Mt,mount:b,unmount:xt,get config(){return $},get ready(){return m??Promise.resolve(null)},query:G,withContext:_,cart:s,getProduct:W,getProducts:J,getRecommendations:X,getScope:re,addGroup:M,account:pt,primeProduct:Q,normalizeProductKey:K,clearProductCache:Y,formatMoney:j,imageUrl:B,plans:q,TetherError:v,resolveProductKey:tt,setCountry:h,detectMarket:ue,getLocalization:le,diagnose:de,on:me},pe={__core:mt,__parts:{}},D=Object.assign(fe,pe),sn=D;function ge(){Reflect.set(window,"Tether",D);let t=P("TETHER_CONFIG");if(!t||H(t,"autoMount")===!1||P("TETHER_INTEGRATION"))return;let e=()=>{Mt().then(()=>b(document)).catch(n=>{a(n,"init")})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}typeof window<"u"&&typeof document<"u"&&ge();export{Ct as VERSION,M as addGroup,D as api,sn as default,re as getScope,Mt as init,b as mount,h as setCountry,xt as unmount};
|
package/dist/esm/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
${
|
|
1
|
+
import{b as j,f as Q,g as G}from"./chunks/chunk-AUVAN3KZ.js";import{A as B,B as J,C as K,a as D,c as T,h as O,i as v,j as b,l as M,o as F,q,s as V}from"./chunks/chunk-YC4JXWRG.js";import{B as _,a as h,c as w,d as S,f as nt,g as k,i as L,u as U}from"./chunks/chunk-CUL66KRA.js";import{B as E,E as N,F as C,G as I,q as g,t as A}from"./chunks/chunk-QDHLXXAZ.js";function H(t,e={}){if(!t)return null;let{variant:r,sellingPlan:a,defaultPurchase:c=g.defaultPurchase,lowStock:u=g.lowStock}=e,d=Q(t,{variant:r,sellingPlan:a,defaultPurchase:c}),n=G(t,{...d,quantity:1},u);if(!n)throw new h(`Product ${t.handle} has no variants`);let{selected:l,line:p}=n,i=(o,s)=>!j(t,l,o,s);return{variant:n.variant,selected:l,purchase:n.purchase.kind,plan:p.kind==="subscription"?n.plan:null,plans:O(t).map(o=>({id:o.id,name:o.name,price:b(n.variant,o.id),savings:M(n.variant,o.id).percentage,selected:p.kind==="subscription"&&o.id===p.planId,available:!!v(n.variant,o.id)})),savings:n.savings.percentage,price:n.price,compareAtPrice:n.compareAtPrice,available:n.variant.availableForSale,show:n.show,unavailable:Object.fromEntries(t.options.map(o=>[o.name,o.optionValues.map(s=>s.name).filter(s=>i(o.name,s))])),isUnavailable:i}}var rt=500,ot=100,it=100,at="query TetherServerProductById($id:ID!){node(id:$id){... on Product{...TetherProduct}}}",st="query TetherServerProduct($handle:String!){product(handle:$handle){...TetherProduct}}",lt=()=>`query TetherServerCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${T()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}`,ct="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}}}",ut=()=>`query TetherServerCollections($first:Int!,$after:String){collections(first:$first,after:$after){nodes{${T()}}pageInfo{hasNextPage endCursor}}}`,dt=t=>`query TetherServerRecs(${t?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${t?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}`,ft=S({product:w(q)}),pt=S({node:w(V)}),mt=S({collections:{nodes:[{handle:"string"}],pageInfo:{hasNextPage:"boolean"}}});async function gt(t){let e=[],r=null;for(let a=0;a<it;a++){let c=await k(t,ut(),{first:ot,after:r},mt);if(e.push(...c.collections.nodes),!c.collections.pageInfo.hasNextPage)break;r=c.collections.pageInfo.endCursor}return e}function Y(t,e){let r=(i,o,s)=>k(t,f=>`${i}
|
|
2
|
+
${D(t,f)}`,o,s);async function a(i){let o=I(i);if(!o)return null;if(o.startsWith("gid://")){let{node:f}=await r(at,{id:o},pt);return f?.id?f:null}return(await r(st,{handle:o},ft)).product}async function c(i,{first:o=e,after:s=null,sortKey:f,reverse:m=!1,filters:$}){let P=await r(lt(),{handle:i,first:o,after:s,sortKey:f||void 0,reverse:m,filters:$??void 0},B);if(!P.collection)return{collection:null,products:[],pageInfo:{hasNextPage:!1,endCursor:null}};let{products:y,...et}=P.collection;return{collection:et,products:y.nodes,pageInfo:y.pageInfo}}async function u(i={}){let{collection:o,query:s,first:f=e,after:m=null,sortKey:$,reverse:P=!1}=i;if(o)return c(o,i);let y=await r(ct,{first:f,after:m,query:s||void 0,sortKey:$||void 0,reverse:P},J);return{collection:null,products:y.products.nodes,pageInfo:y.products.pageInfo}}async function d(i={}){let o=[],s=null;for(let f=0;f<rt;f++){let m=await u({...i,first:e,after:s});if(o.push(...m.products),!m.pageInfo.hasNextPage)break;s=m.pageInfo.endCursor}return o}async function n(i,o={}){let s=await u({...o,collection:i});return s.collection?{...s.collection,products:s.products,pageInfo:s.pageInfo}:null}async function l(i,o="RELATED"){let s=I(typeof i=="object"?i?.id:i),f=s?.startsWith("gid://")??!1;return(await r(dt(f),f?{id:s,intent:o}:{handle:s,intent:o},K)).productRecommendations??[]}return{getProduct:a,getProducts:u,allProducts:d,getCollection:n,allCollections:()=>gt(t),getRecommendations:l}}var W={size:"https://schema.org/size",color:"https://schema.org/color",colour:"https://schema.org/color",material:"https://schema.org/material"},R=t=>JSON.stringify(t).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");function z(t){return JSON.parse(JSON.stringify(t))}var X=t=>t.split("/").pop()??t;function yt(t){return t.availableForSale?t.currentlyNotInStock?"https://schema.org/BackOrder":"https://schema.org/InStock":"https://schema.org/OutOfStock"}function Pt(t,e){if(!t.requiresSellingPlan)return e.price;let r=O(t).find(a=>v(e,a.id));return(r&&b(e,r.id))??e.price}function Z(t,e,r){let a=Pt(t,e),c=r?.includes("?")?"&":"?";return{"@type":"Offer",price:a.amount,priceCurrency:a.currencyCode,availability:yt(e),url:r?`${r}${c}variant=${X(e.id)}`:void 0}}function ht(t,e,r,a){let c=e.selectedOptions.flatMap(u=>{let d=W[u.name.toLowerCase()];return d?[[d.split("/").pop()??d,u.value]]:[]});return{"@type":"Product",name:`${t.title} - ${e.title}`,sku:e.sku||void 0,image:e.image?.url||a[0],...Object.fromEntries(c),offers:Z(t,e,r)}}function St(t,{url:e},r){if(e)return e;let a=C(r.productPath,t.handle,t.id);if(!(!r.siteUrl||!a))return new URL(a,r.siteUrl).toString()}function x(t,e,r){if(!t)return null;let a=St(t,e,r),c=t.images.nodes.map(i=>i.url).filter(Boolean),u=e.brand||t.vendor,d=u?{"@type":"Brand",name:u}:void 0,n=t.description.trim()||void 0,l=t.variants.nodes;if(l.length<=1){let[i]=l;return z({"@context":"https://schema.org","@type":"Product",name:t.title,description:n,url:a,image:c,sku:i?.sku||void 0,brand:d,offers:i?Z(t,i,a):void 0})}let p=t.options.map(i=>W[i.name.toLowerCase()]).filter(Boolean);return z({"@context":"https://schema.org","@type":"ProductGroup",name:t.title,description:n,url:a,productGroupID:X(t.id),image:c,brand:d,variesBy:[...new Set(p)],hasVariant:l.map(i=>ht(t,i,a,c))})}var Ct=25,It=2,Ot=1;function vt(t,{productPath:e=g.productPath,id:r}={}){return C(e,t,r)}function tt(t,e){for(let r of e){let a=t[r];if(typeof a=="string"&&a)return a}return""}function bt(t){let e={};for(let[u,d]of Object.entries(t))u in g&&(e[u]=d);let r=typeof t.domain=="string"&&t.domain?t.domain:"",a=typeof t.token=="string"&&t.token?t.token:"",c=A({...e,domain:r||tt(t,E.domain),token:a||tt(t,E.token)});return t.fetch&&(c.fetch=t.fetch),t.pageSize!==void 0&&(c.pageSize=t.pageSize),t.siteUrl!==void 0&&(c.siteUrl=t.siteUrl),c}var $t=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:Ct;function wt(t,e){return{...t,description:"",descriptionHtml:"",images:{nodes:t.images.nodes.slice(0,Math.max(1,e))},variants:{nodes:t.variants.nodes.map(r=>({...r,image:null}))}}}function Ht(t={}){let e=bt(t);if(!e.domain||!e.token)throw new h("createStorefront needs domain and token: pass them, or import.meta.env with PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN",{code:"NOT_CONFIGURED"});let r=Y(e,$t(e.pageSize)),a={productPath:e.productPath,siteUrl:e.siteUrl};function c(n,{card:l=!1,images:p=It}={}){let i=(Array.isArray(n)?n:[n]).filter(s=>s!=null),o={v:Ot,at:new Date().toISOString(),country:e.country||null,language:e.language||null,products:l?i.map(s=>wt(s,p)):i};return`<script type="application/json" data-tether-hydrate>${R(o)}<\/script>`}function u(n,l={}){return n?`<script type="application/ld+json">${R(x(n,l,a))}<\/script>`:""}function d(n,l={}){return H(n,{defaultPurchase:e.defaultPurchase,lowStock:e.lowStock,...l})}return{config:e,query:(n,l,p)=>L(e,n,l,p),...r,hydrate:c,formatMoney:(n,l=e.locale)=>N(n,l),formatPercent:(n,l=e.locale)=>_(n,l),imageUrl:U,jsonLd:u,jsonLdData:(n,l={})=>x(n,l,a),initialState:d,productUrl:(n,l={})=>vt(n,{productPath:e.productPath,...l}),plans:F}}export{h as TetherError,Ht as createStorefront,N as formatMoney,_ as formatPercent,U as imageUrl,H as initialState,F as plans,I as productKey,vt as productUrl,nt as withContext};
|
package/dist/tether.diagnose.js
CHANGED
|
@@ -70,9 +70,9 @@
|
|
|
70
70
|
let note = `supported until about ${supportedUntil.toISOString().slice(0, 7)}`;
|
|
71
71
|
if (!isReleased) note = "not released yet (release candidate at best)";
|
|
72
72
|
else if (monthsLeft <= 0) {
|
|
73
|
-
note = "no longer supported: Shopify falls back to the oldest supported version. Upgrade (see
|
|
73
|
+
note = "no longer supported: Shopify falls back to the oldest supported version. Upgrade (see docs/reference.md)";
|
|
74
74
|
} else if (monthsLeft < UPGRADE_WARNING_MONTHS) {
|
|
75
|
-
note = `${note}: plan the upgrade to ${nextApiVersion(version)} or later (see
|
|
75
|
+
note = `${note}: plan the upgrade to ${nextApiVersion(version)} or later (see docs/reference.md)`;
|
|
76
76
|
}
|
|
77
77
|
return {
|
|
78
78
|
version,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{var L=Object.defineProperty;var Y=(e,n)=>{for(var t in n)L(e,t,{get:n[t],enumerable:!0})};var P={};Y(P,{apiVersionStatus:()=>y,checkMarkup:()=>k,diagnose:()=>ke,didYouMean:()=>f});var G=window.Tether.__core["config.ts"],[a,
|
|
1
|
+
(()=>{var L=Object.defineProperty;var Y=(e,n)=>{for(var t in n)L(e,t,{get:n[t],enumerable:!0})};var P={};Y(P,{apiVersionStatus:()=>y,checkMarkup:()=>k,diagnose:()=>ke,didYouMean:()=>f});var G=window.Tether.__core["config.ts"],[a,E,$e,Re,Te,Ae,_e]=G;var B=window.Tether.__core["client.ts"],[$,R,Ne,T,xe]=B;var Q=window.Tether.__core["dom.ts"],[De,p,Oe,Ve,Ue,Ie,m,Ce,A,qe,He,Le,d,Ye,l,Ge,Be,Qe]=Q;var j=window.Tether.__core["loader.ts"],[Ke,_]=j;var K=window.Tether.__core["selling-plans.ts"],[v]=K;var W=window.Tether.__core["status.ts"],[N,h]=W;var F=/^(\d{4})-(01|04|07|10)$/;function M(e){let n=F.exec(typeof e=="string"?e:"");return n?{year:Number(n[1]),month:Number(n[2])}:null}var z=(e,n)=>`${e}-${String(n).padStart(2,"0")}`;function x(e,n=1){let t=M(e);if(!t)throw new Error(`not a quarterly Shopify API version: ${e}`);let r=t.year*4+(t.month-1)/3+n;return z(Math.floor(r/4),r%4*3+1)}function y(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 t=M(e);if(!t)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let r=new Date(Date.UTC(t.year,t.month-1,1)),s=new Date(Date.UTC(t.year,t.month-1+12,1)),o=(s.getTime()-n.getTime())/2630016e3,i=r<=n,c=`supported until about ${s.toISOString().slice(0,7)}`;return i?o<=0?c="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see docs/reference.md)":o<3&&(c=`${c}: plan the upgrade to ${x(e)} or later (see docs/reference.md)`):c="not released yet (release candidate at best)",{version:e,ok:i&&o>0,monthsLeft:Math.round(o),next:x(e),note:c}}var J=window.Tether.__core["lazy.ts"],[D]=J;var O=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","addresses-loading","addresses-empty","addresses-error","subscriptions-loading","subscriptions-empty","subscriptions-error"]),V=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
2
|
always-enabled bind cart-checkout-charge cart-clear cart-close cart-count cart-discounts cart-drawer cart-label cart-lines
|
|
3
3
|
cart-note cart-open cart-subtotal cart-total cart-warning checkout code collection collection-bind countries country
|
|
4
4
|
country-bind country-label country-select default-plan default-purchase discount discount-code discount-form discount-input
|
|
@@ -11,4 +11,4 @@
|
|
|
11
11
|
plan-value product products purchase purchase-mode qty qty-minus qty-plus quantity recommendations reverse search
|
|
12
12
|
search-bind search-collections search-input search-limit search-min search-products search-queries search-results
|
|
13
13
|
search-state show soldout-text sort state subscribe-text variant variant-select variant-url max-width max-height crop
|
|
14
|
-
sig label hydrated busy`.split(/\s+/).filter(Boolean)),X=["bind","option-list","option","variant-select","add-to-cart","purchase","plan-list","plan","qty","line-attribute"],Z=["option-list","plan-list","cart-lines","list"],w="metafield:",ee=/^image:\d+$/,te=2;function ne(e,n){let t=Array.from({length:n.length+1},(r,s)=>s);for(let r=1;r<=e.length;r++){let s=[r];for(let o=1;o<=n.length;o++){let i=(t[o-1]??0)+(e[r-1]===n[o-1]?0:1);s.push(Math.min((t[o]??0)+1,(s[o-1]??0)+1,i))}t=s}return t[n.length]??0}function f(e,n,t=""){let r=null,s=1/0;for(let i of n){let c=ne(e,i);c<s&&(s=c,r=i)}let o=Math.max(2,Math.floor(e.length/4));return r!==null&&s<=o?` Did you mean "${t}${r}"?`:""}function re(e){let n=e.id?`#${e.id}`:"",t=e.className&&typeof e.className=="string"?e.className.trim().split(/\s+/):[],r=t.length?`.${t.slice(0,te).join(".")}`:"";return`<${e.tagName.toLowerCase()}${n}${r}>`}var I=()=>`${l("collection")},${l("products")},${l("recommendations")}`;function oe(e,n){d(e,l("product")).forEach(t=>{if(t.closest(I())&&t.closest(l("list")))return;let{key:r,fromUrl:s,raw:o}=h(t);o?s&&!r&&n("warn",`${p("product")}="${o}" but this URL has no value for it (e.g. ?handle=my-product).`,t):n("error",`${p("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`,t)})}function se(e,n){for(let t of X)d(e,l(t)).forEach(r=>{r.closest(l("product"))||t==="line-attribute"&&r.closest(l("group"))||n("warn",`${p(t)} outside any ${p("product")}: it does nothing here.`,r)});d(e,l("group-add")).forEach(t=>{t.closest(l("group"))||n("warn",`${p("group-add")} outside a ${p("group")}.`,t)});for(let t of Z)d(e,l(t)).forEach(r=>{!r.firstElementChild&&!
|
|
14
|
+
sig label hydrated busy`.split(/\s+/).filter(Boolean)),X=["bind","option-list","option","variant-select","add-to-cart","purchase","plan-list","plan","qty","line-attribute"],Z=["option-list","plan-list","cart-lines","list"],w="metafield:",ee=/^image:\d+$/,te=2;function ne(e,n){let t=Array.from({length:n.length+1},(r,s)=>s);for(let r=1;r<=e.length;r++){let s=[r];for(let o=1;o<=n.length;o++){let i=(t[o-1]??0)+(e[r-1]===n[o-1]?0:1);s.push(Math.min((t[o]??0)+1,(s[o-1]??0)+1,i))}t=s}return t[n.length]??0}function f(e,n,t=""){let r=null,s=1/0;for(let i of n){let c=ne(e,i);c<s&&(s=c,r=i)}let o=Math.max(2,Math.floor(e.length/4));return r!==null&&s<=o?` Did you mean "${t}${r}"?`:""}function re(e){let n=e.id?`#${e.id}`:"",t=e.className&&typeof e.className=="string"?e.className.trim().split(/\s+/):[],r=t.length?`.${t.slice(0,te).join(".")}`:"";return`<${e.tagName.toLowerCase()}${n}${r}>`}var I=()=>`${l("collection")},${l("products")},${l("recommendations")}`;function oe(e,n){d(e,l("product")).forEach(t=>{if(t.closest(I())&&t.closest(l("list")))return;let{key:r,fromUrl:s,raw:o}=h(t);o?s&&!r&&n("warn",`${p("product")}="${o}" but this URL has no value for it (e.g. ?handle=my-product).`,t):n("error",`${p("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`,t)})}function se(e,n){for(let t of X)d(e,l(t)).forEach(r=>{r.closest(l("product"))||t==="line-attribute"&&r.closest(l("group"))||n("warn",`${p(t)} outside any ${p("product")}: it does nothing here.`,r)});d(e,l("group-add")).forEach(t=>{t.closest(l("group"))||n("warn",`${p("group-add")} outside a ${p("group")}.`,t)});for(let t of Z)d(e,l(t)).forEach(r=>{!r.firstElementChild&&!A(r)&&n("warn",`${p(t)} without a template child: put one example element inside it.`,r)});d(e,I()).forEach(t=>{d(t,l("list")).length||n("error",`List without a ${p("list")} child: products have nowhere to render.`,t)})}function ie(e,n){d(e,l("show")).forEach(t=>{let r=m(t,"show")??"";O.has(r)||n("warn",`Unknown ${p("show")}="${r}".${f(r,O)}`,t)}),d(e,l("bind")).forEach(t=>{let r=m(t,"bind")||"";!r||V.has(r)||ee.test(r)||r.startsWith(w)||n("warn",`Unknown ${p("bind")}="${r}": it stays empty.${f(r,V)}`,t)})}function ae(e,n){d(e,l("bind")).forEach(t=>{let r=m(t,"bind")||"";if(!r.startsWith(w))return;let s=r.slice(w.length);a.metafields.some(i=>(typeof i=="string"?i:`${i.namespace}.${i.key}`)===s)||n("error",`${p("bind")}="${r}" but "${s}" is not in config.metafields, so it stays empty.`,t)})}function ce(e,n){let t=`${a.prefix}-`,r=new Set;d(e,"*").forEach(s=>{for(let{name:o}of s.attributes){if(!o.startsWith(t))continue;let i=o.slice(t.length);U.has(i)||r.has(i)||(r.add(i),n("warn",`Unknown attribute ${o}: Tether ignores it.${f(i,U,t)}`,s))}})}function le(e,n){let t=d(e,l("cart-drawer")).length;d(e,l("cart-open")).length&&!t&&n("warn",`${p("cart-open")} exists but there is no ${p("cart-drawer")} on this page.`),t>1&&n("warn",`More than one ${p("cart-drawer")}.`),d(e,`[${p("state")}="error"]`).forEach(r=>{r.matches(N())&&n("error",`Scope failed to load (${m(r,"error")||"error"}).`,r)})}function k(e=document){let n=[],t=(r,s,o)=>{n.push(o?{level:r,message:s,element:re(o),el:o}:{level:r,message:s})};return oe(e,t),se(e,t),ie(e,t),ce(e,t),ae(e,t),le(e,t),n}var ue=20,de=3,C=4;function pe(e){return e?`${e.slice(0,C)}\u2026${e.slice(-C)} (${e.length} chars)`:"(missing)"}function q(e,n){if(e instanceof Error&&e.message)return e.message;let t=typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0;return typeof t=="string"&&t?t:n}function me(){return{domain:a.domain||"(missing)",token:pe(a.token),apiVersion:a.apiVersion,endpoint:a.domain?$():null,country:a.country,language:a.language,locale:a.locale,markets:a.markets,prefix:a.prefix,productPath:a.productPath,metafields:a.metafields,autoMount:a.autoMount,observe:a.observe,onError:typeof a.onError=="function"}}async function fe(){return{country:a.country||null,language:a.language||null,locale:a.locale||null,detected:a.markets?.detect?(await D("markets")).detectMarket(a.markets):null}}function ge({ok:e,monthsLeft:n,note:t}){return e&&(n===void 0||n>=de)?null:{level:e?"warn":"error",message:`apiVersion ${a.apiVersion}: ${t}`}}var he=T({shop:{name:"string",primaryDomain:{url:"string"},paymentSettings:{currencyCode:"string"}}});async function be(){if(!E())return{kind:"not-configured"};let e=Date.now();try{let n=await R("query TetherDiagnose { shop { name primaryDomain { url } paymentSettings { currencyCode } } }",{},he,{context:!1});return{kind:"reachable",shop:{name:n.shop.name,url:n.shop.primaryDomain.url,currency:n.shop.paymentSettings.currencyCode},latencyMs:Date.now()-e}}catch(n){return{kind:"unreachable",error:n,latencyMs:Date.now()-e}}}function ye(e,n,t){let r=[],s=t.options.map(i=>i.name),o=d(e,l("product")).filter(i=>h(i).key===n&&i.querySelector(l("add-to-cart")));for(let i of o){let c=new Set(d(i,`${l("option-list")},select${l("option")}`).map(u=>m(u,"option-list")||m(u,"option")));if(!(!c.size&&d(i,`select${l("variant-select")}`).length)){if(!a.language)for(let u of c)!u||s.includes(u)||r.push({level:"warn",message:`Product "${t.handle}" has no option "${u}" (its options: ${s.join(", ")||"none"}).${f(u,s)}`});for(let u of t.options)u.optionValues.length<=1||c.has(u.name)||r.push({level:"warn",message:`Product "${t.handle}": option "${u.name}" (${u.optionValues.length} values) has no tether-option-list, so visitors can't choose it.`})}}return r}async function we(e,n){let t=d(e,l("product")).map(o=>h(o).key),r=[...new Set(t.filter(o=>o!==null&&o!==""))].slice(0,ue);(await Promise.allSettled(r.map(o=>_(o)))).forEach((o,i)=>{let c=r[i]??"";if(o.status==="rejected"){let g=q(o.reason,"not loaded");n.products.push({key:c,error:o.reason instanceof Error?o.reason.message:void 0}),n.problems.push({level:"error",message:`Product "${c}": ${g}. Is it published to the Headless channel?`});return}let u=o.value,S=v(u);n.products.push({key:c,handle:u.handle,title:u.title,plans:S.length,requiresSellingPlan:u.requiresSellingPlan});for(let g of S)n.sellingPlans.push({product:u.handle,group:g.group.name,plan:g.name,id:g.id});n.problems.push(...ye(e,c,u))})}async function ke({root:e=document,silent:n=!1,version:t="",now:r=new Date}={}){let s=await be(),o={version:t,config:me(),apiVersion:y(a.apiVersion,r),market:await fe(),reachable:s.kind==="reachable",shop:s.kind==="reachable"?s.shop:null,latencyMs:s.kind==="not-configured"?null:s.latencyMs,products:[],sellingPlans:[],problems:[]};switch(s.kind){case"not-configured":o.problems.push({level:"error",message:"TETHER_CONFIG needs domain and token."});break;case"unreachable":o.problems.push({level:"error",message:`Storefront API not reachable: ${q(s.error,"unknown error")}`});break;case"reachable":await we(e,o);break}let i=ge(o.apiVersion);return i&&o.problems.push(i),typeof document<"u"&&o.problems.push(...k(e)),n||Pe(o),o}function Pe(e){let n=e.problems.filter(c=>c.level==="error").length,t=e.problems.length-n;console.group(`[${a.prefix}] diagnose: ${n?`${n} error(s)`:"no errors"}, ${t} warning(s)`),console.log("version",e.version,"| API",e.apiVersion.version,`(${e.apiVersion.note})`),console.log("config",e.config);let{country:r,language:s,detected:o}=e.market,i=[r,s].filter(Boolean).join(" / ")||"the store default";console.log("market",`in use: ${i}`,o?`(detection picks ${JSON.stringify(o)})`:""),console.log(e.shop?`Storefront API reachable: ${e.shop.name} (${e.latencyMs??0} ms)`:"Storefront API NOT reachable"),e.products.length&&console.table(e.products),e.sellingPlans.length?console.table(e.sellingPlans):e.reachable&&console.log("No selling plans on the products of this page.");for(let c of e.problems)c.level==="error"?console.error(c.message,c.el??""):console.warn(c.message,c.el??"");console.groupEnd()}function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return b(e)&&b(e.__core)&&b(e.__parts)}function H(e,n){let t=Reflect.get(window,"Tether");if(!Se(t))throw new Error(`tether.${e}.js runs after the Tether script, which loads it, and needs its window.Tether`);t.__parts[e]=n}H("diagnose",P);})();
|
package/dist/tether.extras.js
CHANGED
|
@@ -33,10 +33,32 @@
|
|
|
33
33
|
var m5 = window.Tether.__core["page-market.ts"];
|
|
34
34
|
var [setCountry] = m5;
|
|
35
35
|
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
// tether-core:market-codes.ts
|
|
37
|
+
var m6 = window.Tether.__core["market-codes.ts"];
|
|
38
|
+
var [toCountry, toLanguage] = m6;
|
|
39
|
+
|
|
40
|
+
// src/markets.ts
|
|
41
|
+
var storageKey = () => `${cfg.prefix}:market:${cfg.domain}`;
|
|
42
|
+
function parseJsonOrNull(text) {
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(text);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof SyntaxError) return null;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function toMarket(value) {
|
|
51
|
+
if (typeof value !== "object" || value === null) return null;
|
|
52
|
+
const country = toCountry(Reflect.get(value, "country"));
|
|
53
|
+
if (!country) return null;
|
|
54
|
+
const locale = Reflect.get(value, "locale");
|
|
55
|
+
return {
|
|
56
|
+
country,
|
|
57
|
+
language: toLanguage(Reflect.get(value, "language")) ?? void 0,
|
|
58
|
+
locale: typeof locale === "string" && locale ? locale : void 0
|
|
59
|
+
};
|
|
39
60
|
}
|
|
61
|
+
var parseSavedMarket = (text) => toMarket(parseJsonOrNull(text));
|
|
40
62
|
|
|
41
63
|
// src/extras.ts
|
|
42
64
|
function groupAttributes(group, name) {
|
|
@@ -67,22 +89,6 @@
|
|
|
67
89
|
return null;
|
|
68
90
|
}
|
|
69
91
|
}
|
|
70
|
-
function parseStoredMarket(text) {
|
|
71
|
-
let value;
|
|
72
|
-
try {
|
|
73
|
-
value = JSON.parse(text);
|
|
74
|
-
} catch {
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
if (!isRecord(value)) return null;
|
|
78
|
-
const { country, language, locale } = value;
|
|
79
|
-
if (typeof country !== "string" || !country) return null;
|
|
80
|
-
return {
|
|
81
|
-
country,
|
|
82
|
-
language: typeof language === "string" ? language : null,
|
|
83
|
-
locale: typeof locale === "string" ? locale : void 0
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
92
|
function onStorage(event) {
|
|
87
93
|
if (event.key === cfg.storageKey || event.key === `${cfg.storageKey}:seen`) {
|
|
88
94
|
Cart.init().catch((error) => {
|
|
@@ -90,10 +96,10 @@
|
|
|
90
96
|
});
|
|
91
97
|
return;
|
|
92
98
|
}
|
|
93
|
-
if (event.key !==
|
|
94
|
-
const market =
|
|
99
|
+
if (event.key !== storageKey() || !event.newValue) return;
|
|
100
|
+
const market = parseSavedMarket(event.newValue);
|
|
95
101
|
if (!market) return;
|
|
96
|
-
const options = { language: market.language, locale: market.locale, remember: false };
|
|
102
|
+
const options = { language: market.language ?? null, locale: market.locale, remember: false };
|
|
97
103
|
setCountry(market.country, options).catch((error) => {
|
|
98
104
|
reportError(error, "market from another tab");
|
|
99
105
|
});
|
|
@@ -120,6 +126,11 @@
|
|
|
120
126
|
replaceUrlIfAllowed(url);
|
|
121
127
|
}
|
|
122
128
|
|
|
129
|
+
// server/src/shared/json.ts
|
|
130
|
+
function isRecord(value) {
|
|
131
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
132
|
+
}
|
|
133
|
+
|
|
123
134
|
// src/part-registry.ts
|
|
124
135
|
function isTetherInternals(value) {
|
|
125
136
|
return isRecord(value) && isRecord(value["__core"]) && isRecord(value["__parts"]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var N=Object.defineProperty;var
|
|
1
|
+
(()=>{var N=Object.defineProperty;var R=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})};var f={};R(f,{addGroup:()=>q,onStorage:()=>j,writeVariantUrl:()=>V});var O=window.Tether.__core["config.ts"],[c,Y,Z,P,I,i,p]=O;var v=window.Tether.__core["dom.ts"],[Q,X,m,y,ee,te,k,w,ne,re,h,oe,S,ae,s,ce,ue,ie]=v;var U=window.Tether.__core["product.ts"],[C]=U;var K=window.Tether.__core["cart.ts"],[d]=K;var F=window.Tether.__core["page-market.ts"],[M]=F;var H=window.Tether.__core["market-codes.ts"],[x,b]=H;var E=()=>`${c.prefix}:market:${c.domain}`;function $(e){try{return JSON.parse(e)}catch(t){if(t instanceof SyntaxError)return null;throw t}}function D(e){if(typeof e!="object"||e===null)return null;let t=x(Reflect.get(e,"country"));if(!t)return null;let n=Reflect.get(e,"locale");return{country:t,language:b(Reflect.get(e,"language"))??void 0,locale:typeof n=="string"&&n?n:void 0}}var T=e=>D($(e));function J(e,t){let n=m(h(e,"line-attributes"));return t?[{key:"_group",value:t},...n]:n}async function q(e){let t=e.closest(s("group"));if(!t)return null;let n=k(t,"group"),r=J(t,n),u=S(t,s("product")).flatMap(a=>{let o=C.get(a);if(!o?.variant?.availableForSale||o.quantity<=0)return[];let g=o.getLine();return g?[{...g,attributes:[...g.attributes??[],...r]}]:[]});if(!u.length)return p("group-add: nothing selected"),null;try{let a=await d.add(u);return y("group-added",{group:n,lines:u},t),a}catch(a){return i(a,"group add"),null}}function j(e){if(e.key===c.storageKey||e.key===`${c.storageKey}:seen`){d.init().catch(r=>{i(r,"cart from another tab")});return}if(e.key!==E()||!e.newValue)return;let t=T(e.newValue);if(!t)return;let n={language:t.language??null,locale:t.locale,remember:!1};M(t.country,n).catch(r=>{i(r,"market from another tab")})}var _=new WeakMap,L=e=>e.split("/").pop()??e;function z(e){try{window.history.replaceState(window.history.state,"",e)}catch{}}function V(e,{variant:t,sellingPlanId:n}){let r=`${t.id}|${n??""}`,u=_.get(e);if(_.set(e,r),!u||u===r)return;let a=c.variantUrl&&document.querySelector(s("product"))===e;if(!w(e,"variant-url")&&!a)return;let o=new URL(window.location.href);o.searchParams.set("variant",L(t.id)),n?o.searchParams.set("selling_plan",L(n)):o.searchParams.delete("selling_plan"),z(o)}function l(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W(e){return l(e)&&l(e.__core)&&l(e.__parts)}function A(e,t){let n=Reflect.get(window,"Tether");if(!W(n))throw new Error(`tether.${e}.js runs after the Tether script, which loads it, and needs its window.Tether`);n.__parts[e]=t}A("extras",f);})();
|