@occluze/tether 0.6.3 → 0.6.5
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 +3 -3
- package/dist/esm/chunks/account-QUBHQG3C.js +1 -0
- package/dist/esm/chunks/account-pages-VWDHF6WA.js +1 -0
- package/dist/esm/chunks/chunk-VPVJPNB4.js +1 -0
- package/dist/esm/chunks/{diagnose-4JHU6RTC.js → diagnose-VXQBSD3A.js} +6 -3
- package/dist/esm/index.js +1 -1
- package/dist/tether.account-pages.js +579 -0
- package/dist/tether.account-pages.min.js +1 -0
- package/dist/tether.account.js +64 -15
- package/dist/tether.account.min.js +1 -1
- package/dist/tether.diagnose.js +9 -2
- package/dist/tether.diagnose.min.js +6 -3
- package/dist/tether.js +3 -5
- package/dist/tether.min.js +2 -2
- package/dist/tether.min.js.map +3 -3
- package/package.json +1 -1
- package/src/account-pages.js +305 -0
- package/src/account.js +56 -12
- package/src/diagnose.js +5 -1
- package/src/index.js +2 -5
- package/src/lazy-iife.js +3 -0
- package/src/lazy.js +1 -0
- package/src/parts/account-pages.js +3 -0
- package/types/index.d.ts +27 -1
- package/dist/esm/chunks/account-NVHPA7AX.js +0 -1
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ MIT licensed · 20 KB gzipped · no dependencies · TypeScript types · [full re
|
|
|
33
33
|
| **npm** | Astro, Vite or another bundler or framework | `npm install @occluze/tether` ([Astro guide](docs/astro.md), [other frameworks](docs/frameworks.md)) |
|
|
34
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
35
|
|
|
36
|
-
The script tag pinned to one release: `…/tether@v0.6.
|
|
36
|
+
The script tag pinned to one release: `…/tether@v0.6.5/dist/tether.min.js`. Its optional parts
|
|
37
37
|
(search, accounts, markets, analytics) load from the same folder when a page uses them; host the
|
|
38
38
|
files yourself and set `partsUrl` if they live somewhere else. Customer accounts without the Worker
|
|
39
39
|
run in browser mode; [server mode](docs/accounts.md#server-mode) (recommended for live shops)
|
|
@@ -64,9 +64,9 @@ Site settings → Custom code → **Head**:
|
|
|
64
64
|
<script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.6/dist/tether.min.js" defer></script>
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
-
**Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.
|
|
67
|
+
**Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.5` pins one release,
|
|
68
68
|
`@latest` always takes the newest. Hosting the file yourself? Put the optional parts next to it (`tether.markets.min.js`,
|
|
69
|
-
`tether.search.min.js`, `tether.account.min.js`, `tether.analytics.min.js`, `tether.extras.min.js`,
|
|
69
|
+
`tether.search.min.js`, `tether.account.min.js`, `tether.account-pages.min.js`, `tether.analytics.min.js`, `tether.extras.min.js`,
|
|
70
70
|
`tether.diagnose.min.js`): each loads only when a page uses it.
|
|
71
71
|
|
|
72
72
|
## 3. Add attributes in the Designer
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Q}from"./chunk-VPVJPNB4.js";import{b as h}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{A as R,B as $,D as x,G as q,b as a,e as X,g as A,h as p,o as f,p as k,s as y,u as T,w as Y}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var N=()=>`${a.prefix}:account:${a.domain}`,J=()=>`${a.prefix}:account-login:${a.domain}`,O=()=>a.account?.remember?window.localStorage:window.sessionStorage,et=t=>btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),j=()=>et(crypto.getRandomValues(new Uint8Array(32))),ut=async t=>et(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),E=t=>(a.account?.navigate||(e=>window.location.assign(e)))(t),M=(t,e)=>{try{return JSON.parse(t.getItem(e)||"null")}catch{return null}},D=(t,e,n)=>{try{n?t.setItem(e,JSON.stringify(n)):t.removeItem(e)}catch{}},v=null,c=null,B=null,I=null,w=()=>a.account?.server?new URL(String(a.account.server),window.location.href).href.replace(/\/$/,""):"",z=()=>`${a.prefix}:account-hint:${a.domain}`,b=null;async function U(t,{method:e="GET",body:n}={}){let o=await fetch(`${w()}${t}`,{method:e,credentials:"include",headers:e==="POST"?{"Content-Type":"application/json","X-Tether-Account":"1"}:{},body:n?JSON.stringify(n):void 0}),r=await o.json().catch(()=>({}));if(!o.ok&&o.status!==401)throw new p(`Customer accounts: ${r.error||o.status}`,{status:o.status,userErrors:r.userErrors});return r}async function H(){b||(b=await U("/me"));try{b.loggedIn?window.localStorage.setItem(z(),"1"):window.localStorage.removeItem(z())}catch{}return b}async function P(){if(v)return v;let t=a.account?.shopDomain||a.domain,e=r=>fetch(`https://${t}/.well-known/${r}`).then(s=>{if(!s.ok)throw new p(`Customer accounts: ${r} answered ${s.status}`,{status:s.status});return s.json()}),[n,o]=await Promise.all([e("openid-configuration"),e("customer-account-api")]);return v={...n,graphql:o.graphql_api},v}var lt=()=>a.account?.callbackUrl||`${window.location.origin}${window.location.pathname}`;function nt(){return w()?!!b?.loggedIn:!!(c?.refresh||c?.access&&c.expiresAt>Date.now())}async function dt({returnTo:t=window.location.href,locale:e}={}){if(w()){let d=new URL(`${w()}/login`);d.searchParams.set("returnTo",t);let g=e||a.account.locale||(a.locale||"").split("-")[0];g&&d.searchParams.set("locale",g),a.country&&d.searchParams.set("country",String(a.country).toUpperCase()),E(d.toString());return}if(!a.account?.clientId)throw new p("Customer accounts: set account.clientId",{code:"NOT_CONFIGURED"});let n=await P(),o=j(),r=j(),s=j(),i=lt();D(window.sessionStorage,J(),{state:o,nonce:r,verifier:s,redirect:i,returnTo:t,at:Date.now()});let u=new URL(n.authorization_endpoint),m={client_id:a.account.clientId,scope:"openid email customer-account-api:full",response_type:"code",redirect_uri:i,state:o,nonce:r,code_challenge:await ut(s),code_challenge_method:"S256"},l=e||a.account.locale||(a.locale||"").split("-")[0];l&&(m.locale=l),a.country&&(m.region_country=String(a.country).toUpperCase()),Object.entries(m).forEach(([d,g])=>u.searchParams.set(d,g)),E(u.toString())}async function ot(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 p(`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 ft(t){try{return JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function rt(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},D(O(),N(),c)}async function ht(){let t=new URLSearchParams(window.location.search),e=M(window.sessionStorage,J());if(!e||!t.has("code")&&!t.has("error")||t.get("state")!==e.state)return!1;D(window.sessionStorage,J(),null);let n=new URL(window.location.href);if(["code","state","iss","error","error_description"].forEach(m=>n.searchParams.delete(m)),window.history.replaceState(window.history.state,"",n),t.has("error"))return T("account-error",{error:t.get("error")}),!1;if(Date.now()-e.at>10*6e4)throw new p("Customer accounts: the login took too long, please try again");let o=await ot({grant_type:"authorization_code",client_id:a.account.clientId,redirect_uri:e.redirect,code:t.get("code"),code_verifier:e.verifier}),r=await P(),s=ft(o.id_token||""),i=[].concat(s?.aud||[]);if(!s||s.nonce!==e.nonce||s.iss!==r.issuer||!i.includes(a.account.clientId)||s.exp*1e3<Date.now())throw new p("Customer accounts: the login answer did not check out (nonce/issuer/audience)");rt(o,null),await st(),T("account-login",{});let u=e.returnTo&&new URL(e.returnTo,window.location.href);return u&&u.origin===window.location.origin&&u.href!==n.href&&E(u.href),!0}async function C(){return w()||(c||(c=M(O(),N())),!c)?null:c.access&&c.expiresAt>Date.now()?c.access:c.refresh?(B||(B=(async()=>{try{rt(await ot({grant_type:"refresh_token",client_id:a.account.clientId,refresh_token:c.refresh})),await st()}catch(t){if(t.code==="SESSION_ENDED")F();else throw t}finally{B=null}})()),await B,c?.access||null):(F(),null)}function F(){c=null,I=null,D(O(),N(),null),h.customerAccessToken=null}async function st(){h.customerAccessToken=c?.access||null,h.id()&&c?.access&&await h.setBuyerIdentity({customerAccessToken:c.access},{create:!1}).catch(t=>A(t,"account cart"))}async function V(t,e={}){if(w())throw new p("Customer accounts in server mode only answer customer() and orders()",{code:"NOT_ALLOWED"});let n=await C();if(!n)throw new p("Not logged in",{code:"NOT_LOGGED_IN"});let o=await P(),r=u=>fetch(o.graphql,{method:"POST",headers:{"Content-Type":"application/json",Authorization:u},body:JSON.stringify({query:t,variables:e})}),s=await r(n);s.status===401&&c?.refresh&&(c.expiresAt=0,s=await r(await C()));let i=await s.json().catch(()=>({}));if(!s.ok||i.errors?.length)throw new p(i.errors?.map(u=>u.message).join(" | ")||`Customer accounts: ${s.status}`,{status:s.status});return i.data}async function at(){if(w()){let e=await H();return e.loggedIn?{...e.customer,emailAddress:{emailAddress:e.customer.email},defaultAddress:{formatted:e.customer.address}}:null}return I||(I=(await V("query TetherCustomer{customer{id firstName lastName displayName emailAddress{emailAddress}defaultAddress{formatted}}}")).customer,I)}async function mt({first:t=10}={}){return w()?(await U(`/orders?first=${t}`)).orders||[]:(await V("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 wt({returnTo:t=a.account?.logoutUrl||`${window.location.origin}/`}={}){if(w()){let r=await U("/logout",{method:"POST",body:{returnTo:t,cartId:h.id()}});b={loggedIn:!1};try{window.localStorage.removeItem(z())}catch{}T("account-logout",{}),r.logoutUrl?E(r.logoutUrl):K(document);return}let e=c?.idToken||M(O(),N())?.idToken;if(h.id()&&await h.setBuyerIdentity({customerAccessToken:null},{create:!1}).catch(()=>{}),F(),T("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),E(o.toString())}var gt=t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},pt=t=>{try{return new Date(t).toLocaleDateString(a.locale||void 0)}catch{return t}};async function K(t=document){let e=w()?!!(await H().catch(()=>({loggedIn:!1}))).loggedIn:nt()||!!await C().catch(()=>null);if(y(t,f("show")).forEach(r=>{let s=k(r,"show");s==="logged-in"&&x(r,e),s==="logged-out"&&x(r,!e)}),y(t,f("account-link")).forEach(r=>{let s=k(r,"account-link"),i=s==="payment"&&(a.account?.paymentUrl||a.account?.subscriptionsUrl)||s==="subscriptions"&&a.account?.subscriptionsUrl;r.setAttribute("href",i||`https://${a.domain}/account`)}),!e)return;let n=y(t,f("account-bind"));if(n.length){let r=await at().catch(s=>(A(s,"account"),null));n.forEach(s=>{let i={"first-name":r?.firstName,"last-name":r?.lastName,name:r?.displayName,email:r?.emailAddress?.emailAddress,address:r?.defaultAddress?.formatted?.join(", ")}[k(s,"account-bind")];i!=null&&$(s,i)})}let o=y(t,f("orders"));if(o.length){let r=(u,m)=>y(t,f("show")).forEach(l=>{let d=k(l,"show");d==="orders-loading"&&x(l,u),d==="orders-empty"&&x(l,m)});r(!0,!1);let s=!1,i=await mt({first:parseInt(k(o[0],"limit")||"10",10)}).catch(u=>(A(u,"orders"),s=!0,[]));r(!1,!s&&i.length===0),o.forEach(u=>q(u,i,(m,l)=>{let d=l.lineItems?.nodes||[];y(m,f("order-bind")).forEach(g=>{let L=k(g,"order-bind");if(L==="url"){let S=G(l);S&&g.setAttribute("href",S);return}if(L==="image"){let S=d.find(it=>it.image)?.image;S&&R(g,S.url,S.altText||d[0]?.title||"");return}let W={name:l.name,date:pt(l.processedAt),total:Y(l.totalPrice),status:l.financialStatus?.toLowerCase(),fulfillment:l.fulfillmentStatus?.toLowerCase(),items:d.map(S=>`${S.quantity}\xD7 ${S.title}`).join(", ")}[L];W!=null&&$(g,W)}),y(m,f("order-lines")).forEach(g=>St(g,d)),k(m,"order-bind")==="url"&&G(l)&&m.setAttribute("href",G(l))}))}kt.some(r=>y(t,f(r)).length)&&await(await ct()).renderPages(t)}var yt=t=>String(t||"").split("/").pop().split("?")[0];function G(t){let e=a.account?.orderUrl;return e?String(e).replace("{id}",encodeURIComponent(yt(t.id))):gt(t.statusPageUrl)?t.statusPageUrl:null}function St(t,e){q(t,e,(n,o)=>{y(n,f("order-line")).concat(n.matches(f("order-line"))?[n]:[]).forEach(r=>{let s=k(r,"order-line");if(s==="image"){o.image&&R(r,o.image.url,o.image.altText||o.title);return}let i={title:o.title,"variant-title":o.variantTitle||"",quantity:String(o.quantity)}[s];i!=null&&$(r,i)})})}var kt=["order","addresses","subscriptions","profile-form","address-form"],Z=null;function ct(){return Z||(Z=Q("account-pages").then(t=>(t.setup({server:w,serverFetch:U,query:V,customer:at,reset:()=>{I=null,b=null}}),t))),Z}var _=t=>(...e)=>ct().then(n=>n[t](...e)),Et=_("order"),Ut=_("updateProfile"),Pt=_("addresses"),$t=_("saveAddress"),vt=_("deleteAddress"),Ct=_("subscriptions"),Nt=_("subscriptionAction"),Ot=_("requestReturn"),tt=!1;async function Dt(t=document){if(!tt){if(tt=!0,document.addEventListener("click",e=>{let n=e.target;n.closest?.(f("account-login"))?(e.preventDefault(),dt().catch(o=>A(o,"login"))):n.closest?.(f("account-logout"))&&(e.preventDefault(),wt().catch(o=>A(o,"logout")))}),w()){let e=new URL(window.location.href);e.searchParams.get("account")&&(e.searchParams.delete("account"),window.history.replaceState(window.history.state,"",e),T("account-login",{})),h.beforeCheckout=async()=>{if(!(await H()).loggedIn||!h.id())return null;let n=await U("/cart",{method:"POST",body:{cartId:h.id()}}).catch(()=>null);return n?.checkoutUrl?`${n.checkoutUrl}${n.checkoutUrl.includes("?")?"&":"?"}logged_in=true`:null}}else{try{await ht()}catch(e){A(e,"login")}!h.customerAccessToken&&await C().catch(()=>null)&&(h.customerAccessToken=c.access)}X("account",nt()?"logged in":"logged out")}await K(t)}export{Pt as addresses,at as customer,vt as deleteAddress,C as getToken,ht as handleCallback,nt as isLoggedIn,dt as login,wt as logout,Dt as mountAccount,Et as order,mt as orders,V as query,K as render,Ot as requestReturn,$t as saveAddress,Nt as subscriptionAction,Ct as subscriptions,Ut as updateProfile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as V,B as I,D as X,G as T,b as Q,g as P,h as F,n as A,o as d,p as y,s as c,u as W,w as b}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var C="amount currencyCode",R="id firstName lastName company address1 address2 city province zoneCode zip country countryCode phoneNumber formatted",L={order:`query TetherOrder($id:ID!){order(id:$id){id name number processedAt cancelledAt financialStatus fulfillmentStatus statusPageUrl requiresShipping totalPrice{${C}}subtotal{${C}}totalShipping{${C}}totalTax{${C}}shippingAddress{${R}}billingAddress{${R}}lineItems(first:50){nodes{id name title variantTitle quantity sku image{url altText}price{${C}}totalPrice{${C}}suggestedReturnReasonDefinitions(first:10){nodes{id name handle}}}}fulfillments(first:10){nodes{id status createdAt estimatedDeliveryAt latestShipmentStatus trackingInformation{company number url}}}returnInformation{returnableLineItems(first:50){nodes{quantity lineItem{id}}}}returns(first:10){nodes{id status}}}}`,addresses:`query TetherAddresses{customer{defaultAddress{id}addresses(first:20){nodes{${R}}}}}`,subscriptions:`query TetherSubscriptions{customer{subscriptionContracts(first:20,reverse:true){nodes{id status nextBillingDate currencyCode deliveryPrice{${C}}deliveryPolicy{interval intervalCount{count}}lines(first:20){nodes{id name title variantTitle quantity sku currentPrice{${C}}lineDiscountedPrice{${C}}image{url altText}}}upcomingBillingCycles(first:3){nodes{cycleIndex skipped billingAttemptExpectedDate}}}}}}`,contract:"query TetherContract($id:ID!){customer{subscriptionContract(id:$id){id status upcomingBillingCycles(first:3){nodes{cycleIndex skipped}}}}}"},S={profile:"mutation TetherProfile($input: CustomerUpdateInput!) { customerUpdate(input: $input) { customer { firstName lastName } userErrors { field message } } }",addressCreate:`mutation TetherAddressCreate($address:CustomerAddressInput!,$default:Boolean){customerAddressCreate(address:$address,defaultAddress:$default){customerAddress{${R}}userErrors{field message}}}`,addressUpdate:`mutation TetherAddressUpdate($id:ID!,$address:CustomerAddressInput,$default:Boolean){customerAddressUpdate(addressId:$id,address:$address,defaultAddress:$default){customerAddress{${R}}userErrors{field message}}}`,addressDelete:"mutation TetherAddressDelete($id: ID!) { customerAddressDelete(addressId: $id) { deletedAddressId userErrors { field message } } }",pause:"mutation TetherPause($id: ID!) { subscriptionContractPause(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",resume:"mutation TetherResume($id: ID!) { subscriptionContractActivate(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",cancel:"mutation TetherCancel($id: ID!) { subscriptionContractCancel(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",skip:"mutation TetherSkip($input: SubscriptionBillingCycleInput!) { subscriptionBillingCycleSkip(billingCycleInput: $input) { billingCycle { cycleIndex skipped } userErrors { field message } } }",unskip:"mutation TetherUnskip($input: SubscriptionBillingCycleInput!) { subscriptionBillingCycleUnskip(billingCycleInput: $input) { billingCycle { cycleIndex skipped } userErrors { field message } } }",returnRequest:"mutation TetherReturn($orderId: ID!, $lines: [RequestedLineItemInput!]!) { orderRequestReturn(orderId: $orderId, requestedLineItems: $lines) { return { id status } userErrors { field message } } }"},p=class extends Error{},q=e=>new RegExp(`^gid://shopify/${e}/\\d+(\\?[\\w=&.-]{1,80})?$`),re={Order:q("Order"),CustomerAddress:q("CustomerAddress"),SubscriptionContract:q("SubscriptionContract"),LineItem:q("LineItem"),ReturnReasonDefinition:q("ReturnReasonDefinition")};function D(e,t){let s=/^\d{1,20}$/.test(String(t??""))?`gid://shopify/${e}/${t}`:String(t??"");if(!re[e].test(s))throw new p(`${e} id`);return s}var N=(e,t=255)=>{if(e==null||e==="")return;if(typeof e!="string"&&typeof e!="number")throw new p("text");let s=String(e).replace(/[\u0000-\u001f\u007f]/g,"").trim();if(s.length>t)throw new p("too long");return s},ne=["firstName","lastName","company","address1","address2","city","zip","zoneCode","phoneNumber"];function ie(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new p("address");let t={};if(ne.forEach(s=>{let i=N(e[s]);i!==void 0&&(t[s]=i)}),e.countryCode!=null&&e.countryCode!==""){let s=String(e.countryCode).toUpperCase();if(!/^[A-Z]{2}$/.test(s))throw new p("countryCode");t.countryCode=s}return t}var $=e=>{let t=e?.userErrors||[];if(t.length){let s=new p(t.map(i=>i.message).join(" | "));throw s.userErrors=t,s}return e},Y={async order(e,{id:t}){return{order:(await e(L.order,{id:D("Order",t)}))?.order||null}},async profile(e,{firstName:t,lastName:s}){let i={};if(t!==void 0&&(i.firstName=N(t,100)??""),s!==void 0&&(i.lastName=N(s,100)??""),!Object.keys(i).length)throw new p("nothing to change");return{customer:$((await e(S.profile,{input:i}))?.customerUpdate).customer}},async addresses(e){let t=(await e(L.addresses,{}))?.customer,s=t?.defaultAddress?.id||null;return{addresses:(t?.addresses?.nodes||[]).map(i=>({...i,isDefault:i.id===s}))}},async saveAddress(e,{id:t,address:s,isDefault:i}){let r=ie(s||{}),n=i===!0?!0:void 0;return{address:$(t?(await e(S.addressUpdate,{id:D("CustomerAddress",t),address:Object.keys(r).length?r:null,default:n??null}))?.customerAddressUpdate:(await e(S.addressCreate,{address:r,default:n??!1}))?.customerAddressCreate).customerAddress}},async deleteAddress(e,{id:t}){return{deleted:$((await e(S.addressDelete,{id:D("CustomerAddress",t)}))?.customerAddressDelete).deletedAddressId}},async subscriptions(e){return{subscriptions:(await e(L.subscriptions,{}))?.customer?.subscriptionContracts?.nodes||[]}},async subscription(e,{id:t,action:s}){if(!["pause","resume","skip","unskip","cancel"].includes(s))throw new p("action");let i=D("SubscriptionContract",t),r=(await e(L.contract,{id:i}))?.customer?.subscriptionContract;if(!r){let o=new p("not found");throw o.status=404,o}if(s==="skip"||s==="unskip"){let o=r.upcomingBillingCycles?.nodes||[],u=s==="skip"?o.find(m=>!m.skipped):o.find(m=>m.skipped);if(!u)throw new p(s==="skip"?"no upcoming delivery to skip":"nothing skipped");return{billingCycle:$((await e(S[s],{input:{contractId:i,selector:{index:u.cycleIndex}}}))?.[s==="skip"?"subscriptionBillingCycleSkip":"subscriptionBillingCycleUnskip"]).billingCycle}}let n={pause:"subscriptionContractPause",resume:"subscriptionContractActivate",cancel:"subscriptionContractCancel"}[s];return{contract:$((await e(S[s],{id:i}))?.[n]).contract}},async requestReturn(e,{orderId:t,lines:s}){let i=D("Order",t);if(!Array.isArray(s)||!s.length||s.length>50)throw new p("lines");let r=s.map(a=>{let o=Number(a?.quantity);if(!Number.isInteger(o)||o<1||o>1e3)throw new p("quantity");let u={lineItemId:D("LineItem",a.lineItemId),quantity:o};a.reasonId&&(u.returnReasonDefinitionId=D("ReturnReasonDefinition",a.reasonId));let f=N(a.note,300);return f&&(u.customerNote=f),u});return{return:$((await e(S.returnRequest,{orderId:i,lines:r}))?.orderRequestReturn).return}}};var G=null,Z=!1;function De(e){G=e}var H=e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},O=e=>{try{return new Date(e).toLocaleDateString(Q.locale||void 0)}catch{return e}},oe={order:e=>["GET",`/order?id=${encodeURIComponent(e.id)}`],addresses:()=>["GET","/addresses"],subscriptions:()=>["GET","/subscriptions"],profile:()=>["POST","/profile"],saveAddress:()=>["POST","/address"],deleteAddress:()=>["POST","/address/delete"],subscription:()=>["POST","/subscription"],requestReturn:()=>["POST","/return"]};async function w(e,t={}){let{server:s,serverFetch:i,query:r}=G;if(s()){let[n,a]=oe[e](t),o=await i(a,n==="POST"?{method:n,body:t}:{});if(o.loggedIn===!1)throw new F("Not logged in",{code:"NOT_LOGGED_IN",status:401});return o}try{return await Y[e]((n,a)=>r(n,a),t)}catch(n){throw n instanceof p?new F(n.message,{code:"INVALID",userErrors:n.userErrors}):n}}var U=e=>{G.reset(),W("account-updated",{what:e})},ae=e=>w("order",{id:e}).then(t=>t.order),de=({firstName:e,lastName:t}={})=>w("profile",{firstName:e,lastName:t}).then(s=>(U("profile"),s.customer)),ue=()=>w("addresses").then(e=>e.addresses),J=(e,{id:t,isDefault:s}={})=>w("saveAddress",{id:t,address:e,isDefault:s}).then(i=>(U("addresses"),i.address)),ce=e=>w("deleteAddress",{id:e}).then(t=>(U("addresses"),t.deleted)),le=()=>w("subscriptions").then(e=>e.subscriptions),pe=(e,t)=>w("subscription",{id:e,action:t}).then(s=>(U("subscriptions"),s)),fe=(e,t)=>w("requestReturn",{orderId:e,lines:t}).then(s=>(U("orders"),s.return));var x=e=>e?String(e).toLowerCase().replace(/_/g," "):"",z=e=>(e?.formatted||[]).join(", "),E=(e,t,s)=>c(e,d(t)).forEach(i=>{let r=y(i,t);r in s&&X(i,!!s[r])}),j=(e,t)=>E(e,"show",t);function me(e,t,s=null){T(e,t,(i,r)=>{let n=s&&s.get(r.id)||0;i.dataset.tetherLine=r.id,c(i,d("order-line")).concat(i.matches(d("order-line"))?[i]:[]).forEach(a=>{let o=y(a,"order-line");if(o==="image"){r.image&&V(a,r.image.url,r.image.altText||r.title);return}let u={title:r.title||r.name,"variant-title":r.variantTitle||"",quantity:String(r.quantity),price:r.price?b(r.price):"",total:r.totalPrice?b(r.totalPrice):"",sku:r.sku||"",returnable:String(n)}[o];u!=null&&I(a,u)}),E(i,"order-line-show",{returnable:n>0}),c(i,d("return-quantity")).forEach(a=>{a.max=String(n),a.min="0",a.value||(a.value="0"),a.disabled=n<1}),c(i,`select${d("return-reason")}`).forEach(a=>{let o=r.suggestedReturnReasonDefinitions?.nodes||[];a.dataset.tetherFilled!==r.id&&(a.dataset.tetherFilled=r.id,o.forEach(u=>a.appendChild(new Option(u.name,u.id))))})})}var he={order:d("order")};async function ee(e){let t=y(e,"order")||"",s=t.startsWith("url:")?new URL(window.location.href).searchParams.get(t.slice(4)||"id"):t,i=o=>e.setAttribute(A("order-state"),o);if(!s){i("not-found"),E(e,"order-show",{"not-found":!0});return}i("loading"),E(e,"order-show",{loading:!0,ready:!1,"not-found":!1,error:!1});let r;try{r=await ae(s)}catch(o){P(o,"order"),i("error"),E(e,"order-show",{loading:!1,error:!0});return}if(!r){i("not-found"),E(e,"order-show",{loading:!1,"not-found":!0});return}e.dataset.tetherOrderId=r.id;let n=new Map((r.returnInformation?.returnableLineItems?.nodes||[]).map(o=>[o.lineItem?.id,o.quantity])),a=r.fulfillments?.nodes||[];c(e,d("order-bind")).forEach(o=>{let u=y(o,"order-bind");if(u==="url"){H(r.statusPageUrl)&&o.setAttribute("href",r.statusPageUrl);return}let f={name:r.name,date:O(r.processedAt),total:b(r.totalPrice),subtotal:r.subtotal?b(r.subtotal):"",shipping:r.totalShipping?b(r.totalShipping):"",tax:r.totalTax?b(r.totalTax):"",status:x(r.financialStatus),fulfillment:x(r.fulfillmentStatus),"shipping-address":z(r.shippingAddress),"billing-address":z(r.billingAddress),items:(r.lineItems?.nodes||[]).map(m=>`${m.quantity}\xD7 ${m.title||m.name}`).join(", "),cancelled:r.cancelledAt?O(r.cancelledAt):""}[u];f!=null&&I(o,f)}),c(e,d("order-lines")).forEach(o=>me(o,r.lineItems?.nodes||[],n)),c(e,d("order-fulfillments")).forEach(o=>T(o,a,(u,f)=>{let m=f.trackingInformation?.[0]||{};c(u,d("fulfillment-bind")).concat(u.matches(d("fulfillment-bind"))?[u]:[]).forEach(h=>{let g=y(h,"fulfillment-bind");if(g==="url"){H(m.url)&&h.setAttribute("href",m.url);return}let l={status:x(f.latestShipmentStatus||f.status),date:O(f.createdAt),eta:f.estimatedDeliveryAt?O(f.estimatedDeliveryAt):"",company:m.company||"",number:m.number||""}[g];l!=null&&I(h,l)})})),E(e,"order-show",{loading:!1,ready:!0,error:!1,"not-found":!1,cancelled:!!r.cancelledAt,shipped:a.length>0,returnable:[...n.values()].some(o=>o>0),"has-returns":(r.returns?.nodes||[]).length>0,"return-requested":e.dataset.tetherReturned==="1"}),i("ready")}async function ge(e){let t=await G.customer().catch(()=>null);t&&["firstName","lastName"].forEach(s=>{let i=e.elements?.[s];i&&!i.dataset.tetherTouched&&(i.value=t[s]||"")})}var te=null;async function B(e){let t=c(e,d("addresses"));if(!t.length)return;j(e,{"addresses-loading":!0,"addresses-empty":!1});let s=[];try{s=te=await ue()}catch(i){P(i,"addresses")}j(e,{"addresses-loading":!1,"addresses-empty":s.length===0}),t.forEach(i=>T(i,s,(r,n)=>{r.dataset.tetherAddress=n.id,c(r,d("address-bind")).concat(r.matches(d("address-bind"))?[r]:[]).forEach(a=>{let o={formatted:z(n),name:[n.firstName,n.lastName].filter(Boolean).join(" "),company:n.company||"",address1:n.address1||"",address2:n.address2||"",city:n.city||"",zip:n.zip||"",province:n.province||"",country:n.country||"",phone:n.phoneNumber||""}[y(a,"address-bind")];o!=null&&I(a,o)}),E(r,"address-show",{default:n.isDefault,"not-default":!n.isDefault})}))}var ye=["pause","resume","skip","unskip","cancel"];function be(e){let t=e.upcomingBillingCycles?.nodes?.[0],s=e.status;return{active:s==="ACTIVE",paused:s==="PAUSED",cancelled:s==="CANCELLED",expired:s==="EXPIRED",failed:s==="FAILED",skipped:!!t?.skipped,"can-pause":s==="ACTIVE","can-resume":s==="PAUSED"||s==="FAILED","can-skip":s==="ACTIVE"&&!!t&&!t.skipped,"can-unskip":s==="ACTIVE"&&!!t?.skipped,"can-cancel":s==="ACTIVE"||s==="PAUSED"||s==="FAILED"}}async function se(e){let t=c(e,d("subscriptions"));if(!t.length)return;j(e,{"subscriptions-loading":!0,"subscriptions-empty":!1});let s=[];try{s=await le()}catch(i){P(i,"subscriptions")}j(e,{"subscriptions-loading":!1,"subscriptions-empty":s.length===0}),t.forEach(i=>T(i,s,(r,n)=>{r.dataset.tetherSubscription=n.id,r.setAttribute(A("subscription-status"),x(n.status));let a=n.lines?.nodes||[],o=n.deliveryPolicy?.intervalCount?.count||1,u=x(n.deliveryPolicy?.interval),f=a.reduce((h,g)=>h+parseFloat(g.lineDiscountedPrice?.amount||0),0);c(r,d("subscription-bind")).forEach(h=>{let g=y(h,"subscription-bind"),l={status:x(n.status),next:n.nextBillingDate?O(n.nextBillingDate):"",interval:u?o===1?u:`${o} ${u}s`:"",products:a.map(v=>`${v.quantity}\xD7 ${v.title}`).join(", "),total:a.length?b({amount:String(f),currencyCode:n.currencyCode}):"",delivery:n.deliveryPrice?b(n.deliveryPrice):""}[g];l!=null&&I(h,l)}),c(r,d("subscription-lines")).forEach(h=>T(h,a,(g,l)=>{c(g,d("subscription-line")).concat(g.matches(d("subscription-line"))?[g]:[]).forEach(v=>{let _=y(v,"subscription-line");if(_==="image"){l.image&&V(v,l.image.url,l.image.altText||l.title);return}let M={title:l.title,"variant-title":l.variantTitle||"",quantity:String(l.quantity),price:b(l.currentPrice)}[_];M!=null&&I(v,M)})}));let m=be(n);E(r,"subscription-show",m),c(r,d("subscription-action")).forEach(h=>{let g=y(h,"subscription-action"),l=m[`can-${g}`];h.disabled=!l,h.classList.toggle("is-disabled",!l)})}))}async function $e(e=document){Z||(Z=!0,Ae()),await Promise.all([...c(e,d("order")).map(t=>ee(t)),...c(e,d("profile-form")).map(t=>ge(t)),B(e),se(e)])}var K=e=>Object.fromEntries([...e.elements].filter(t=>t.name&&t.type!=="submit"&&t.type!=="button"&&t.type!=="checkbox").map(t=>[t.name,t.value]));async function k(e,t,{error:s}={}){e.classList.add("is-busy"),e.setAttribute("aria-busy","true"),e.setAttribute(A("form-state"),"pending"),c(e,d("form-error")).forEach(i=>I(i,""));try{let i=await t();return e.setAttribute(A("form-state"),"saved"),i}catch(i){e.setAttribute(A("form-state"),"error");let r=i?.userErrors?.map(n=>n.message).join(" ")||i?.message||"Something went wrong";c(e,d("form-error")).forEach(n=>I(n,r.replace(/^Customer accounts: /,""))),s&&P(i,s);return}finally{e.classList.remove("is-busy"),e.removeAttribute("aria-busy")}}function Ae(){document.addEventListener("submit",e=>{let t=e.target;if(t.matches?.(d("profile-form")))e.preventDefault(),k(t,()=>de(K(t)));else if(t.matches?.(d("address-form"))){e.preventDefault();let s=t.dataset.tetherAddressId||void 0,i=!!t.elements?.isDefault?.checked;k(t,async()=>{await J(K(t),{id:s,isDefault:i}),t.reset(),delete t.dataset.tetherAddressId,await B(document)})}}),document.addEventListener("input",e=>{e.target.closest?.(d("profile-form"))&&(e.target.dataset.tetherTouched="1")}),document.addEventListener("click",e=>{let t=e.target,s=t.closest?.("[data-tether-address]"),i=n=>{let a=y(n,"confirm");return!a||window.confirm(a)},r;if((r=t.closest?.(d("address-delete")))&&s)e.preventDefault(),i(r)&&k(s,async()=>{await ce(s.dataset.tetherAddress),await B(document)});else if((r=t.closest?.(d("address-default")))&&s)e.preventDefault(),k(s,async()=>{await J(null,{id:s.dataset.tetherAddress,isDefault:!0}),await B(document)});else if((r=t.closest?.(d("address-edit")))&&s){e.preventDefault();let n=(te||[]).find(o=>o.id===s.dataset.tetherAddress),a=document.querySelector(d("address-form"));n&&a&&(a.dataset.tetherAddressId=n.id,[...a.elements].forEach(o=>{o.name&&o.name in n&&(o.value=n[o.name]??""),o.name==="isDefault"&&(o.checked=n.isDefault)}),a.scrollIntoView?.({block:"nearest"}))}else if(r=t.closest?.(d("address-new"))){let n=document.querySelector(d("address-form"));n&&(n.reset(),delete n.dataset.tetherAddressId)}else if(r=t.closest?.(d("subscription-action"))){e.preventDefault();let n=r.closest("[data-tether-subscription]"),a=y(r,"subscription-action");if(!n||!ye.includes(a)||r.disabled||!i(r))return;n.setAttribute(A("subscription-state"),"pending"),k(n,async()=>{await pe(n.dataset.tetherSubscription,a),await se(document)}).then(()=>{n.setAttribute(A("subscription-state"),n.getAttribute(A("form-state"))==="error"?"error":"done")})}else if(r=t.closest?.(d("order-return"))){e.preventDefault();let n=r.closest(he.order);if(!n?.dataset.tetherOrderId)return;let a=c(n,"[data-tether-line]").map(o=>({lineItemId:o.dataset.tetherLine,quantity:parseInt(o.querySelector(d("return-quantity"))?.value||"0",10),reasonId:o.querySelector(d("return-reason"))?.value||void 0,note:o.querySelector(d("return-note"))?.value||void 0})).filter(o=>o.quantity>0);if(!a.length||!i(r))return;k(n,async()=>{await fe(n.dataset.tetherOrderId,a),n.dataset.tetherReturned="1",await ee(n)})}})}export{ue as addresses,ce as deleteAddress,ae as order,$e as renderPages,fe as requestReturn,J as saveAddress,De as setup,pe as subscriptionAction,le as subscriptions,de as updateProfile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t={diagnose:()=>import("./diagnose-VXQBSD3A.js"),markets:()=>import("./markets-ui-F3R5T5EL.js"),search:()=>import("./search-NILMGYXG.js"),extras:()=>import("./extras-R4X34VQL.js"),account:()=>import("./account-QUBHQG3C.js"),"account-pages":()=>import("./account-pages-VWDHF6WA.js"),analytics:()=>import("./analytics-SLATWPLC.js")},r=o=>t[o](),a=void 0;export{r as a,a as b};
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import{c as D}from"./chunk-64TUD3QR.js";import{a as
|
|
1
|
+
import{c as D}from"./chunk-64TUD3QR.js";import{a as y,d as M}from"./chunk-RREHGH4A.js";import{c as P}from"./chunk-FIOZPPC5.js";import{e as V}from"./chunk-AJLPU2JC.js";import{F as q,b as i,d as S,i as E,l as x,n as h,o as c,p as g,s as d}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 a=o.y*4+(o.m-1)/3+n;return B(Math.floor(a/4),a%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 a=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 a>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:a<=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","addresses-loading","addresses-empty","subscriptions-loading","subscriptions-empty"]),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
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
|
|
5
5
|
discount-remove display error group group-add hide-single language limit line line-attribute line-attributes line-id
|
|
6
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
|
|
7
|
+
option-selected option-value order order-bind order-line order-lines order-line-show order-show order-state order-fulfillments
|
|
8
|
+
fulfillment-bind order-return return-quantity return-reason return-note orders profile-form address-form addresses address-bind
|
|
9
|
+
address-show address-edit address-new address-delete address-default subscriptions subscription-bind subscription-lines
|
|
10
|
+
subscription-line subscription-show subscription-action subscription-status subscription-state confirm form-state form-error page-country page-language page-locale page-title plan plan-bind plan-list
|
|
8
11
|
plan-value product products purchase purchase-mode qty qty-minus qty-plus quantity recommendations reverse search
|
|
9
12
|
search-bind search-collections search-input search-limit search-min search-products search-queries search-results
|
|
10
13
|
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},(
|
|
14
|
+
sig label hydrated busy`.split(/\s+/).filter(Boolean));function O(e,n){let o=Array.from({length:e.length+1},(a,r)=>[r,...Array(n.length).fill(0)]);for(let a=1;a<=n.length;a++)o[0][a]=a;for(let a=1;a<=e.length;a++)for(let r=1;r<=n.length;r++)o[a][r]=Math.min(o[a-1][r]+1,o[a][r-1]+1,o[a-1][r-1]+(e[a-1]===n[r-1]?0:1));return o[e.length][n.length]}function $(e,n,o=""){let a=null,r=1/0;for(let f of n){let l=O(String(e),f);l<r&&(r=l,a=f)}return a&&r<=Math.max(2,Math.floor(String(e).length/4))?` Did you mean "${o}${a}"?`:""}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,s,u)=>n.push({level:t,message:s,element:u?j(u):void 0,el:u}),a=t=>!!t.closest(c("product")),r=`${c("collection")},${c("products")},${c("recommendations")}`;d(e,c("product")).forEach(t=>{if(t.closest(r)&&t.closest(c("list")))return;let{key:s,fromUrl:u,raw:b}=y(t);b?u&&!s&&o("warn",`${h("product")}="${b}" 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=>{d(e,c(t)).forEach(s=>{a(s)||t==="line-attribute"&&s.closest(c("group"))||o("warn",`${h(t)} outside any ${h("product")}: it does nothing here.`,s)})}),d(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=>d(e,c(t)).forEach(s=>{!s.firstElementChild&&!q(s)&&o("warn",`${h(t)} without a template child: put one example element inside it.`,s)})),d(e,r).forEach(t=>{d(t,c("list")).length||o("error",`List without a ${h("list")} child: products have nowhere to render.`,t)}),d(e,c("show")).forEach(t=>{let s=g(t,"show");C.has(s)||o("warn",`Unknown ${h("show")}="${s}".${$(s,C)}`,t)}),d(e,c("bind")).forEach(t=>{let s=g(t,"bind")||"";!s||N.has(s)||/^image:\d+$/.test(s)||s.startsWith("metafield:")||o("warn",`Unknown ${h("bind")}="${s}": it stays empty.${$(s,N)}`,t)});let l=`${i.prefix}-`,w=new Set;return d(e,"*").forEach(t=>{for(let s of t.attributes){if(!s.name.startsWith(l))continue;let u=s.name.slice(l.length);U.has(u)||w.has(u)||(w.add(u),o("warn",`Unknown attribute ${s.name}: Tether ignores it.${$(u,U,l)}`,t))}}),d(e,c("bind")).forEach(t=>{let s=g(t,"bind")||"";if(!s.startsWith("metafield:"))return;let u=s.slice(10);(i.metafields||[]).some(m=>(typeof m=="string"?m:`${m.namespace}.${m.key}`)===u)||o("error",`${h("bind")}="${s}" but "${u}" is not in config.metafields, so it stays empty.`,t)}),d(e,c("cart-open")).length&&!d(e,c("cart-drawer")).length&&o("warn",`${h("cart-open")} exists but there is no ${h("cart-drawer")} on this page.`),d(e,c("cart-drawer")).length>1&&o("warn",`More than one ${h("cart-drawer")}.`),d(e,`[${h("state")}="error"]`).forEach(t=>{t.matches(M())&&o("error",`Scope failed to load (${g(t,"error")||"error"}).`,t)}),n}async function X({root:e=document,silent:n=!1,version:o,now:a=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,a),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(d(e,c("product")).map(t=>y(t).key).filter(Boolean))].slice(0,20);(await Promise.allSettled(l.map(t=>P(t)))).forEach((t,s)=>{if(t.status==="fulfilled"){let u=t.value,b=V(u);r.products.push({key:l[s],handle:u.handle,title:u.title,plans:b.length,requiresSellingPlan:u.requiresSellingPlan}),b.forEach(m=>r.sellingPlans.push({product:u.handle,group:m.group?.name,plan:m.name,id:m.id})),d(e,c("product")).filter(m=>y(m).key===l[s]&&m.querySelector(c("add-to-cart"))).forEach(m=>{let k=new Set(d(m,`${c("option-list")},select${c("option")}`).map(p=>g(p,"option-list")||g(p,"option")));if(!k.size&&d(m,`select${c("variant-select")}`).length)return;let v=(u.options||[]).map(p=>p.name);i.language||[...k].filter(p=>p&&!v.includes(p)).forEach(p=>{r.problems.push({level:"warn",message:`Product "${u.handle}" has no option "${p}" (its options: ${v.join(", ")||"none"}).${$(p,v)}`})}),(u.options||[]).filter(p=>p.optionValues.length>1&&!k.has(p.name)).forEach(p=>{r.problems.push({level:"warn",message:`Product "${u.handle}": option "${p.name}" (${p.optionValues.length} values) has no tether-option-list, so visitors can't choose it.`})})})}else r.products.push({key:l[s],error:t.reason?.message}),r.problems.push({level:"error",message:`Product "${l[s]}": ${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(a=>a.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(a=>(a.level==="error"?n.error:n.warn)(a.message,a.el||"")),n.groupEnd?.()}export{T as apiVersionStatus,R as checkMarkup,X as diagnose,$ as didYouMean};
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as j,b as W,d as x,f as C,g as Z,h as g,i as X,j as Y,k as ee,l as te,m as ne}from"./chunks/chunk-VCPI7MJ2.js";import{a as V}from"./chunks/chunk-ZIUIWEON.js";import{a as Q}from"./chunks/chunk-RREHGH4A.js";import{a as l,b as re}from"./chunks/chunk-VPVJPNB4.js";import{a as J,b as c}from"./chunks/chunk-L2TRRKYV.js";import{a as _,b as q,c as R,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 P,d as L,e as $,f as D,g as u,h as M,j as N,l as U,n as p,o as a,u as k,w as H,y as z}from"./chunks/chunk-K2YEQAIH.js";import"./chunks/chunk-VC46IEJQ.js";var oe="0.6.5",f=null,S=null;function m(t=document){if(!L())return 0;let e=0;return Z(),ne(t),g(t,j()).forEach(n=>{if(x.has(n))return;x.add(n),e++;let o=new W(n);C.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>m(i.detail.container)),ee(o.load())}),g(t,a("product")).forEach(n=>{X(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,["account-login","account-bind","account-link","orders","order","addresses","subscriptions","profile-form","address-form"].map(n=>`[${p(n)}]`).join(",")+`,[${p("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||ge())&&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")),te(),c.render(),$(`mounted ${e} scope(s)`,t),e}function ie(){c.close()}function fe(t){let e=t?.closest?.(a("product"));return e&&V.get(e)||null}var ae=!1;function me(){ae||(ae=!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(ce());if(i&&i.closest(a("cart-lines"))){let d=i.getAttribute(`data-${r.prefix}-key`),E=c.lines.find(w=>w.id===d),b=w=>{t.preventDefault(),w().catch(de=>u(de,"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(p("discount-code"));d&&c.removeDiscount(d).catch(E=>u(E,"discount"));return}let y=e.closest(a("group-add"));y&&(t.preventDefault(),h(y,()=>se(y)))}),document.addEventListener("change",t=>{let e=t.target;if(!e?.closest)return;let n=e.closest(ce()),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?.(p("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(f||Promise.resolve()).then(()=>{let t=T();if(!t&&A){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:le}A=!!T(),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(()=>m(document),()=>m(document)):m(document)})),document.addEventListener("astro:before-swap",()=>ie())),window.addEventListener("online",()=>{Y(),C.forEach(t=>{t.root.getAttribute(p("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?J(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 ce(){return`[data-${r.prefix}-key]`}var se=t=>l("extras").then(e=>e.addGroup(t)),v=null;function ue(t={}){return f&&!Object.keys(t).length?f:(P({...window.TETHER_CONFIG||{},...t}),L()?(me(),r.observe&&he(),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"))),f=pe(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}),O}),f):(D("TETHER_CONFIG is missing domain or token. Tether is idle."),f=Promise.resolve(null),f))}function T(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 le=null,A=!1;async function pe(t){let e=r.markets||{};le={country:r.country,language:r.language,locale:r.locale};let n=T();if(A=!!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),$("market",o))}function ge(){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 ye=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 he(){if(S||typeof MutationObserver>"u")return;let t=null,e=new Set;S=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&&m(o)}),e.clear()},50)}),S.observe(document.body,{childList:!0,subtree:!0})}var O={VERSION:oe,init:ue,mount:m,unmount:ie,get config(){return r},get ready(){return f||Promise.resolve(null)},query:U,withContext:N,cart:c,getProduct:R,getProducts:G,getRecommendations:B,getScope:fe,addGroup:se,account:ye,primeProduct:q,normalizeProductKey:_,clearProductCache:F,formatMoney:H,imageUrl:z,plans:K,TetherError:M,resolveProductKey:Q,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:oe})),__core:re,__parts:{},on(t,e){let n=o=>e(o.detail,o);return document.addEventListener(`${r.prefix}:${t}`,n),()=>document.removeEventListener(`${r.prefix}:${t}`,n)}},Pe=O;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=O,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let e=()=>ue().then(()=>m(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{oe as VERSION,se as addGroup,O as api,Pe as default,fe as getScope,ue as init,m as mount,I as setCountry,ie as unmount};
|