@swishapp/sdk 0.60.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/swish.js +2 -2
- package/package.json +1 -1
package/dist/swish.js
CHANGED
|
@@ -15,7 +15,7 @@ Values:
|
|
|
15
15
|
left: 0px;
|
|
16
16
|
right: 0px;
|
|
17
17
|
}
|
|
18
|
-
`),document.documentElement.setAttribute("locked",""))},"lockScroll"),oi=i(()=>{Ie>0&&Ie--,Ie===0&&(fe&&fe.replaceSync(""),window.scrollTo({top:Re,behavior:"instant"}),Re=0,document.documentElement.removeAttribute("locked"))},"unlockScroll");typeof requestIdleCallback=="function"?requestIdleCallback(()=>{be()}):setTimeout(()=>{be()},1e3);var ai=x({itemId:G(V(b())),productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()))}),he=class extends C{static{i(this,"EditItemVariantHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(ai,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(c=>c.message)});return}let{itemId:a,productId:u,variantId:l}=o.output;dr({productId:u.toString(),variantId:l?.toString(),onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async c=>{let{item:p,product:h,variant:v}=c,y={code:"ok",data:{item:p,product:h,variant:v}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemVariant",{detail:y})),n(y)},"onSubmit")})})}};var ui=x({productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(Number),F())),quantity:G(V(F(),at(1))),tags:G(ut(b()))}),Te=class extends C{static{i(this,"CreateItemHandler")}async invoke(e){let r=e.data,n=O(ui,r);if(!n.success)return{code:"error",message:"Invalid intent data",issues:n.issues.map(v=>v.message)};let{productId:s,variantId:o,quantity:a,tags:u}=n.output,l=await this.swish.storefront.loadSaveIntentData({productId:E("Product",s),variantId:o?E("ProductVariant",o):void 0});if(l.errors)return{code:"error",message:l.errors.message??"Failed to load save intent data",issues:l.errors.graphQLErrors?.map(v=>v.message)??[]};if(!l.data||!l.data.product)return{code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=l.data,p=c.variantsCount?.count&&c.variantsCount.count>1;if(!p||this.options.allowSaveWithoutVariant){let v=i(()=>!p&&c.selectedOrFirstAvailableVariant?Number(P(c.selectedOrFirstAvailableVariant.id)):o,"variantIdToUse"),y=await this.swish.api.items.create({productId:s,variantId:v(),quantity:a,tags:u});if("error"in y)return{code:"error",message:"Failed to create item",issues:[y.error.message]};if(!y.data)return{code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let R="variant"in l.data?l.data.variant:void 0,m={code:"ok",data:{item:y.data,product:c,variant:p?R:c.selectedOrFirstAvailableVariant}};return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:m})),m}let h=await new he(this.swish,this.eventBus,this.options).invoke({action:"edit",type:"swish/ItemVariant",data:{productId:s,variantId:o}});return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:h})),h}};var _e=class extends C{static{i(this,"CreateListHandler")}async invoke(e){return new Promise(r=>{Pe({onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async n=>{let{list:s}=n;r({code:"ok",data:{list:s}})},"onSubmit")})})}};var li=x({itemId:b()}),Oe=class extends C{static{i(this,"DeleteItemHandler")}async invoke(e){return new Promise(r=>{let n=O(li,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)});return}let{itemId:s}=n.output;sr({itemId:s,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(()=>{r({code:"ok",data:{itemId:s}})},"onSubmit")})})}};var ci=x({listId:b()}),Le=class extends C{static{i(this,"DeleteListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(ci,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;or({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async()=>{r({code:"ok",data:{listId:o}})},"onSubmit")})})}};var pi=x({itemId:b()}),$e=class extends C{static{i(this,"EditItemListsHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(pi,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(u=>u.message)});return}let{itemId:a}=o.output;lr({itemId:a,onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async u=>{let{item:l,product:c,variant:p}=u,h={code:"ok",data:{item:l,product:c,variant:p}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemLists",{detail:h})),n(h)},"onSubmit"),onUnsave(u){let l={code:"ok",data:{itemId:u.itemId}};n(l)}})})}};var di=x({listId:b()}),Ve=class extends C{static{i(this,"EditListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(di,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;Pe({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async a=>{let{list:u}=a;r({code:"ok",data:{list:u}})},"onSubmit")})})}};var qe=class extends C{static{i(this,"OpenHomeHandler")}async invoke(e){return new Promise(r=>{ar({onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var fi=x({listId:b()}),Be=class extends C{static{i(this,"OpenListMenuHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(fi,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;ur({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onEdit:i(a=>{r({code:"ok",data:a})},"onEdit"),onDelete:i(()=>{r({code:"ok",data:{listId:o}})},"onDelete")})})}};var Mo=x({returnTo:G(b())}),Ne=class extends C{static{i(this,"OpenSignInHandler")}async invoke(e){return new Promise(r=>{ir({returnTo:e.data?.returnTo,onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var hi=x({productId:b(),variantId:G(b())}),Ge=class extends C{static{i(this,"OpenQuickBuyHandler")}async invoke(e){return new Promise(r=>{let n=O(hi,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)});return}let{productId:s,variantId:o}=n.output;fr({productId:s,variantId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(a=>{r({code:"ok",data:a})},"onSubmit")})})}};var ye=class{constructor(e,r){this.swish=e;this.options=r}static{i(this,"IntentHook")}};var je=class extends ye{static{i(this,"AfterCreateItemHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){let{item:r,product:n,variant:s}=e.data;n&&this.swish.ui.showToast({title:"Saved",text:n.title,image:s?.image?.url??n.featuredImage?.url,action:{label:"Add to List",onClick:i(()=>{this.swish.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:r.id}})},"onClick")}})}}};var Ue=class extends ye{static{i(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){if("itemId"in e.data)return;let{product:r,variant:n}=e.data;r&&this.swish.ui.showToast({title:"Saved",text:r.title,image:n?.image?.url??r.featuredImage?.url,action:{label:"View",onClick:i(()=>{this.swish.intents.invoke({action:"open",type:"swish/Home"})},"onClick")}})}}};var Me=class{static{i(this,"Intents")}constructor(e,r){this.swish=e,this.eventBus=new EventTarget,this.options=r,this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,r){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,r)}async invoke(e){let r=this.parseIntent(e),n=this.getIntentQuery(r),s={lifecycle:"before",intent:r};return this.publishAnalyticsEvent("swish-intent",s),this.publishAnalyticsEvent(`swish-intent=${n}`,s),{intent:r,complete:this.handleIntent(r).then(o=>{let a={lifecycle:"after",intent:r,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${n}`,a),o})}}listen(e,r){let n=this.getIntentQuery(e),s=i(a=>{"detail"in a&&a.detail?r(a.detail):console.warn("Intent response event without detail",a)},"eventListener"),o=i(()=>{this.eventBus.removeEventListener(n,s)},"unsubscribe");return this.eventBus.addEventListener(n,s),o}getIntentQuery(e){return`${e.action}:${e.type}`}parseIntent(e){if(typeof e=="string"){let[r,...n]=e.split(","),[s,o]=r.split(":"),a=n.reduce((u,l)=>{let[c,p]=l.split("=");return u[c]=p,u},{});return{action:s,type:o,data:a}}return e}async handleIntent(e){return e.action==="create"&&e.type==="swish/Item"?new Te(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/Item"?new Oe(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemVariant"?new he(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemLists"?new $e(this.swish,this.eventBus,this.options).invoke(e):e.action==="create"&&e.type==="swish/List"?new _e(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/List"?new Ve(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/List"?new Le(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/Home"?new qe(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/ListMenu"?new Be(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/SignIn"?new Ne(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/QuickBuy"?new Ge(this.swish,this.eventBus,this.options).invoke(e):{code:"error",message:"Invalid intent",issues:["Invalid intent"]}}initIntentHooks(){this.eventBus.addEventListener("create:swish/Item",e=>{new je(this.swish,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:swish/ItemLists",e=>{new Ue(this.swish,this.options).invoke(e.detail)})}initIntentWatcher(){ge({selector:"[swish-intent]",onElementFound:i(e=>{let r=this.parseIntent(e.getAttribute("swish-intent"));r&&e.addEventListener("click",()=>{this.invoke(r)})},"onElementFound")}),ge({selector:"a[href*='swish-intent=']",onElementFound:i(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",r=>{if(!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&!r.altKey){let s=new URL(e.href).searchParams.get("swish-intent");if(s){let o=this.parseIntent(s);o&&(r.preventDefault(),r.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),de({fireOnInit:!0,onLocationChange:i(e=>{let r=new URLSearchParams(window.location.search).get("swish-intent");if(r){let n=this.parseIntent(r);if(n){this.invoke(n);let s=new URL(window.location.href);s.searchParams.delete("swish-intent"),window.history.replaceState({},document.title,s.toString())}}},"onLocationChange")})}};var yi=Symbol.for("preact-signals");function He(){if(ee>1)ee--;else{for(var t,e=!1;we!==void 0;){var r=we;for(we=void 0,pt++;r!==void 0;){var n=r.o;if(r.o=void 0,r.f&=-3,!(8&r.f)&&vr(r))try{r.c()}catch(s){e||(t=s,e=!0)}r=n}}if(pt=0,ee--,e)throw t}}i(He,"t");function te(t){if(ee>0)return t();ee++;try{return t()}finally{He()}}i(te,"r");var I=void 0;function yr(t){var e=I;I=void 0;try{return t()}finally{I=e}}i(yr,"n");var we=void 0,ee=0,pt=0,Fe=0;function mr(t){if(I!==void 0){var e=t.n;if(e===void 0||e.t!==I)return e={i:0,S:t,p:I.s,n:void 0,t:I,e:void 0,x:void 0,r:e},I.s!==void 0&&(I.s.n=e),I.s=e,t.n=e,32&I.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=I.s,e.n=void 0,I.s.n=e,I.s=e),e}}i(mr,"e");function q(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(q,"u");q.prototype.brand=yi;q.prototype.h=function(){return!0};q.prototype.S=function(t){var e=this,r=this.t;r!==t&&t.e===void 0&&(t.x=r,this.t=t,r!==void 0?r.e=t:yr(function(){var n;(n=e.W)==null||n.call(e)}))};q.prototype.U=function(t){var e=this;if(this.t!==void 0){var r=t.e,n=t.x;r!==void 0&&(r.x=n,t.e=void 0),n!==void 0&&(n.e=r,t.x=void 0),t===this.t&&(this.t=n,n===void 0&&yr(function(){var s;(s=e.Z)==null||s.call(e)}))}};q.prototype.subscribe=function(t){var e=this;return M(function(){var r=e.value,n=I;I=void 0;try{t(r)}finally{I=n}},{name:"sub"})};q.prototype.valueOf=function(){return this.value};q.prototype.toString=function(){return this.value+""};q.prototype.toJSON=function(){return this.value};q.prototype.peek=function(){var t=I;I=void 0;try{return this.value}finally{I=t}};Object.defineProperty(q.prototype,"value",{get:i(function(){var t=mr(this);return t!==void 0&&(t.i=this.i),this.v},"get"),set:i(function(t){if(t!==this.v){if(pt>100)throw new Error("Cycle detected");this.v=t,this.i++,Fe++,ee++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{He()}}},"set")});function S(t,e){return new q(t,e)}i(S,"d");function vr(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}i(vr,"c");function gr(t){for(var e=t.s;e!==void 0;e=e.n){var r=e.S.n;if(r!==void 0&&(e.r=r),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}i(gr,"a");function Ir(t){for(var e=t.s,r=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):r=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}t.s=r}i(Ir,"l");function ae(t,e){q.call(this,void 0),this.x=t,this.s=void 0,this.g=Fe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(ae,"y");ae.prototype=new q;ae.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Fe))return!0;if(this.g=Fe,this.f|=1,this.i>0&&!vr(this))return this.f&=-2,!0;var t=I;try{gr(this),I=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(r){this.v=r,this.f|=16,this.i++}return I=t,Ir(this),this.f&=-2,!0};ae.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}q.prototype.S.call(this,t)};ae.prototype.U=function(t){if(this.t!==void 0&&(q.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ae.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ae.prototype,"value",{get:i(function(){if(1&this.f)throw new Error("Cycle detected");var t=mr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v},"get")});function U(t,e){return new ae(t,e)}i(U,"w");function br(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ee++;var r=I;I=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,dt(t),n}finally{I=r,He()}}}i(br,"_");function dt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,br(t)}i(dt,"b");function mi(t){if(I!==this)throw new Error("Out-of-order effect");Ir(this),I=t,this.f&=-2,8&this.f&&dt(this),He()}i(mi,"g");function me(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}i(me,"p");me.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};me.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,br(this),gr(this),ee++;var t=I;return I=this,mi.bind(this,t)};me.prototype.N=function(){2&this.f||(this.f|=2,this.o=we,we=this)};me.prototype.d=function(){this.f|=8,1&this.f||dt(this)};me.prototype.dispose=function(){this.d()};function M(t,e){var r=new me(t,e);try{r.c()}catch(s){throw r.d(),s}var n=r.d.bind(r);return n[Symbol.dispose]=n,n}i(M,"E");var vi=/\/products\/([^/?]+)(?:\?variant=(\d+))?/,ft=i(t=>{let e=t.match(vi);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),wr=i(({source:t,onProductUrlChange:e})=>{let r=i(n=>{let s=ft(n);s?.productHandle&&e(s)},"handleChange");if(t instanceof HTMLAnchorElement)return Yt({element:t,onHrefChange:i(n=>r(n),"onHrefChange")});if(t instanceof Location)return de({onLocationChange:i(n=>r(n.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Er=i(t=>e=>{let{productHandle:r,productId:n,variantId:s,itemId:o}=e?.dataset??{},l=!!(n||r)||!!o,c=S({loading:!1,productId:n,variantId:s,itemId:o});if(!l){let p=e instanceof HTMLAnchorElement?e:window.location,h=ft(p.href);h?.productHandle&&h.productHandle!==c.value.productHandle&&(c.value={...c.value,...h,productId:void 0},wr({source:p,onProductUrlChange:i(v=>{c.value={...c.value,...v,productId:v.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return M(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},t.storefront.loadProductId({productHandle:c.value.productHandle}).then(p=>{p.errors&&console.error("Error loading product id",p.errors),c.value={...c.value,productId:p.data?.product?.id?P(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var Cr=i(t=>e=>{let r=U(()=>{let{productId:w,variantId:g,loading:T}=e.value;return!w||T?null:g?`variant:${P(g)}`:`product:${P(w)}`}),n=U(()=>e.value.loading||!!e.value.itemId||!e.value.productId),s=U(()=>({limit:1,query:r.value??void 0})),o=S(!n.value),a=S(null),u=S(!1),l=S(!1),{data:c,loading:p,error:h,refetching:v}=t.state.swishQuery(w=>t.api.items.list(w),{refetch:["item-create","item-update","item-delete"],variables:s,skip:n}),y=S(e.value.itemId??null);M(()=>{te(()=>{if(o.value=p.value,a.value=h.value,!e.value.itemId){let w=c.value?.[0]?.id??null;w!==y.value&&(y.value=w)}})});async function R(){if(!y.value)return;u.value=!0,(await(await t.intents.invoke({action:"delete",type:"swish/Item",data:{itemId:y.value}})).complete).code==="ok"&&(y.value=null),u.value=!1}i(R,"unsave");async function m(){if(!y.value)return;u.value=!0;let g=await(await t.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:y.value}})).complete;g.code==="ok"&&"itemId"in g.data&&(y.value=null),u.value=!1}i(m,"update");async function D(){let{productId:w,variantId:g}=e.value;if(!w)return;u.value=!0,l.value=!0;let _=await(await t.intents.invoke({action:"create",type:"swish/Item",data:{productId:w,variantId:g}})).complete;if(_.code==="ok"){let ve=_.data;y.value=ve.item.id,u.value=!1}else _.code==="error"&&console.warn("Failed to create item",_),te(()=>{u.value=!1,l.value=!1})}i(D,"save");let $=U(()=>o.value||u.value||e.value.loading);M(()=>{l.value&&!u.value&&!v.value&&(l.value=!1)});let k=U(()=>{let w=v.value&&l.value,g=!!y.value,T=!g&&(u.value||w),_=g&&(u.value||w),ve=U(()=>T?"saving":_?"unsaving":g?"saved":"unsaved");return{error:a.value,status:ve.value,savedItemId:y.value,loading:$.value,submitting:u.value,saved:g,saving:T,unsaving:_}});async function z(){$.value||(k.value.saved&&k.value.savedItemId?m():k.value.saved||await D())}return i(z,"toggle"),Object.assign(k,{save:D,unsave:R,update:m,toggle:z})},"itemStateSignal");var xr=i(t=>()=>{let{data:e,loading:r,error:n}=t.state.swishQuery(()=>t.api.items.count(),{refetch:["item-create","item-delete"]}),s=S(0),o=S(!0),a=S(null);return M(()=>{te(()=>{o.value=r.value,a.value=n.value,s.value=e.value?.count??0})}),U(()=>({count:s.value,loading:o.value,error:a.value}))},"itemCountSignal");var Sr=i(t=>(e,r)=>{let n=S(null),s=S(null),o=S(null),a=S(!r?.skip),u=S(!1),l=U(()=>a.value&&u.value);async function c(){if(!r?.skip?.value)try{a.value=!0;let p=await e(r?.variables?.value);te(()=>{o.value="error"in p?p.error:null,n.value="data"in p?p.data:null,s.value="pageInfo"in p?p.pageInfo:null,a.value=!1,u.value=!0})}catch(p){te(()=>{o.value=p,a.value=!1,u.value=!0})}}return i(c,"executeFetch"),M(()=>{if(c(),r?.refetch?.length)return t.events.subscribe(r.refetch,c)}),{data:n,pageInfo:s,error:o,loading:a,refetching:l}},"swishQuerySignals");var ue="GraphQL Client";var ht="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",yt="Response returned unexpected Content-Type:",mt="An unknown error has occurred. The API did not return a data object or any errors in its response.",Qe={json:"application/json",multipart:"multipart/mixed"},vt="X-SDK-Variant",gt="X-SDK-Version",Dr="shopify-graphql-client",kr="1.4.1",ze=1e3,Rr=[429,503],It=/@(defer)\b/i,Ar=`\r
|
|
18
|
+
`),document.documentElement.setAttribute("locked",""))},"lockScroll"),oi=i(()=>{Ie>0&&Ie--,Ie===0&&(fe&&fe.replaceSync(""),window.scrollTo({top:Re,behavior:"instant"}),Re=0,document.documentElement.removeAttribute("locked"))},"unlockScroll");typeof requestIdleCallback=="function"?requestIdleCallback(()=>{be()}):setTimeout(()=>{be()},1e3);var ai=x({itemId:G(V(b())),productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()))}),he=class extends C{static{i(this,"EditItemVariantHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(ai,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(c=>c.message)});return}let{itemId:a,productId:u,variantId:l}=o.output;dr({productId:u.toString(),variantId:l?.toString(),onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async c=>{let{item:p,product:h,variant:v}=c,y={code:"ok",data:{item:p,product:h,variant:v}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemVariant",{detail:y})),n(y)},"onSubmit")})})}};var ui=x({productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(Number),F())),quantity:G(V(F(),at(1))),tags:G(ut(b()))}),Te=class extends C{static{i(this,"CreateItemHandler")}async invoke(e){let r=e.data,n=O(ui,r);if(!n.success)return{code:"error",message:"Invalid intent data",issues:n.issues.map(v=>v.message)};let{productId:s,variantId:o,quantity:a,tags:u}=n.output,l=await this.swish.storefront.loadSaveIntentData({productId:E("Product",s),variantId:o?E("ProductVariant",o):void 0});if(l.errors)return{code:"error",message:l.errors.message??"Failed to load save intent data",issues:l.errors.graphQLErrors?.map(v=>v.message)??[]};if(!l.data||!l.data.product)return{code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=l.data,p=c.variantsCount?.count&&c.variantsCount.count>1;if(!p||this.options.allowSaveWithoutVariant){let v=i(()=>!p&&c.selectedOrFirstAvailableVariant?Number(P(c.selectedOrFirstAvailableVariant.id)):o,"variantIdToUse"),y=await this.swish.api.items.create({productId:s,variantId:v(),quantity:a,tags:u});if("error"in y)return{code:"error",message:"Failed to create item",issues:[y.error.message]};if(!y.data)return{code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let R="variant"in l.data?l.data.variant:void 0,m={code:"ok",data:{item:y.data,product:c,variant:p?R:c.selectedOrFirstAvailableVariant}};return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:m})),m}let h=await new he(this.swish,this.eventBus,this.options).invoke({action:"edit",type:"swish/ItemVariant",data:{productId:s,variantId:o}});return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:h})),h}};var _e=class extends C{static{i(this,"CreateListHandler")}async invoke(e){return new Promise(r=>{Pe({onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async n=>{let{list:s}=n;r({code:"ok",data:{list:s}})},"onSubmit")})})}};var li=x({itemId:b()}),Oe=class extends C{static{i(this,"DeleteItemHandler")}async invoke(e){return new Promise(r=>{let n=O(li,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)});return}let{itemId:s}=n.output;sr({itemId:s,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(()=>{r({code:"ok",data:{itemId:s}})},"onSubmit")})})}};var ci=x({listId:b()}),Le=class extends C{static{i(this,"DeleteListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(ci,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;or({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async()=>{r({code:"ok",data:{listId:o}})},"onSubmit")})})}};var pi=x({itemId:b()}),$e=class extends C{static{i(this,"EditItemListsHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(pi,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(u=>u.message)});return}let{itemId:a}=o.output;lr({itemId:a,onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async u=>{let{item:l,product:c,variant:p}=u,h={code:"ok",data:{item:l,product:c,variant:p}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemLists",{detail:h})),n(h)},"onSubmit"),onUnsave(u){let l={code:"ok",data:{itemId:u.itemId}};n(l)}})})}};var di=x({listId:b()}),Ve=class extends C{static{i(this,"EditListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(di,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;Pe({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async a=>{let{list:u}=a;r({code:"ok",data:{list:u}})},"onSubmit")})})}};var qe=class extends C{static{i(this,"OpenHomeHandler")}async invoke(e){return new Promise(r=>{ar({onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var fi=x({listId:b()}),Be=class extends C{static{i(this,"OpenListMenuHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(fi,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;ur({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onEdit:i(a=>{r({code:"ok",data:a})},"onEdit"),onDelete:i(()=>{r({code:"ok",data:{listId:o}})},"onDelete")})})}};var Mo=x({returnTo:G(b())}),Ne=class extends C{static{i(this,"OpenSignInHandler")}async invoke(e){return new Promise(r=>{ir({returnTo:e.data?.returnTo,onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var hi=x({productId:b(),variantId:G(b())}),Ge=class extends C{static{i(this,"OpenQuickBuyHandler")}async invoke(e){return new Promise(r=>{let n=O(hi,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)});return}let{productId:s,variantId:o}=n.output;fr({productId:s,variantId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(a=>{r({code:"ok",data:a})},"onSubmit")})})}};var ye=class{constructor(e,r){this.swish=e;this.options=r}static{i(this,"IntentHook")}};var je=class extends ye{static{i(this,"AfterCreateItemHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){let{item:r,product:n,variant:s}=e.data;n&&this.swish.ui.showToast({title:"Saved",text:n.title,image:s?.image?.url??n.featuredImage?.url,action:{label:"Add to List",onClick:i(()=>{this.swish.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:r.id}})},"onClick")}})}}};var Ue=class extends ye{static{i(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){if("itemId"in e.data)return;let{product:r,variant:n}=e.data;r&&this.swish.ui.showToast({title:"Saved",text:r.title,image:n?.image?.url??r.featuredImage?.url,action:{label:"View",onClick:i(()=>{this.swish.intents.invoke({action:"open",type:"swish/Home"})},"onClick")}})}}};var Me=class{static{i(this,"Intents")}constructor(e,r){this.swish=e,this.eventBus=new EventTarget,this.options=r,this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,r){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,r)}async invoke(e){let r=this.parseIntent(e),n=this.getIntentQuery(r),s={lifecycle:"before",intent:r};return this.publishAnalyticsEvent("swish-intent",s),this.publishAnalyticsEvent(`swish-intent=${n}`,s),{intent:r,complete:this.handleIntent(r).then(o=>{let a={lifecycle:"after",intent:r,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${n}`,a),o})}}listen(e,r){let n=this.getIntentQuery(e),s=i(a=>{"detail"in a&&a.detail?r(a.detail):console.warn("Intent response event without detail",a)},"eventListener"),o=i(()=>{this.eventBus.removeEventListener(n,s)},"unsubscribe");return this.eventBus.addEventListener(n,s),o}getIntentQuery(e){return`${e.action}:${e.type}`}parseIntent(e){if(typeof e=="string"){let[r,...n]=e.split(","),[s,o]=r.split(":"),a=n.reduce((u,l)=>{let[c,p]=l.split("=");return u[c]=p,u},{});return{action:s,type:o,data:a}}return e}async handleIntent(e){return e.action==="create"&&e.type==="swish/Item"?new Te(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/Item"?new Oe(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemVariant"?new he(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemLists"?new $e(this.swish,this.eventBus,this.options).invoke(e):e.action==="create"&&e.type==="swish/List"?new _e(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/List"?new Ve(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/List"?new Le(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/Home"?new qe(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/ListMenu"?new Be(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/SignIn"?new Ne(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/QuickBuy"?new Ge(this.swish,this.eventBus,this.options).invoke(e):{code:"error",message:"Invalid intent",issues:["Invalid intent"]}}initIntentHooks(){this.eventBus.addEventListener("create:swish/Item",e=>{new je(this.swish,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:swish/ItemLists",e=>{new Ue(this.swish,this.options).invoke(e.detail)})}initIntentWatcher(){ge({selector:"[swish-intent]",onElementFound:i(e=>{let r=this.parseIntent(e.getAttribute("swish-intent"));r&&e.addEventListener("click",()=>{this.invoke(r)})},"onElementFound")}),ge({selector:"a[href*='swish-intent=']",onElementFound:i(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",r=>{if(!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&!r.altKey){let s=new URL(e.href).searchParams.get("swish-intent");if(s){let o=this.parseIntent(s);o&&(r.preventDefault(),r.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),de({fireOnInit:!0,onLocationChange:i(e=>{let r=new URLSearchParams(window.location.search).get("swish-intent");if(r){let n=this.parseIntent(r);if(n){this.invoke(n);let s=new URL(window.location.href);s.searchParams.delete("swish-intent"),window.history.replaceState({},document.title,s.toString())}}},"onLocationChange")})}};var yi=Symbol.for("preact-signals");function He(){if(ee>1)ee--;else{for(var t,e=!1;we!==void 0;){var r=we;for(we=void 0,pt++;r!==void 0;){var n=r.o;if(r.o=void 0,r.f&=-3,!(8&r.f)&&vr(r))try{r.c()}catch(s){e||(t=s,e=!0)}r=n}}if(pt=0,ee--,e)throw t}}i(He,"t");function te(t){if(ee>0)return t();ee++;try{return t()}finally{He()}}i(te,"r");var I=void 0;function yr(t){var e=I;I=void 0;try{return t()}finally{I=e}}i(yr,"n");var we=void 0,ee=0,pt=0,Fe=0;function mr(t){if(I!==void 0){var e=t.n;if(e===void 0||e.t!==I)return e={i:0,S:t,p:I.s,n:void 0,t:I,e:void 0,x:void 0,r:e},I.s!==void 0&&(I.s.n=e),I.s=e,t.n=e,32&I.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=I.s,e.n=void 0,I.s.n=e,I.s=e),e}}i(mr,"e");function q(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(q,"u");q.prototype.brand=yi;q.prototype.h=function(){return!0};q.prototype.S=function(t){var e=this,r=this.t;r!==t&&t.e===void 0&&(t.x=r,this.t=t,r!==void 0?r.e=t:yr(function(){var n;(n=e.W)==null||n.call(e)}))};q.prototype.U=function(t){var e=this;if(this.t!==void 0){var r=t.e,n=t.x;r!==void 0&&(r.x=n,t.e=void 0),n!==void 0&&(n.e=r,t.x=void 0),t===this.t&&(this.t=n,n===void 0&&yr(function(){var s;(s=e.Z)==null||s.call(e)}))}};q.prototype.subscribe=function(t){var e=this;return M(function(){var r=e.value,n=I;I=void 0;try{t(r)}finally{I=n}},{name:"sub"})};q.prototype.valueOf=function(){return this.value};q.prototype.toString=function(){return this.value+""};q.prototype.toJSON=function(){return this.value};q.prototype.peek=function(){var t=I;I=void 0;try{return this.value}finally{I=t}};Object.defineProperty(q.prototype,"value",{get:i(function(){var t=mr(this);return t!==void 0&&(t.i=this.i),this.v},"get"),set:i(function(t){if(t!==this.v){if(pt>100)throw new Error("Cycle detected");this.v=t,this.i++,Fe++,ee++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{He()}}},"set")});function S(t,e){return new q(t,e)}i(S,"d");function vr(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}i(vr,"c");function gr(t){for(var e=t.s;e!==void 0;e=e.n){var r=e.S.n;if(r!==void 0&&(e.r=r),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}i(gr,"a");function Ir(t){for(var e=t.s,r=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):r=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}t.s=r}i(Ir,"l");function ae(t,e){q.call(this,void 0),this.x=t,this.s=void 0,this.g=Fe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(ae,"y");ae.prototype=new q;ae.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Fe))return!0;if(this.g=Fe,this.f|=1,this.i>0&&!vr(this))return this.f&=-2,!0;var t=I;try{gr(this),I=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(r){this.v=r,this.f|=16,this.i++}return I=t,Ir(this),this.f&=-2,!0};ae.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}q.prototype.S.call(this,t)};ae.prototype.U=function(t){if(this.t!==void 0&&(q.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ae.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ae.prototype,"value",{get:i(function(){if(1&this.f)throw new Error("Cycle detected");var t=mr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v},"get")});function U(t,e){return new ae(t,e)}i(U,"w");function br(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ee++;var r=I;I=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,dt(t),n}finally{I=r,He()}}}i(br,"_");function dt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,br(t)}i(dt,"b");function mi(t){if(I!==this)throw new Error("Out-of-order effect");Ir(this),I=t,this.f&=-2,8&this.f&&dt(this),He()}i(mi,"g");function me(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}i(me,"p");me.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};me.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,br(this),gr(this),ee++;var t=I;return I=this,mi.bind(this,t)};me.prototype.N=function(){2&this.f||(this.f|=2,this.o=we,we=this)};me.prototype.d=function(){this.f|=8,1&this.f||dt(this)};me.prototype.dispose=function(){this.d()};function M(t,e){var r=new me(t,e);try{r.c()}catch(s){throw r.d(),s}var n=r.d.bind(r);return n[Symbol.dispose]=n,n}i(M,"E");var vi=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,ft=i(t=>{let e=t.match(vi);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),wr=i(({source:t,onProductUrlChange:e})=>{let r=i(n=>{let s=ft(n);s?.productHandle&&e(s)},"handleChange");if(t instanceof HTMLAnchorElement)return Yt({element:t,onHrefChange:i(n=>r(n),"onHrefChange")});if(t instanceof Location)return de({onLocationChange:i(n=>r(n.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Er=i(t=>e=>{let{productHandle:r,productId:n,variantId:s,itemId:o}=e?.dataset??{},l=!!(n||r)||!!o,c=S({loading:!1,productId:n,variantId:s,itemId:o});if(!l){let p=e instanceof HTMLAnchorElement?e:window.location,h=ft(p.href);h?.productHandle&&h.productHandle!==c.value.productHandle&&(c.value={...c.value,...h,productId:void 0},wr({source:p,onProductUrlChange:i(v=>{c.value={...c.value,...v,productId:v.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return M(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},t.storefront.loadProductId({productHandle:c.value.productHandle}).then(p=>{p.errors&&console.error("Error loading product id",p.errors),c.value={...c.value,productId:p.data?.product?.id?P(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var Cr=i(t=>e=>{let r=U(()=>{let{productId:w,variantId:g,loading:T}=e.value;return!w||T?null:g?`variant:${P(g)}`:`product:${P(w)}`}),n=U(()=>e.value.loading||!!e.value.itemId||!e.value.productId),s=U(()=>({limit:1,query:r.value??void 0})),o=S(!n.value),a=S(null),u=S(!1),l=S(!1),{data:c,loading:p,error:h,refetching:v}=t.state.swishQuery(w=>t.api.items.list(w),{refetch:["item-create","item-update","item-delete"],variables:s,skip:n}),y=S(e.value.itemId??null);M(()=>{te(()=>{if(o.value=p.value,a.value=h.value,!e.value.itemId){let w=c.value?.[0]?.id??null;w!==y.value&&(y.value=w)}})});async function R(){if(!y.value)return;u.value=!0,(await(await t.intents.invoke({action:"delete",type:"swish/Item",data:{itemId:y.value}})).complete).code==="ok"&&(y.value=null),u.value=!1}i(R,"unsave");async function m(){if(!y.value)return;u.value=!0;let g=await(await t.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:y.value}})).complete;g.code==="ok"&&"itemId"in g.data&&(y.value=null),u.value=!1}i(m,"update");async function D(){let{productId:w,variantId:g}=e.value;if(!w)return;u.value=!0,l.value=!0;let _=await(await t.intents.invoke({action:"create",type:"swish/Item",data:{productId:w,variantId:g}})).complete;if(_.code==="ok"){let ve=_.data;y.value=ve.item.id,u.value=!1}else _.code==="error"&&console.warn("Failed to create item",_),te(()=>{u.value=!1,l.value=!1})}i(D,"save");let $=U(()=>o.value||u.value||e.value.loading);M(()=>{l.value&&!u.value&&!v.value&&(l.value=!1)});let k=U(()=>{let w=v.value&&l.value,g=!!y.value,T=!g&&(u.value||w),_=g&&(u.value||w),ve=U(()=>T?"saving":_?"unsaving":g?"saved":"unsaved");return{error:a.value,status:ve.value,savedItemId:y.value,loading:$.value,submitting:u.value,saved:g,saving:T,unsaving:_}});async function z(){$.value||(k.value.saved&&k.value.savedItemId?m():k.value.saved||await D())}return i(z,"toggle"),Object.assign(k,{save:D,unsave:R,update:m,toggle:z})},"itemStateSignal");var xr=i(t=>()=>{let{data:e,loading:r,error:n}=t.state.swishQuery(()=>t.api.items.count(),{refetch:["item-create","item-delete"]}),s=S(0),o=S(!0),a=S(null);return M(()=>{te(()=>{o.value=r.value,a.value=n.value,s.value=e.value?.count??0})}),U(()=>({count:s.value,loading:o.value,error:a.value}))},"itemCountSignal");var Sr=i(t=>(e,r)=>{let n=S(null),s=S(null),o=S(null),a=S(!r?.skip),u=S(!1),l=U(()=>a.value&&u.value);async function c(){if(!r?.skip?.value)try{a.value=!0;let p=await e(r?.variables?.value);te(()=>{o.value="error"in p?p.error:null,n.value="data"in p?p.data:null,s.value="pageInfo"in p?p.pageInfo:null,a.value=!1,u.value=!0})}catch(p){te(()=>{o.value=p,a.value=!1,u.value=!0})}}return i(c,"executeFetch"),M(()=>{if(c(),r?.refetch?.length)return t.events.subscribe(r.refetch,c)}),{data:n,pageInfo:s,error:o,loading:a,refetching:l}},"swishQuerySignals");var ue="GraphQL Client";var ht="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",yt="Response returned unexpected Content-Type:",mt="An unknown error has occurred. The API did not return a data object or any errors in its response.",Qe={json:"application/json",multipart:"multipart/mixed"},vt="X-SDK-Variant",gt="X-SDK-Version",Dr="shopify-graphql-client",kr="1.4.1",ze=1e3,Rr=[429,503],It=/@(defer)\b/i,Ar=`\r
|
|
19
19
|
`,Pr=/boundary="?([^=";]+)"?/i,bt=Ar+Ar;function X(t,e=ue){return t.startsWith(`${e}`)?t:`${e}: ${t}`}i(X,"formatErrorMessage");function Y(t){return t instanceof Error?t.message:JSON.stringify(t)}i(Y,"getErrorMessage");function wt(t){return t instanceof Error&&t.cause?t.cause:void 0}i(wt,"getErrorCause");function Et(t){return t.flatMap(({errors:e})=>e??[])}i(Et,"combineErrors");function We({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${t}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}i(We,"validateRetries");function B(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}i(B,"getKeyValueIfValid");function Ct(t,e){if(t.length===0)return e;let n={[t.pop()]:e};return t.length===0?n:Ct(t,n)}i(Ct,"buildDataObjectByPath");function Or(t,e){return Object.keys(e||{}).reduce((r,n)=>(typeof e[n]=="object"||Array.isArray(e[n]))&&t[n]?(r[n]=Or(t[n],e[n]),r):(r[n]=e[n],r),Array.isArray(t)?[...t]:{...t})}i(Or,"combineObjects");function xt([t,...e]){return e.reduce(Or,{...t})}i(xt,"buildCombinedDataObject");function St({clientLogger:t,customFetchApi:e=fetch,client:r=ue,defaultRetryWaitTime:n=ze,retriableCodes:s=Rr}){let o=i(async(a,u,l)=>{let c=u+1,p=l+1,h;try{if(h=await e(...a),t({type:"HTTP-Response",content:{requestParams:a,response:h}}),!h.ok&&s.includes(h.status)&&c<=p)throw new Error;let v=h?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return v&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:a,deprecationNotice:v}}),h}catch(v){if(c<=p){let y=h?.headers.get("Retry-After");return await gi(y?parseInt(y,10):n),t({type:"HTTP-Retry",content:{requestParams:a,lastResponse:h,retryAttempt:u,maxRetries:l}}),o(a,c,l)}throw new Error(X(`${l>0?`Attempted maximum number of ${l} network retries. Last message - `:""}${Y(v)}`,r))}},"httpFetch");return o}i(St,"generateHttpFetch");async function gi(t){return new Promise(e=>setTimeout(e,t))}i(gi,"sleep");function At({headers:t,url:e,customFetchApi:r=fetch,retries:n=0,logger:s}){We({client:ue,retries:n});let o={headers:t,url:e,retries:n},a=Ii(s),u=St({customFetchApi:r,clientLogger:a,defaultRetryWaitTime:ze}),l=bi(u,o),c=wi(l),p=ki(l);return{config:o,fetch:l,request:c,requestStream:p}}i(At,"createGraphQLClient");function Ii(t){return e=>{t&&t(e)}}i(Ii,"generateClientLogger");async function Lr(t){let{errors:e,data:r,extensions:n}=await t.json();return{...B("data",r),...B("extensions",n),headers:t.headers,...e||!r?{errors:{networkStatusCode:t.status,message:X(e?ht:mt),...B("graphQLErrors",e),response:t}}:{}}}i(Lr,"processJSONResponse");function bi(t,{url:e,headers:r,retries:n}){return async(s,o={})=>{let{variables:a,headers:u,url:l,retries:c,keepalive:p,signal:h}=o,v=JSON.stringify({query:s,variables:a});We({client:ue,retries:c});let y=Object.entries({...r,...u}).reduce((m,[D,$])=>(m[D]=Array.isArray($)?$.join(", "):$.toString(),m),{});return!y[vt]&&!y[gt]&&(y[vt]=Dr,y[gt]=kr),t([l??e,{method:"POST",headers:y,body:v,signal:h,keepalive:p}],1,c??n)}}i(bi,"generateFetch");function wi(t){return async(...e)=>{if(It.test(e[0]))throw new Error(X("This operation will result in a streamable response - use requestStream() instead."));let r=null;try{r=await t(...e);let{status:n,statusText:s}=r,o=r.headers.get("content-type")||"";return r.ok?o.includes(Qe.json)?await Lr(r):{errors:{networkStatusCode:n,message:X(`${yt} ${o}`),response:r}}:{errors:{networkStatusCode:n,message:X(s),response:r}}}catch(n){return{errors:{message:Y(n),...r==null?{}:{networkStatusCode:r.status,response:r}}}}}}i(wi,"generateRequest");async function*Ei(t){let e=new TextDecoder;if(t.body[Symbol.asyncIterator])for await(let r of t.body)yield e.decode(r);else{let r=t.body.getReader(),n;try{for(;!(n=await r.read()).done;)yield e.decode(n.value)}finally{r.cancel()}}}i(Ei,"getStreamBodyIterator");function Ci(t,e){return{async*[Symbol.asyncIterator](){try{let r="";for await(let n of t)if(r+=n,r.indexOf(e)>-1){let s=r.lastIndexOf(e),a=r.slice(0,s).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(bt)+bt.length).trim());a.length>0&&(yield a),r=r.slice(s+e.length),r.trim()==="--"&&(r="")}}catch(r){throw new Error(`Error occured while processing stream payload - ${Y(r)}`)}}}}i(Ci,"readStreamChunk");function xi(t){return{async*[Symbol.asyncIterator](){yield{...await Lr(t),hasNext:!1}}}}i(xi,"createJsonResponseAsyncIterator");function Si(t){return t.map(e=>{try{return JSON.parse(e)}catch(r){throw new Error(`Error in parsing multipart response - ${Y(r)}`)}}).map(e=>{let{data:r,incremental:n,hasNext:s,extensions:o,errors:a}=e;if(!n)return{data:r||{},...B("errors",a),...B("extensions",o),hasNext:s};let u=n.map(({data:l,path:c,errors:p})=>({data:l&&c?Ct(c,l):{},...B("errors",p)}));return{data:u.length===1?u[0].data:xt([...u.map(({data:l})=>l)]),...B("errors",Et(u)),hasNext:s}})}i(Si,"getResponseDataFromChunkBodies");function Ai(t,e){if(t.length>0)throw new Error(ht,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(mt)}i(Ai,"validateResponseData");function Di(t,e){let r=(e??"").match(Pr),n=`--${r?r[1]:"-"}`;if(!t.body?.getReader&&!t.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:t});let s=Ei(t),o={},a;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let l of Ci(s,n)){let c=Si(l);a=c.find(h=>h.extensions)?.extensions??a;let p=Et(c);o=xt([o,...c.map(({data:h})=>h)]),u=c.slice(-1)[0].hasNext,Ai(p,o),yield{...B("data",o),...B("extensions",a),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let l=wt(u);yield{...B("data",o),...B("extensions",a),errors:{message:X(Y(u)),networkStatusCode:t.status,...B("graphQLErrors",l?.graphQLErrors),response:t},hasNext:!1}}}}}i(Di,"createMultipartResponseAsyncInterator");function ki(t){return async(...e)=>{if(!It.test(e[0]))throw new Error(X("This operation does not result in a streamable response - use request() instead."));try{let r=await t(...e),{statusText:n}=r;if(!r.ok)throw new Error(n,{cause:r});let s=r.headers.get("content-type")||"";switch(!0){case s.includes(Qe.json):return xi(r);case s.includes(Qe.multipart):return Di(r,s);default:throw new Error(`${yt} ${s}`,{cause:r})}}catch(r){return{async*[Symbol.asyncIterator](){let n=wt(r);yield{errors:{message:X(Y(r)),...B("networkStatusCode",n?.status),...B("response",n)},hasNext:!1}}}}}}i(ki,"generateRequestStream");function Dt({client:t,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let r=e.trim(),n=r.match(/^https?:/)?r:`https://${r}`,s=new URL(n);return s.protocol="https",s.origin}catch(r){throw new Error(`${t}: a valid store domain ("${e}") must be provided`,{cause:r})}}i(Dt,"validateDomainAndGetStoreUrl");function Xe({client:t,currentSupportedApiVersions:e,apiVersion:r,logger:n}){let s=`${t}: the provided apiVersion ("${r}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!r||typeof r!="string")throw new Error(`${s} is invalid. ${o}`);let a=r.trim();e.includes(a)||(n?n({type:"Unsupported_Api_Version",content:{apiVersion:r,supportedApiVersions:e}}):console.warn(`${s} is likely deprecated or not supported. ${o}`))}i(Xe,"validateApiVersion");function Ke(t){let e=t*3-2;return e===10?e:`0${e}`}i(Ke,"getQuarterMonth");function kt(t,e,r){let n=e-r;return n<=0?`${t-1}-${Ke(n+4)}`:`${t}-${Ke(n)}`}i(kt,"getPrevousVersion");function $r(){let t=new Date,e=t.getUTCMonth(),r=t.getUTCFullYear(),n=Math.floor(e/3+1);return{year:r,quarter:n,version:`${r}-${Ke(n)}`}}i($r,"getCurrentApiVersion");function Rt(){let{year:t,quarter:e,version:r}=$r(),n=e===4?`${t+1}-01`:`${t}-${Ke(e+1)}`;return[kt(t,e,3),kt(t,e,2),kt(t,e,1),r,n,"unstable"]}i(Rt,"getCurrentSupportedApiVersions");function Pt(t){return e=>({...e??{},...t.headers})}i(Pt,"generateGetHeaders");function Tt({getHeaders:t,getApiUrl:e}){return(r,n)=>{let s=[r];if(n&&Object.keys(n).length>0){let{variables:o,apiVersion:a,headers:u,retries:l,signal:c}=n;s.push({...o?{variables:o}:{},...u?{headers:t(u)}:{},...a?{url:e(a)}:{},...l?{retries:l}:{},...c?{signal:c}:{}})}return s}}i(Tt,"generateGetGQLClientParams");var _t="application/json",Vr="storefront-api-client",qr="1.0.9",Br="X-Shopify-Storefront-Access-Token",Nr="Shopify-Storefront-Private-Token",Gr="X-SDK-Variant",jr="X-SDK-Version",Ur="X-SDK-Variant-Source",le="Storefront API Client";function Mr(t){if(t&&typeof window<"u")throw new Error(`${le}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}i(Mr,"validatePrivateAccessTokenUsage");function Fr(t,e){if(!t&&!e)throw new Error(`${le}: a public or private access token must be provided`);if(t&&e)throw new Error(`${le}: only provide either a public or private access token`)}i(Fr,"validateRequiredAccessTokens");function Ot({storeDomain:t,apiVersion:e,publicAccessToken:r,privateAccessToken:n,clientName:s,retries:o=0,customFetchApi:a,logger:u}){let l=Rt(),c=Dt({client:le,storeDomain:t}),p={client:le,currentSupportedApiVersions:l,logger:u};Xe({...p,apiVersion:e}),Fr(r,n),Mr(n);let h=Ri(c,e,p),v={storeDomain:c,apiVersion:e,...r?{publicAccessToken:r}:{privateAccessToken:n},headers:{"Content-Type":_t,Accept:_t,[Gr]:Vr,[jr]:qr,...s?{[Ur]:s}:{},...r?{[Br]:r}:{[Nr]:n}},apiUrl:h(),clientName:s},y=At({headers:v.headers,url:v.apiUrl,retries:o,customFetchApi:a,logger:u}),R=Pt(v),m=Pi(v,h),D=Tt({getHeaders:R,getApiUrl:m});return Object.freeze({config:v,getHeaders:R,getApiUrl:m,fetch:i((...k)=>y.fetch(...D(...k)),"fetch"),request:i((...k)=>y.request(...D(...k)),"request"),requestStream:i((...k)=>y.requestStream(...D(...k)),"requestStream")})}i(Ot,"createStorefrontApiClient");function Ri(t,e,r){return n=>{n&&Xe({...r,apiVersion:n});let s=(n??e).trim();return`${t}/api/${s}/graphql.json`}}i(Ri,"generateApiUrlFormatter");function Pi(t,e){return r=>r?e(r):t.apiUrl}i(Pi,"generateGetApiUrl");var L=`
|
|
20
20
|
fragment productImageFields on Image {
|
|
21
21
|
id
|
|
@@ -456,4 +456,4 @@ Values:
|
|
|
456
456
|
|
|
457
457
|
`);g=Qt.pop()??"";for(let $n of Qt){let Vn=$n.split(`
|
|
458
458
|
`),Ee=[],zt;for(let H of Vn)if(H.startsWith("data:"))Ee.push(H.replace(/^data:\s*/,""));else if(H.startsWith("event:"))zt=H.replace(/^event:\s*/,"");else if(H.startsWith("id:"))h=H.replace(/^id:\s*/,"");else if(H.startsWith("retry:")){let Xt=Number.parseInt(H.replace(/^retry:\s*/,""),10);Number.isNaN(Xt)||(y=Xt)}let re,Wt=!1;if(Ee.length){let H=Ee.join(`
|
|
459
|
-
`);try{re=JSON.parse(H),Wt=!0}catch{re=H}}Wt&&(s&&await s(re),n&&(re=await n(re))),r?.({data:re,event:zt,id:h,retry:y}),Ee.length&&(yield re)}}}finally{m.removeEventListener("abort",T),w.releaseLock()}break}catch($){if(e?.($),a!==void 0&&R>=a)break;let k=Math.min(y*2**(R-1),u??3e4);await v(k)}}},"createStream")()}},"createSseClient"),Bi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),Ni=d(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),Gi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),In=d(({allowReserved:t,explode:e,name:r,style:n,value:s})=>{if(!e){let u=(t?s:s.map(l=>encodeURIComponent(l))).join(Ni(n));switch(n){case"label":return`.${u}`;case"matrix":return`;${r}=${u}`;case"simple":return u;default:return`${r}=${u}`}}let o=Bi(n),a=s.map(u=>n==="label"||n==="simple"?t?u:encodeURIComponent(u):Ze({allowReserved:t,name:r,value:u})).join(o);return n==="label"||n==="matrix"?o+a:a},"serializeArrayParam"),Ze=d(({allowReserved:t,name:e,value:r})=>{if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?r:encodeURIComponent(r)}`},"serializePrimitiveParam"),bn=d(({allowReserved:t,explode:e,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(s).forEach(([p,h])=>{l=[...l,p,t?h:encodeURIComponent(h)]});let c=l.join(",");switch(n){case"form":return`${r}=${c}`;case"label":return`.${c}`;case"matrix":return`;${r}=${c}`;default:return c}}let a=Gi(n),u=Object.entries(s).map(([l,c])=>Ze({allowReserved:t,name:n==="deepObject"?`${r}[${l}]`:l,value:c})).join(a);return n==="label"||n==="matrix"?a+u:u},"serializeObjectParam"),ji=/\{[^{}]+\}/g,Ui=d(({path:t,url:e})=>{let r=e,n=e.match(ji);if(n)for(let s of n){let o=!1,a=s.substring(1,s.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let l=t[a];if(l==null)continue;if(Array.isArray(l)){r=r.replace(s,In({explode:o,name:a,style:u,value:l}));continue}if(typeof l=="object"){r=r.replace(s,bn({explode:o,name:a,style:u,value:l,valueOnly:!0}));continue}if(u==="matrix"){r=r.replace(s,`;${Ze({name:a,value:l})}`);continue}let c=encodeURIComponent(u==="label"?`.${l}`:l);r=r.replace(s,c)}return r},"defaultPathSerializer"),Mi=d(({baseUrl:t,path:e,query:r,querySerializer:n,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,a=(t??"")+o;e&&(a=Ui({path:e,url:a}));let u=r?n(r):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function wn(t){let e=t.body!==void 0;if(e&&t.bodySerializer)return"serializedBody"in t?t.serializedBody!==void 0&&t.serializedBody!==""?t.serializedBody:null:t.body!==""?t.body:null;if(e)return t.body}i(wn,"G");d(wn,"getValidRequestBody");var Fi=d(async(t,e)=>{let r=typeof e=="function"?await e(t):e;if(r)return t.scheme==="bearer"?`Bearer ${r}`:t.scheme==="basic"?`Basic ${btoa(r)}`:r},"getAuthToken"),En=d(({allowReserved:t,array:e,object:r}={})=>d(n=>{let s=[];if(n&&typeof n=="object")for(let o in n){let a=n[o];if(a!=null)if(Array.isArray(a)){let u=In({allowReserved:t,explode:!0,name:o,style:"form",value:a,...e});u&&s.push(u)}else if(typeof a=="object"){let u=bn({allowReserved:t,explode:!0,name:o,style:"deepObject",value:a,...r});u&&s.push(u)}else{let u=Ze({allowReserved:t,name:o,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),Hi=d(t=>{var e;if(!t)return"stream";let r=(e=t.split(";")[0])==null?void 0:e.trim();if(r){if(r.startsWith("application/json")||r.endsWith("+json"))return"json";if(r==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>r.startsWith(n)))return"blob";if(r.startsWith("text/"))return"text"}},"getParseAs"),Qi=d((t,e)=>{var r,n;return e?!!(t.headers.has(e)||(r=t.query)!=null&&r[e]||(n=t.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),zi=d(async({security:t,...e})=>{for(let r of t){if(Qi(e,r.name))continue;let n=await Fi(r,e.auth);if(!n)continue;let s=r.name??"Authorization";switch(r.in){case"query":e.query||(e.query={}),e.query[s]=n;break;case"cookie":e.headers.append("Cookie",`${s}=${n}`);break;case"header":default:e.headers.set(s,n);break}}},"setAuthParams"),mn=d(t=>Mi({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:En(t.querySerializer),url:t.url}),"buildUrl"),vn=d((t,e)=>{var r;let n={...t,...e};return(r=n.baseUrl)!=null&&r.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Cn(t.headers,e.headers),n},"mergeConfigs"),Wi=d(t=>{let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e},"headersEntries"),Cn=d((...t)=>{let e=new Headers;for(let r of t){if(!r)continue;let n=r instanceof Headers?Wi(r):Object.entries(r);for(let[s,o]of n)if(o===null)e.delete(s);else if(Array.isArray(o))for(let a of o)e.append(s,a);else o!==void 0&&e.set(s,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),xn=class{static{i(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let r=this.getInterceptorIndex(e);this.fns[r]&&(this.fns[r]=null)}exists(e){let r=this.getInterceptorIndex(e);return!!this.fns[r]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,r){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=r,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(xn,"Interceptors");var Nt=xn,Xi=d(()=>({error:new Nt,request:new Nt,response:new Nt}),"createInterceptors"),Ki=En({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Yi={"Content-Type":"application/json"},Je=d((t={})=>({...$i,headers:Yi,parseAs:"auto",querySerializer:Ki,...t}),"createConfig"),Gt=d((t={})=>{let e=vn(Je(),t),r=d(()=>({...e}),"getConfig"),n=d(c=>(e=vn(e,c),r()),"setConfig"),s=Xi(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:Cn(e.headers,c.headers),serializedBody:void 0};p.security&&await zi({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let h=mn(p);return{opts:p,url:h}},"beforeRequest"),a=d(async c=>{let{opts:p,url:h}=await o(c),v={redirect:"follow",...p,body:wn(p)},y=new Request(h,v);for(let g of s.request.fns)g&&(y=await g(y,p));let R=p.fetch,m=await R(y);for(let g of s.response.fns)g&&(m=await g(m,y,p));let D={request:y,response:m};if(m.ok){let g=(p.parseAs==="auto"?Hi(m.headers.get("Content-Type")):p.parseAs)??"json";if(m.status===204||m.headers.get("Content-Length")==="0"){let _;switch(g){case"arrayBuffer":case"blob":case"text":_=await m[g]();break;case"formData":_=new FormData;break;case"stream":_=m.body;break;case"json":default:_={};break}return p.responseStyle==="data"?_:{data:_,...D}}let T;switch(g){case"arrayBuffer":case"blob":case"formData":case"json":case"text":T=await m[g]();break;case"stream":return p.responseStyle==="data"?m.body:{data:m.body,...D}}return g==="json"&&(p.responseValidator&&await p.responseValidator(T),p.responseTransformer&&(T=await p.responseTransformer(T))),p.responseStyle==="data"?T:{data:T,...D}}let $=await m.text(),k;try{k=JSON.parse($)}catch{}let z=k??$,w=z;for(let g of s.error.fns)g&&(w=await g(z,m,y,p));if(w=w||{},p.throwOnError)throw w;return p.responseStyle==="data"?void 0:{error:w,...D}},"request"),u=d(c=>p=>a({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:h,url:v}=await o(p);return qi({...h,body:h.body,headers:h.headers,method:c,onRequest:d(async(y,R)=>{let m=new Request(y,R);for(let D of s.request.fns)D&&(m=await D(m,h));return m},"onRequest"),url:v})},"makeSseFn");return{buildUrl:mn,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:r,head:u("HEAD"),interceptors:s,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:n,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:u("TRACE")}},"createClient"),A=Gt(Je({baseUrl:"https://swish.app/api/2026-01"})),Ji=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),Zi=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),es=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),ts=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),rs=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),ns=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),is=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),ss=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),os=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),as=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),us=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),ls=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),cs=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),ps=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),ds=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),fs=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),hs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...t}),"profileControllerCustomerAccountsVersion"),ys=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),ms=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),vs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...t}),"ordersControllerFind"),gs=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...t}),"ordersControllerFindOne"),jt="2026-01",gn="/apps/wishlist/api",Sn=d(t=>new Is(t),"createApiClient"),An=class{static{i(this,"H")}constructor(e){this.useProxy=!1,this.version=jt,this.items={list:d(n=>this.handlePaginatedRequest(as({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(us({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),delete:d(n=>this.handleRequest(os({body:{itemIds:n},client:this.useProxy?this.proxyClient:this.directClient})),"delete"),findById:d(n=>this.handleRequest(ps({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(ds({body:s,path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(cs({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),setListsById:d((n,s)=>this.handleRequest(fs({body:{listIds:s},path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(ls({client:this.useProxy?this.proxyClient:this.directClient})),"count")},this.lists={list:d(n=>this.handlePaginatedRequest(Ji({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(Zi({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),findById:d(n=>this.handleRequest(ts({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(rs({body:s,path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(es({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),orderItems:d((n,s)=>this.handleRequest(ns({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"orderItems"),addItemsToList:d((n,s)=>this.handleRequest(is({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"addItemsToList"),removeItemFromList:d((n,s)=>this.handleRequest(ss({path:{listId:n,itemId:s},client:this.useProxy?this.proxyClient:this.directClient})),"removeItemFromList")},this.profiles={customerAccountsVersion:d(()=>this.handleRequest(hs({client:this.useProxy?this.proxyClient:this.directClient})),"customerAccountsVersion"),createToken:d((n={},s)=>this.handleRequest(ms({body:n,client:this.useProxy||s!=null&&s.useProxy?this.proxyClient:this.directClient})),"createToken"),identify:d(n=>this.handleRequest(ys({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"identify")},this.orders={list:d(n=>this.handlePaginatedRequest(vs({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),findById:d(n=>this.handleRequest(gs({path:{orderId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById")},this.handleRequest=d(async n=>{let{data:s,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:s?.data}},"handleRequest"),this.handlePaginatedRequest=d(async n=>{var s;let{data:o,error:a}=await n;return a!=null&&a.error?{error:a.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((s=o?.data)==null?void 0:s.length)??0}}},"handlePaginatedRequest");var r;this.profile=e.profile,(r=e.config)!=null&&r.version&&(this.version=e.config.version),this.directClient=Gt(Je({baseUrl:`https://swish.app/api/${this.version}`})),this.proxyClient=Gt(Je({baseUrl:gn})),e.authToken&&(this.authToken=e.authToken),e.config&&this.setConfig(e.config),e.requestInterceptor&&(this.proxyClient.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&(this.proxyClient.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),this.proxyClient.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig({proxyBaseUrl:e=gn,baseUrl:r,useProxy:n=!1,...s}){this.useProxy=n,this.proxyClient.setConfig({...s,baseUrl:e}),this.directClient.setConfig({...s})}proxyRequestInterceptor(e){return this.profile&&(e.headers.set("Profile",this.profile),e.headers.set("Swish-Api-Version",this.version)),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(An,"SwishClient");var Is=An;var Dn=i(t=>t?JSON.parse(atob(t.split(".")[1])):null,"getTokenData"),kn=i((t,e=60)=>{let r=Dn(t);return r?r.exp&&r.exp<Date.now()/1e3+e:!1},"isTokenExpired"),Rn=i(t=>{let e=Dn(t);return e?e.sub.startsWith("gid://shopify/Customer/"):!1},"isCustomerToken");var On=Fn(_n(),1);var Ln=i(t=>new On.default(async e=>{let r=[...new Set(e)].sort((s,o)=>s.localeCompare(o)),n=await t.items.list({query:r.join(" "),limit:200});return"error"in n?(console.error("Failed to load items",n.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(s=>{let o=n.data.find(a=>s===`variant:${a.variantId}`||s===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:i(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var et=class{static{i(this,"SwishApi")}constructor(e,r){this.config=e,this.cache=new K("swish-api","max-age=60, stale-while-revalidate=3600",r+(e.version??jt)),this.cache.cleanupExpiredEntries().catch(o=>{console.warn("Swish API cache initialization cleanup error:",o)});let n=this.config.loadProfile?.(),s=this.config.loadAuthToken?.();this.apiClient=Sn({profile:n,authToken:s,proxyMode:this.config.proxyMode,config:{...e,fetch:i((o,a)=>(o instanceof Request?o.method:a?.method??"GET")==="GET"?this.cache.fetchWithCache(o,a):fetch(o,a),"fetch")},requestInterceptor:i(async o=>{let a=new URL(o.url,window.location.origin),u=this.config.proxyBaseUrl??"/apps/wishlist/api",l=a.pathname==="/profiles/token";return!a.pathname.startsWith(u)&&!l&&await this.bootstrapAuth(),o},"requestInterceptor"),responseInterceptor:i(async(o,a)=>(this.processProfileHeader(o),a.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(o,a),o),"responseInterceptor")}),this.itemsLoader=Ln(this)}async bootstrapAuth(){if(this._bootstrapAuthPromise)return this._bootstrapAuthPromise;this._bootstrapAuthPromise=(async()=>{let e=this.config.loadAuthToken?.();if(e)try{if(kn(e,60))throw new Error("TOKEN_EXPIRED")}catch(o){(!(o instanceof Error)||o.message!=="TOKEN_EXPIRED")&&console.error("Failed to decode cached auth token",{cause:o}),this.config.deleteAuthToken?.(),e=void 0}if(e){this.apiClient.setAuthToken(e);return}let r=this.apiClient.getProfile(),n=this.config.customerId,s=await this.apiClient.profiles.createToken({customer:n,session:r},{useProxy:!0});if("error"in s){console.error("Failed to bootstrap auth with error",s.error);return}if(!s.data?.token){console.error("Failed to bootstrap auth with no token");return}await this.config.storeAuthToken?.(s.data.token),this.apiClient.setAuthToken(s.data.token)})();try{return await this._bootstrapAuthPromise}finally{this._bootstrapAuthPromise=void 0}}processProfileHeader(e){let r=e.headers.get("Set-Profile");r?(this.apiClient.setProfile(r),this.config.storeProfile?.(r)):r===""&&this.config.deleteProfile?.()}get items(){return{...this.apiClient.items,list:i(async(e,r)=>{if(!f.customer.id&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(r?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let n=e.query.split(" ");n.length>1&&console.warn("Batching will only support one query parameter");let s=n[0];if(!s.match(/^product:\d+$/)&&!s.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(s)}return this.apiClient.items.list(e)},"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get orders(){return{...this.apiClient.orders,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.orders.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.orders.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var tt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{i(this,"SwishApiPublisher")}async processFetchResponse(e,r){try{let n=this.getEventName(r.method,e.status,r.url);if(!n)return;let s=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{s=JSON.parse(s).data}catch(o){console.warn(o)}this.eventBus.publish(n,s)}catch(n){console.warn(n)}}getEventName(e,r,n){e=e.toUpperCase();let s=new URL(n).pathname;return e==="GET"||r<200||r>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,l]=a.split(" ");return u!==e?!1:new RegExp(l).test(s)})?.[1]}};var rt=class extends HTMLElement{constructor(){super();this.getComponentRef=i(()=>this.componentRef,"getComponentRef");this.setComponentRef=i(r=>{this.componentRef=r},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let r=this.querySelector("template");r&&this.shadowRoot&&(this.shadowRoot.appendChild(r.content),r.remove())}static{i(this,"SwishUiElement")}};var Rs="0.60.0",f={customer:{id:null,email:null,firstName:null,lastName:null,b2b:null},localization:{country:"",language:"",market:0},routes:{accountUrl:"/account",accountLoginUrl:"/account/login",rootUrl:"/"}},Lc=i(async t=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}try{let n=document.getElementById("swishEmbedData");if(!n)throw new Error("Swish embed data not found");Object.assign(f,JSON.parse(n.innerText))}catch(n){console.warn("Could not read Swish embed data.",{cause:n})}let e=t.proxy?.baseUrl??"/apps/wishlist",r=new Ht({loadProfile:i(()=>localStorage.getItem("swish-profile")??void 0,"loadProfile"),storeProfile:i(n=>localStorage.setItem("swish-profile",n),"storeProfile"),deleteProfile:i(()=>localStorage.removeItem("swish-profile"),"deleteProfile"),loadAuthToken:i(()=>sessionStorage.getItem("swish-token")??void 0,"loadAuthToken"),storeAuthToken:i(n=>sessionStorage.setItem("swish-token",n),"storeAuthToken"),deleteAuthToken:i(()=>sessionStorage.removeItem("swish-token"),"deleteAuthToken"),proxy:{baseUrl:e},ui:t.ui,storefront:t.storefront,swishApi:t.swishApi});try{let n=localStorage.getItem("swish-token"),s=n&&Rn(n),o=!!f.customer.id;o!==s&&localStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await r.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=r,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e,market:f.localization.market,country:f.localization.country,rootUrl:f.routes.rootUrl}),r},"swishApp"),Ht=class{constructor(e){this.ui={hideModal:nr,showModal:Q,initShopBridge:hr,showToast:pr,initListDetailPage:cr};this.dom={createElementLocator:ge,createQueryParamsObserver:de};this.state={itemContext:Er(this),itemState:Cr(this),itemCount:xr(this),swishQuery:Sr(this),effect:M,signal:S,computed:U};this.options=e,this.events=new Se;let r={proxyBaseUrl:`${this.options.proxy.baseUrl}/api`,...this.options.swishApi??{}};this.swishApiPublisher=new tt(this.events);let n=[Rs,e.ui?.version].join("-");this.swishApi=new et({...r,version:r.version,customerId:f.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse,loadProfile:e.loadProfile,storeProfile:e.storeProfile,deleteProfile:e.deleteProfile,loadAuthToken:e.loadAuthToken,storeAuthToken:e.storeAuthToken,deleteAuthToken:e.deleteAuthToken},n),this.ajaxApiPublisher=new xe(this.events),this.ajaxApi=new Ce({storeDomain:this.options.storefront.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ye(this.options.storefront),this.options.ui&&rr(this.options.ui),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",rt),this.intents=new Me(this,{allowSaveWithoutVariant:!1,deleteSavedItemsWithoutEdit:!1,showToastAfterSave:!0,showToastAfterDelete:!0})}static{i(this,"SwishApp")}get customer(){return f.customer}get localization(){return f.localization}get shopifyRoutes(){return f.routes}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.options.storefront.storeDomain}`}};export{Ht as SwishApp,Rs as VERSION,Lc as swishApp,f as swishEmbedData};
|
|
459
|
+
`);try{re=JSON.parse(H),Wt=!0}catch{re=H}}Wt&&(s&&await s(re),n&&(re=await n(re))),r?.({data:re,event:zt,id:h,retry:y}),Ee.length&&(yield re)}}}finally{m.removeEventListener("abort",T),w.releaseLock()}break}catch($){if(e?.($),a!==void 0&&R>=a)break;let k=Math.min(y*2**(R-1),u??3e4);await v(k)}}},"createStream")()}},"createSseClient"),Bi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),Ni=d(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),Gi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),In=d(({allowReserved:t,explode:e,name:r,style:n,value:s})=>{if(!e){let u=(t?s:s.map(l=>encodeURIComponent(l))).join(Ni(n));switch(n){case"label":return`.${u}`;case"matrix":return`;${r}=${u}`;case"simple":return u;default:return`${r}=${u}`}}let o=Bi(n),a=s.map(u=>n==="label"||n==="simple"?t?u:encodeURIComponent(u):Ze({allowReserved:t,name:r,value:u})).join(o);return n==="label"||n==="matrix"?o+a:a},"serializeArrayParam"),Ze=d(({allowReserved:t,name:e,value:r})=>{if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?r:encodeURIComponent(r)}`},"serializePrimitiveParam"),bn=d(({allowReserved:t,explode:e,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(s).forEach(([p,h])=>{l=[...l,p,t?h:encodeURIComponent(h)]});let c=l.join(",");switch(n){case"form":return`${r}=${c}`;case"label":return`.${c}`;case"matrix":return`;${r}=${c}`;default:return c}}let a=Gi(n),u=Object.entries(s).map(([l,c])=>Ze({allowReserved:t,name:n==="deepObject"?`${r}[${l}]`:l,value:c})).join(a);return n==="label"||n==="matrix"?a+u:u},"serializeObjectParam"),ji=/\{[^{}]+\}/g,Ui=d(({path:t,url:e})=>{let r=e,n=e.match(ji);if(n)for(let s of n){let o=!1,a=s.substring(1,s.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let l=t[a];if(l==null)continue;if(Array.isArray(l)){r=r.replace(s,In({explode:o,name:a,style:u,value:l}));continue}if(typeof l=="object"){r=r.replace(s,bn({explode:o,name:a,style:u,value:l,valueOnly:!0}));continue}if(u==="matrix"){r=r.replace(s,`;${Ze({name:a,value:l})}`);continue}let c=encodeURIComponent(u==="label"?`.${l}`:l);r=r.replace(s,c)}return r},"defaultPathSerializer"),Mi=d(({baseUrl:t,path:e,query:r,querySerializer:n,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,a=(t??"")+o;e&&(a=Ui({path:e,url:a}));let u=r?n(r):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function wn(t){let e=t.body!==void 0;if(e&&t.bodySerializer)return"serializedBody"in t?t.serializedBody!==void 0&&t.serializedBody!==""?t.serializedBody:null:t.body!==""?t.body:null;if(e)return t.body}i(wn,"G");d(wn,"getValidRequestBody");var Fi=d(async(t,e)=>{let r=typeof e=="function"?await e(t):e;if(r)return t.scheme==="bearer"?`Bearer ${r}`:t.scheme==="basic"?`Basic ${btoa(r)}`:r},"getAuthToken"),En=d(({allowReserved:t,array:e,object:r}={})=>d(n=>{let s=[];if(n&&typeof n=="object")for(let o in n){let a=n[o];if(a!=null)if(Array.isArray(a)){let u=In({allowReserved:t,explode:!0,name:o,style:"form",value:a,...e});u&&s.push(u)}else if(typeof a=="object"){let u=bn({allowReserved:t,explode:!0,name:o,style:"deepObject",value:a,...r});u&&s.push(u)}else{let u=Ze({allowReserved:t,name:o,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),Hi=d(t=>{var e;if(!t)return"stream";let r=(e=t.split(";")[0])==null?void 0:e.trim();if(r){if(r.startsWith("application/json")||r.endsWith("+json"))return"json";if(r==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>r.startsWith(n)))return"blob";if(r.startsWith("text/"))return"text"}},"getParseAs"),Qi=d((t,e)=>{var r,n;return e?!!(t.headers.has(e)||(r=t.query)!=null&&r[e]||(n=t.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),zi=d(async({security:t,...e})=>{for(let r of t){if(Qi(e,r.name))continue;let n=await Fi(r,e.auth);if(!n)continue;let s=r.name??"Authorization";switch(r.in){case"query":e.query||(e.query={}),e.query[s]=n;break;case"cookie":e.headers.append("Cookie",`${s}=${n}`);break;case"header":default:e.headers.set(s,n);break}}},"setAuthParams"),mn=d(t=>Mi({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:En(t.querySerializer),url:t.url}),"buildUrl"),vn=d((t,e)=>{var r;let n={...t,...e};return(r=n.baseUrl)!=null&&r.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Cn(t.headers,e.headers),n},"mergeConfigs"),Wi=d(t=>{let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e},"headersEntries"),Cn=d((...t)=>{let e=new Headers;for(let r of t){if(!r)continue;let n=r instanceof Headers?Wi(r):Object.entries(r);for(let[s,o]of n)if(o===null)e.delete(s);else if(Array.isArray(o))for(let a of o)e.append(s,a);else o!==void 0&&e.set(s,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),xn=class{static{i(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let r=this.getInterceptorIndex(e);this.fns[r]&&(this.fns[r]=null)}exists(e){let r=this.getInterceptorIndex(e);return!!this.fns[r]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,r){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=r,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(xn,"Interceptors");var Nt=xn,Xi=d(()=>({error:new Nt,request:new Nt,response:new Nt}),"createInterceptors"),Ki=En({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Yi={"Content-Type":"application/json"},Je=d((t={})=>({...$i,headers:Yi,parseAs:"auto",querySerializer:Ki,...t}),"createConfig"),Gt=d((t={})=>{let e=vn(Je(),t),r=d(()=>({...e}),"getConfig"),n=d(c=>(e=vn(e,c),r()),"setConfig"),s=Xi(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:Cn(e.headers,c.headers),serializedBody:void 0};p.security&&await zi({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let h=mn(p);return{opts:p,url:h}},"beforeRequest"),a=d(async c=>{let{opts:p,url:h}=await o(c),v={redirect:"follow",...p,body:wn(p)},y=new Request(h,v);for(let g of s.request.fns)g&&(y=await g(y,p));let R=p.fetch,m=await R(y);for(let g of s.response.fns)g&&(m=await g(m,y,p));let D={request:y,response:m};if(m.ok){let g=(p.parseAs==="auto"?Hi(m.headers.get("Content-Type")):p.parseAs)??"json";if(m.status===204||m.headers.get("Content-Length")==="0"){let _;switch(g){case"arrayBuffer":case"blob":case"text":_=await m[g]();break;case"formData":_=new FormData;break;case"stream":_=m.body;break;case"json":default:_={};break}return p.responseStyle==="data"?_:{data:_,...D}}let T;switch(g){case"arrayBuffer":case"blob":case"formData":case"json":case"text":T=await m[g]();break;case"stream":return p.responseStyle==="data"?m.body:{data:m.body,...D}}return g==="json"&&(p.responseValidator&&await p.responseValidator(T),p.responseTransformer&&(T=await p.responseTransformer(T))),p.responseStyle==="data"?T:{data:T,...D}}let $=await m.text(),k;try{k=JSON.parse($)}catch{}let z=k??$,w=z;for(let g of s.error.fns)g&&(w=await g(z,m,y,p));if(w=w||{},p.throwOnError)throw w;return p.responseStyle==="data"?void 0:{error:w,...D}},"request"),u=d(c=>p=>a({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:h,url:v}=await o(p);return qi({...h,body:h.body,headers:h.headers,method:c,onRequest:d(async(y,R)=>{let m=new Request(y,R);for(let D of s.request.fns)D&&(m=await D(m,h));return m},"onRequest"),url:v})},"makeSseFn");return{buildUrl:mn,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:r,head:u("HEAD"),interceptors:s,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:n,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:u("TRACE")}},"createClient"),A=Gt(Je({baseUrl:"https://swish.app/api/2026-01"})),Ji=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),Zi=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),es=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),ts=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),rs=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),ns=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),is=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),ss=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),os=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),as=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),us=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),ls=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),cs=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),ps=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),ds=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),fs=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),hs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...t}),"profileControllerCustomerAccountsVersion"),ys=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),ms=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),vs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...t}),"ordersControllerFind"),gs=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...t}),"ordersControllerFindOne"),jt="2026-01",gn="/apps/wishlist/api",Sn=d(t=>new Is(t),"createApiClient"),An=class{static{i(this,"H")}constructor(e){this.useProxy=!1,this.version=jt,this.items={list:d(n=>this.handlePaginatedRequest(as({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(us({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),delete:d(n=>this.handleRequest(os({body:{itemIds:n},client:this.useProxy?this.proxyClient:this.directClient})),"delete"),findById:d(n=>this.handleRequest(ps({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(ds({body:s,path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(cs({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),setListsById:d((n,s)=>this.handleRequest(fs({body:{listIds:s},path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(ls({client:this.useProxy?this.proxyClient:this.directClient})),"count")},this.lists={list:d(n=>this.handlePaginatedRequest(Ji({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(Zi({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),findById:d(n=>this.handleRequest(ts({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(rs({body:s,path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(es({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),orderItems:d((n,s)=>this.handleRequest(ns({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"orderItems"),addItemsToList:d((n,s)=>this.handleRequest(is({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"addItemsToList"),removeItemFromList:d((n,s)=>this.handleRequest(ss({path:{listId:n,itemId:s},client:this.useProxy?this.proxyClient:this.directClient})),"removeItemFromList")},this.profiles={customerAccountsVersion:d(()=>this.handleRequest(hs({client:this.useProxy?this.proxyClient:this.directClient})),"customerAccountsVersion"),createToken:d((n={},s)=>this.handleRequest(ms({body:n,client:this.useProxy||s!=null&&s.useProxy?this.proxyClient:this.directClient})),"createToken"),identify:d(n=>this.handleRequest(ys({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"identify")},this.orders={list:d(n=>this.handlePaginatedRequest(vs({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),findById:d(n=>this.handleRequest(gs({path:{orderId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById")},this.handleRequest=d(async n=>{let{data:s,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:s?.data}},"handleRequest"),this.handlePaginatedRequest=d(async n=>{var s;let{data:o,error:a}=await n;return a!=null&&a.error?{error:a.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((s=o?.data)==null?void 0:s.length)??0}}},"handlePaginatedRequest");var r;this.profile=e.profile,(r=e.config)!=null&&r.version&&(this.version=e.config.version),this.directClient=Gt(Je({baseUrl:`https://swish.app/api/${this.version}`})),this.proxyClient=Gt(Je({baseUrl:gn})),e.authToken&&(this.authToken=e.authToken),e.config&&this.setConfig(e.config),e.requestInterceptor&&(this.proxyClient.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&(this.proxyClient.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),this.proxyClient.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig({proxyBaseUrl:e=gn,baseUrl:r,useProxy:n=!1,...s}){this.useProxy=n,this.proxyClient.setConfig({...s,baseUrl:e}),this.directClient.setConfig({...s})}proxyRequestInterceptor(e){return this.profile&&(e.headers.set("Profile",this.profile),e.headers.set("Swish-Api-Version",this.version)),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(An,"SwishClient");var Is=An;var Dn=i(t=>t?JSON.parse(atob(t.split(".")[1])):null,"getTokenData"),kn=i((t,e=60)=>{let r=Dn(t);return r?r.exp&&r.exp<Date.now()/1e3+e:!1},"isTokenExpired"),Rn=i(t=>{let e=Dn(t);return e?e.sub.startsWith("gid://shopify/Customer/"):!1},"isCustomerToken");var On=Fn(_n(),1);var Ln=i(t=>new On.default(async e=>{let r=[...new Set(e)].sort((s,o)=>s.localeCompare(o)),n=await t.items.list({query:r.join(" "),limit:200});return"error"in n?(console.error("Failed to load items",n.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(s=>{let o=n.data.find(a=>s===`variant:${a.variantId}`||s===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:i(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var et=class{static{i(this,"SwishApi")}constructor(e,r){this.config=e,this.cache=new K("swish-api","max-age=60, stale-while-revalidate=3600",r+(e.version??jt)),this.cache.cleanupExpiredEntries().catch(o=>{console.warn("Swish API cache initialization cleanup error:",o)});let n=this.config.loadProfile?.(),s=this.config.loadAuthToken?.();this.apiClient=Sn({profile:n,authToken:s,proxyMode:this.config.proxyMode,config:{...e,fetch:i((o,a)=>(o instanceof Request?o.method:a?.method??"GET")==="GET"?this.cache.fetchWithCache(o,a):fetch(o,a),"fetch")},requestInterceptor:i(async o=>{let a=new URL(o.url,window.location.origin),u=this.config.proxyBaseUrl??"/apps/wishlist/api",l=a.pathname==="/profiles/token";return!a.pathname.startsWith(u)&&!l&&await this.bootstrapAuth(),o},"requestInterceptor"),responseInterceptor:i(async(o,a)=>(this.processProfileHeader(o),a.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(o,a),o),"responseInterceptor")}),this.itemsLoader=Ln(this)}async bootstrapAuth(){if(this._bootstrapAuthPromise)return this._bootstrapAuthPromise;this._bootstrapAuthPromise=(async()=>{let e=this.config.loadAuthToken?.();if(e)try{if(kn(e,60))throw new Error("TOKEN_EXPIRED")}catch(o){(!(o instanceof Error)||o.message!=="TOKEN_EXPIRED")&&console.error("Failed to decode cached auth token",{cause:o}),this.config.deleteAuthToken?.(),e=void 0}if(e){this.apiClient.setAuthToken(e);return}let r=this.apiClient.getProfile(),n=this.config.customerId,s=await this.apiClient.profiles.createToken({customer:n,session:r},{useProxy:!0});if("error"in s){console.error("Failed to bootstrap auth with error",s.error);return}if(!s.data?.token){console.error("Failed to bootstrap auth with no token");return}await this.config.storeAuthToken?.(s.data.token),this.apiClient.setAuthToken(s.data.token)})();try{return await this._bootstrapAuthPromise}finally{this._bootstrapAuthPromise=void 0}}processProfileHeader(e){let r=e.headers.get("Set-Profile");r?(this.apiClient.setProfile(r),this.config.storeProfile?.(r)):r===""&&this.config.deleteProfile?.()}get items(){return{...this.apiClient.items,list:i(async(e,r)=>{if(!f.customer.id&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(r?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let n=e.query.split(" ");n.length>1&&console.warn("Batching will only support one query parameter");let s=n[0];if(!s.match(/^product:\d+$/)&&!s.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(s)}return this.apiClient.items.list(e)},"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get orders(){return{...this.apiClient.orders,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.orders.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.orders.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var tt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{i(this,"SwishApiPublisher")}async processFetchResponse(e,r){try{let n=this.getEventName(r.method,e.status,r.url);if(!n)return;let s=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{s=JSON.parse(s).data}catch(o){console.warn(o)}this.eventBus.publish(n,s)}catch(n){console.warn(n)}}getEventName(e,r,n){e=e.toUpperCase();let s=new URL(n).pathname;return e==="GET"||r<200||r>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,l]=a.split(" ");return u!==e?!1:new RegExp(l).test(s)})?.[1]}};var rt=class extends HTMLElement{constructor(){super();this.getComponentRef=i(()=>this.componentRef,"getComponentRef");this.setComponentRef=i(r=>{this.componentRef=r},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let r=this.querySelector("template");r&&this.shadowRoot&&(this.shadowRoot.appendChild(r.content),r.remove())}static{i(this,"SwishUiElement")}};var Rs="0.61.0",f={customer:{id:null,email:null,firstName:null,lastName:null,b2b:null},localization:{country:"",language:"",market:0},routes:{accountUrl:"/account",accountLoginUrl:"/account/login",rootUrl:"/"}},Lc=i(async t=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}try{let n=document.getElementById("swishEmbedData");if(!n)throw new Error("Swish embed data not found");Object.assign(f,JSON.parse(n.innerText))}catch(n){console.warn("Could not read Swish embed data.",{cause:n})}let e=t.proxy?.baseUrl??"/apps/wishlist",r=new Ht({loadProfile:i(()=>localStorage.getItem("swish-profile")??void 0,"loadProfile"),storeProfile:i(n=>localStorage.setItem("swish-profile",n),"storeProfile"),deleteProfile:i(()=>localStorage.removeItem("swish-profile"),"deleteProfile"),loadAuthToken:i(()=>sessionStorage.getItem("swish-token")??void 0,"loadAuthToken"),storeAuthToken:i(n=>sessionStorage.setItem("swish-token",n),"storeAuthToken"),deleteAuthToken:i(()=>sessionStorage.removeItem("swish-token"),"deleteAuthToken"),proxy:{baseUrl:e},ui:t.ui,storefront:t.storefront,swishApi:t.swishApi});try{let n=localStorage.getItem("swish-token"),s=n&&Rn(n),o=!!f.customer.id;o!==s&&localStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await r.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=r,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e,market:f.localization.market,country:f.localization.country,rootUrl:f.routes.rootUrl}),r},"swishApp"),Ht=class{constructor(e){this.ui={hideModal:nr,showModal:Q,initShopBridge:hr,showToast:pr,initListDetailPage:cr};this.dom={createElementLocator:ge,createQueryParamsObserver:de};this.state={itemContext:Er(this),itemState:Cr(this),itemCount:xr(this),swishQuery:Sr(this),effect:M,signal:S,computed:U};this.options=e,this.events=new Se;let r={proxyBaseUrl:`${this.options.proxy.baseUrl}/api`,...this.options.swishApi??{}};this.swishApiPublisher=new tt(this.events);let n=[Rs,e.ui?.version].join("-");this.swishApi=new et({...r,version:r.version,customerId:f.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse,loadProfile:e.loadProfile,storeProfile:e.storeProfile,deleteProfile:e.deleteProfile,loadAuthToken:e.loadAuthToken,storeAuthToken:e.storeAuthToken,deleteAuthToken:e.deleteAuthToken},n),this.ajaxApiPublisher=new xe(this.events),this.ajaxApi=new Ce({storeDomain:this.options.storefront.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ye(this.options.storefront),this.options.ui&&rr(this.options.ui),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",rt),this.intents=new Me(this,{allowSaveWithoutVariant:!1,deleteSavedItemsWithoutEdit:!1,showToastAfterSave:!0,showToastAfterDelete:!0})}static{i(this,"SwishApp")}get customer(){return f.customer}get localization(){return f.localization}get shopifyRoutes(){return f.routes}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.options.storefront.storeDomain}`}};export{Ht as SwishApp,Rs as VERSION,Lc as swishApp,f as swishEmbedData};
|